I have an ajax call that sends some data (first name, last name, email) to a php file which is supposed to email me. The data I'm sending exists, I've checked that. When I run it however I am getting a blank error. Am I missing something easy? Any advice?
$.ajax({
type: 'POST',
url: 'signup.php',
data: { first_name: 'first_name', last_name: 'last_name', email_address: 'email_address'},
contentType: 'application/json; charset=utf-8',
async: false,
success: (function() {
alert("Successful");
}),
error: (function(data){
})
});
In signup.php I have the following:
<?php
// Get User Information From AJAX Post
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_address = $_POST['email_address'];
//Set Email Information
$to = 'example@example.com';
$subject = 'New User';
$message = "New User
$first_name
$last_name
$email_address";
$headers = 'From: example@example.com'. "
";
//Send Email
mail($to, $subject, $message, $headers);
?>
Your problems are
I suggest not posting json, but normal url encoded form data, that way $_POST
will be populated with the values sent.
If you pass an object in the data field it will be encoded for you so you wont have to doing 'first_name='+encodeURIComponent(first_name)+'&last_name='+encodeURIComponent(last_name)+'&email_address'+encodeURIComponent(email_address)
$.ajax({
type: 'POST',
url: '/signup.php',
data: {'first_name': first_name, 'last_name': last_name, 'email_address': email_address},
async: false,
success: (function() {
alert("Successful");
}),
error: (function(ts){
alert(ts.responseText);
})
});
Also in your php you try some string interpolation(putting variables in a string), but you use single quotes, you have to use double quotes.
$message = "New User
$first_name
$last_name
$email_address";