d
Amit DhamuSoftware Engineer
 

Simple AJAX Using jQuery

1 minute read 00000 views

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.

// PHP - load-data.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

Method 1

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

function completeFunction(id, response) {
  $('#' + id).html(response)
}

Method 2

$.ajax({
  type: 'POST',
  url: 'load-data.php',
  data: {
    forename: 'Amit',
    surname: 'Dhamu',
  },
  success: function (response) {
    $('#responseContainer').html(response)
  },
  error: function (feedback) {
    console.log(feedback)
  },
})