Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get response from php file after posting

Tags:

jquery

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"
?>
like image 636
user966585 Avatar asked Sep 27 '11 09:09

user966585


2 Answers

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.

like image 98
ipr101 Avatar answered Oct 30 '22 16:10

ipr101


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.

like image 1
Bas Slagter Avatar answered Oct 30 '22 15:10

Bas Slagter