Amit Dhamu

Writes Code

Simple AJAX Using jQuery

There are two methods which I use frequently when handling AJAX requests using jQuery. Both achieve the same results but just two different ways as to how to go about it.

Method 1

// PHP - load-data.php
<?php
    $first_name = $_POST['forename'];
    $last_name = $_POST['surname'];
    $full_name = $first_name." ".$last_name;

    echo $full_name; // This is the result that gets sent back
?>

// jQuery
$.post("ajax/load-data.php", {
    forename: "Amit",
    surname: "Dhamu"
}, function(response) {
    setTimeout("completeFunction('responseContainer', '"+escape(response)+"')", 400);
});

function completeFunction(id, response) {
    $("#"+id).html(unescape(response));
}



Method 2

// PHP - load-data.php
<?php
    $first_name = $_POST['forename'];
    $last_name = $_POST['surname'];
    $full_name = $first_name." ".$last_name;

    echo $full_name; // This is the result that gets sent back
?>    

// jQuery
$.ajax({
    type: "POST",
    url: "ajax/load-data.php",
    data: {forename:"Amit", surname:"Dhamu"},
    success: function(response) {
   $("#responseContainer").html(response);
    },
    error: function(feedback) {
    alert(feedback);
    }
});


ajax / php / request / jquery

← Show Hidden Files on Mac Generate Random Password →