Rameez Rameez - 4 months ago 17
Javascript Question

How to pass values from a html page using jQuery to PHP and get a response back?

I am trying to pass the values from jQuery to PHP. Here is my code,

jQuery Function:

$(document).ready(function () {
$("#contact_form").submit(function () {
var RequesterName = $("#RequesterName").val();
var Requestoremail = $("#Requestoremail").val();
var Subject = '[Request] Mail Subject';
$.ajax({
type: 'post',
dataType: 'json',
url: 'sendmail.php',
data: { RequesterName_val: RequesterName, Requestoremail_val: Requestoremail, Subject_val: Subject },
success: function (data) {
alert('Mail Sent Successsfully');
}
});
});
})


and PHP:

<?php
$to = $_POST['RequesterName_val'];
$subject = $_POST['Subject_val'];
$RequesterName = $_POST['RequesterName_val'];
$Requestoremail = $_POST['Requestoremail_val'];

$message = "RequesterName:".$RequesterName." , Requestoremail:".$Requestoremail." ";

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <'.$Requestoremail.'>' . "\r\n";
$headers .= "Reply-To: '.$Requestoremail.'\r\n";

if (mail($to,$subject,$message,$headers)) {
echo "Success";
} else {
echo "Error";
}

die();

?>


It seems mail is triggering from php but I am not getting a response back and "Mail Sent Successfully" is not displaying in jQuery? How can i get a response for success and failure of mail trigger?

Answer

Your $.ajax call says that the response should be JSON, but you're just returning plain text. When jQuery gets an error trying to parse the JSON, it doesn't call the success: callback.

You can either correct the PHP so it returns JSON:

echo json_encode(mail($to,$subject,$message,$headers));
die();

Then in the success function you would write:

success: function(data) {
    if (data) {
        alert('Mail sent successfully');
    } else {
        alert('Mail not sent');
    }
}

or you can change the $.ajax call to use dataType: 'text', and the callback would be:

success: function(data) {
    if (data == 'Success') {
        alert('Mail sent successfully');
    } else {
        alert('Mail not sent');
    }
}