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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With