Reputation: 15
I'm new in JQuery. I have managed to return data to JQuery from php script but now I get to see the message <!--Separate connection with sessions -->
when I show the returned message from php script to the user and I only want to display my message to the user using alert().
PHP code:
<?php
include "initialize.php";
if(empty($_POST) === false){
global $con;
$message = "";
$email = trim($_POST["email"]);
if(isSubscribed($email) === false){
$message = "Thank you for subscribing to our latest updates";
mysqli_query($con,"INSERT INTO subscribers(email) VALUES('".$email ."')");
}
else{
$message = "You already subscribed.";
}
echo $message;
}
?>
JQuery Code:
$(function () {
$('#frms').on('submit', function (e) {
var email = $("#email").val();
if (!validateEmail(email)) {
alert('Error: Make sure you provided a valid email address');
}
else {
$.ajax({
type: 'post',
url: 'initialize/subscribe.php',
data: $('#frms').serialize(),
success: function (data) {
alert(data);
}
});
}
e.preventDefault();
});
});
Upvotes: 1
Views: 190
Reputation: 61
return data like this :
$returnArr=array(); returnArr['message']=$message;
echo json_encode(returnArr);
exit;
and at client side use this code alert(data.message);
Upvotes: 1
Reputation: 14544
<!--Separate connection with sessions -->
This is an HTML comment, and it probably means when you call the PHP script from your jQuery, that HTML is also added somewhere to the response.
i.e. Your PHP "page" is not only echoing your message; it is echoing that HTML as well.
A quick fix is to kill the PHP script immediately after you echo your message, to prevent any other output from being returned to the jQuery.
echo $message;
die; // Add this
This will terminate the script after you echo your message, and not allow any other output to be generated.
If you still see the HTML after adding die
, it probably means the HTML is added before you echo your message. In which case it might be in initialize.php
and you would have to prevent that other script from echoing anything as well.
Upvotes: 2