Understanding how ajax works

Hey guys! This is my first time trying my hand at ajax and im just putting my foot in the water first. i’m trying to make it so when the form is submitted, the data is shown on the page. Here’s the code:

$('document').ready(function () {

    $('form #submit').click(function(e){
        e.preventDefault();
        var formdata = $('form').serialize();

        $.ajax({
            type: 'POST',
            url:'ajax_recieve.php',
            data: formdata,
            dataType: 'html',
            success: function(data){
                data.appendTo('footer');
            }
        });
    });

});

the php code:

<?php
if($_POST){
    return "post sdssd";
}
?>

can someone help me with this code please?

When we use Ajax the golden rule for returning data is to echo it out like a normal PHP script as an Ajax connection doesn’t see returned values, so in your case you would use the following:

if (isset($_POST) && sizeof($_POST)) {
    exit('Post was sent');
}

You can also use echo as well but I personally like to use exit and it ends the script right there and then where as echo continues to use memory until the script exits itself or you tell it to, hope that helps.

Hi, does that script throw any errors?

This looks wrong to me as data in your callback will be a HTML string in this case, so ‘a string’.appendTo($(‘footer’)) isn’t valid javascript.
Use console.log to debug what is happening along the way.


success: function(data){
  console.log(data);
  $('footer').append(data);
}

thanks guys! it works now.