Jquery post method for JSON in php files

jQuery is the awesomest thing I have came across so far. It makes things so easy one can easily understand why upon seeing example below. “post” method of jQuery is frequently used by many sites even Facebook and Google. You must have seen that log-in to Gmail doesn’t redirect/reload and tells you that username or password is incorrect instead they post the values using AJAX or lets say using post method of jQuery and display the error response.

Required: jquery.js(I use jquery-1.6.js. Download latest!)

Using:

file1.php


$(document).ready(function(){
$.post( 'filename', {data : data}, function(data , status){
if(status == 'success'){
alert(data.name); //your code }
}, "json" );
});

In file2.php


</div>
<div>if(isset($_POST['data'])){
echo json_encode(array('name'=>$_POST['data']));
}</div>
<div>

Explanation:

file1.php

  1. checks if the current document is ready.
  2. is the jquery method “post” is given arguments, first is the “filename” is the file name which you want to handle the post variables. Second is associative array sort of thing in which first “data” is name of the post variable and second “data” is the value of the variable. Third argument is the callback function, this executes when the post is complete. This function is provided two arguments, first is “data” which is the response from the file which is handling post. We will explain it after sometime. And the second is “status” it is optional in all of this without this code will still work. It actually holds the status of response.
  3. checks if status is success
  4. if status is success we use alert to check for the JSON value which is data.name and will alert “data” because we sent it back from file2.php.
  5. “json” is the last argument of the post method which tells the that this method is expecting JSON as response.

Note:

  • post variable name can be in quotes ‘data’.
  •  argument status can be omit.
  • “json” is required as argument if you want response to be JSON.

 

file2.php

  1. checks if $_POST[‘data’] is set. The data index is the same variable name we have sent from file1.php.
  2. first we create an associative array with key as “name” and value as $_POST[‘data’]. Then we encode it in JSON using json_encode and echo it, which is accepted by first file in callback function as data and checked using alert in file1.php as data.name which is the key in associative array.

Note:

  • This file should not have any of HTML code.
  • This file should not echo anything other than JSON.
  • You can use include() but above two points should always hold.
Hope this will help you in case you find trouble. Please also go through the jQuery website, they have pretty good tutorials.