Display user posts with ajax success
I am trying to display two kinds of custom messages on jquery / ajax response.
In my processing script, I store these messages like this:
// Initialize Json array.
$messages ='';
// Check for the email:
if (!empty($_POST['email'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$messages = array('success'=>false,'cssClass'=>'alert-danger','message'=>'Email does not match the required format.');
}
// Print a message based upon the result:
if ($stmt->affected_rows == 1) {
// Print a message and wrap up:
$messages = array('success'=>true,'cssClass'=>'alert-success','message'=>'Your password has been changed. You will receive the new, temporary password at the email address with which you registered. Once you have logged in with this password, you may change it by clicking on the "Password Modification" link.');
}
echo json_encode($messages);
In JQuery, I'm trying to populate this post with something like this. But I cannot print these messages.
UPDATE:
success: function (json) {
if (json.success) {
// it worked
alert('ok');
$('#message').append('<div class="alert alert-dismissible ' + json.cssClass + '" role="alert">' + json.message + '</div>');
$('#message').show();
} else {
// something went wrong
alert('not ok');
$('#message').append('<div class="alert alert-dismissible ' + json.cssClass + '" role="alert">' + json.message + '</div>');
$('#message').show();
}
Can anyone tell me where I am going wrong? Hope someone can help me.
Thank.
+3
source to share
2 answers
You are just missing one line of code.
That the server script provides a JSON string .
And you cannot access properties from JSON string .
First you have to parse the JSON string and create a JSON object from it ...
success: function (jsonString) {
var json = JSON.parse(jsonString); //parse the JSON string and create JSON object
if (json.success) {
// it worked
alert('ok');
$('#message').append('<div class="alert alert-dismissible ' + json.cssClass + '" role="alert">' + json.message + '</div>');
$('#message').show();
} else {
// something went wrong
alert('not ok');
}
}
The above code uses the class JSON
available inJS Platform
+2
source to share