Can I get more variables instead of string in jquery $ ajax?
I have this script:
$.ajax({
url: 'submit_to_db.php',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&comments=' + comments,
success: function(result) {
$('#response').remove();
$('#container').append('<p id="response">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});
Then in my php file, after inserting into the database, I repeat "comment updated", then I attach to the container and slowly fade out. In the meantime, I want to insert a new comment into the container. So I tried echo "comment updated! & Com =". $ Comment; but it was returned as a string, not 2 variables. \
EDIT:
So strange, I am getting undefined in my php file,
$ comment = $ _POST ['comment']
is there something wrong in my js or php code?
+1
show_lol
a source
to share
2 answers
The answer contains no variables. It contains the text, the result of the query you made. I recommend using JSON.
#in submit_to_db.php
$response = array();
if($submitted) { #if the comment was inserted successfully
$response['status'] = 'OK';
$response['message'] = 'Your comment was added';
$response['comment'] = $_POST['comments'];
}
else {
$response['status'] = 'ERROR';
$response['error'] = 'You must enter your name'; #just an example
}
echo json_encode($response);
#would yield {"status":"OK","comment":"the comment just added"}
#in yourJsFile.js
$.ajax({
url: 'submit_to_db.php',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&comments=' + comments,
dataType: 'json',
success: function(response) {
if(response.status == 'OK') {
$('#response').remove();
$('#container').append('<p id="response">' + response.message + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
$('#comments').append('<li>' + response.comment + '</li>'); //just an example
}
else {
$('#container').append('<p id="response">' + response.error + '</p>');
}
}
});
+2
a source to share