jQuery get response from php file after posting
I'm posting some data to a php file with jquery. The PHP file just saves the data and prints the success of fail message. I would like to get the message generated by php file and embed in a div. I'm unable to figure out how i can return the message from PHP file.
Here is my code:
jQuery:
$(document).ready(function(){
$('#submit').click(function() {
$.ajax({
type : 'POST',
url : 'post.php',
data: {
email : $('#email').val(),
url : $('#url').val(),
name : $('#name').val()
},
});
开发者_运维技巧 });
});
PHP:
<?php
//save data
$message = "saved successfully"
?>
Try -
$(document).ready(function(){
$('#submit').click(function() {
$.ajax({
type : 'POST',
url : 'post.php',
data: {
email : $('#email').val(),
url : $('#url').val(),
name : $('#name').val()
},
success:function (data) {
$("#yourdiv").append(data);
}
});
});
});
This uses the success
callback of the ajax
function to return your data back to the page within the data
parameter. The callback function then appends your data to a div on the page.
You'll also need to -
echo $message
In your php page to give jQuery some data to work with.
Did you look at the properties of the ajax method yet?
From the jQuery site:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Of course, your PHP need to echo something (a JSON object preferably) that returns to the script.
精彩评论