Wednesday, December 26, 2012

jQuery ajax() method


jQuery ajax() method

This article is taken from this website: http://coursesweb.net/jquery/jquery-ajax

The ajax() method is used to perform an AJAX (asynchronous HTTP) request.
All jQuery AJAX functions: load(), get()post() use the ajax() method. This is the most powerful and customizable Ajax method, but its syntax is more complex than the others.
  Syntax:
$.ajax({ name:value, name:value, ...})
- The parameters specify one ore more name:value pairs that configure the Ajax request. They are presented in a list below, but first here's a simple POST request:
$.ajax({
  type: 'POST',
  url: 'script.php',
  data: 'name=some_name&id=an_id',
  success: function(response){
    $('#result').html(response);
  }
});
The data "name=some_name&id=an_id" are send to the "script.php" file through POST method, then the response from the server is placed into an HTML element which has id="result".

Options to configure jQuery ajax

Here's some options (name/value pairs) that can be used to configure the Ajax request.
"xhr" represents the XMLHTTPRequest object.

    async   - a Boolean value (true or false) indicating whether the request should be handled asynchronous or not (default: true). Cross-domain requests and dataType:"jsonp"; requests do not support synchronous operation.
$.ajax({
  url: "file.php",
  async: false
});

    beforeSend(xhr)   - a function to run before the request is sent. Can be used to set custom headers, etc.
$.ajax({
  url: "file.php",
  beforeSend: function() {
    xhr.setRequestHeader("Accept", "text/javascript");
    $('#resp').html('Loading...');
  },
  success: function(response){
    $('#resp').html('response');
  }
});

    cache   - a Boolean value indicating whether the browser should cache the requested pages (default: true, and false for dataType 'script' and 'jsonp').
$.ajax({
  url: "file.html",
  cache: false
});

    complete(xhr, status)   - A function to be called when the request finishes (after success and error callbacks are executed)
$.ajax({
  url: "file.php",
  complete: function() { alert('complete'); }
});

    contentType   - the content type used when sending data to the server (default: 'application/x-www-form-urlencoded').
$.ajax({
  type: "POST",
  url: "file.php",
  data: "{'name1':'value', 'name2':'value'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

    context   - specifies the "this" value for all AJAX related callback functions.
$.ajax({
  url: "file.php",
  context: $('#idd'),
  success: function(){
    $(this).html('Done');      // this will be "#idd"
  }
});

    data   - data to be sent to the server. It is converted to a query string, if not already a string.
$.ajax({
  type: "GET",
  url: "file.php",
  data: "id=78&name=some_name"
});

    dataFilter(data, type)   - a function used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter.
$.ajax({
  url: "file.php",
  data: {'json':'datas'},
  contentType: "application/json; charset=utf-8",
  dataFilter: function(data) {
    var resp = eval('(' + data + ')');
    return resp;
  },
  success: function(response, status, xhr){
    $('#idd').html(response.property);
  }
});

    dataType   - The type of data that you're expecting back from the server.
"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
"script": Evaluates the response as JavaScript and returns it as plain text.
"json": Evaluates the response as JSON and returns a JavaScript object.
"jsonp": Loads in a JSON block using JSONP.
- If none is specified, jQuery will try to infer it based on the MIME type of the response.
$.ajax({
  // Load and execute a JavaScript file
  type: "GET",
  url: "file.js",
  dataType: "script"
});

    error(xhr, status, error)   - function to run if the request fails.
$.ajax({
  url: "file.php",
  error: function(xhr, status, error) { alert(error); }
});

    global   - a Boolean value specifying whether or not to trigger global AJAX event handles for the request (default: true). Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered.
$.ajax({
  url: "file.php",
  global: false,
  success: function(msg){
    alert(msg);
  }
});

    headers   - a map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function
$.ajax({
  headers: { "Content-Type": "application/json", "Accept": "application/json" },
  type: "POST",
  url: "file.php",
  data: {'json': 'data'},
  dataType: "json",
  success: function(json){
    // do something...
  }
});

    ifModified   - a Boolean, if is set to true, will allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header (default: false).
$.ajax({
  url: "file.php",
  ifModified: true,
  success: function(data, status){
    if(status!="notmodified") {
      $("#display").append(data);
    }
  }
});

    jsonp   - a string overriding the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server.
// jQuery will change the url to include &jsonp=jsonpmethod
$.ajax({
  dataType: 'jsnp',
  data: 'id=10',
  jsonp: 'jsnp',
  url: "file.php",
});

    password   - a string that specifies a password to be used in an HTTP access authentication request, used if the server performs HTTP authentication before providing a response.
    username   - a string that specifies an username to be used in an HTTP access authentication request, used if the server performs HTTP authentication before providing a response
$.ajax({
  url: "file.php",
  username: 'name',
  password: 'pass',
  success: function(response){
    $("#display").html(response);
  }
});

    processData   - a Boolean value specifying whether or not data sent with the request should be transformed into a query string (default: true). If you want to send a DOMDocument, or other non-processed data, set this option to false.
// Sends an xml document as data to the server
var xmlDocument = [create xml document];
 $.ajax({
   url: "page.php",
   processData: false,
   data: xmlDocument,
  success: function(response){
    $("#display").html(response);
  }
 });

    scriptCharset   - forces the request to be interpreted as a certain charset. Only for requests with "jsonp" or "script" dataType and "GET" type.
$.ajax({
  type: "GET",
  url: "file.php",
  scriptCharset: "utf-8",
  contentType: "application/x-www-form-urlencoded; charset=UTF-8",
  data: "id=12&name=some_name",
  success: function(response){
    $("#idd").html(response);
  }
  
});

    statusCode   - a map of numeric HTTP codes and functions to be called when the response has the corresponding code.
// alert when the response status is a 404
$.ajax({
  url: "file.php",
  statusCode: {
    404: function() {
      alert('page not found');
    }
  }
});

    success(response, status, xhr)   - a function to be run when the request succeeds.
$.ajax({
  url: "file.php",
  data: 'id=an_id',
  success: function(response, status, xhr){
    if(status=="success") {
      $("#display").html(response);
    }
    else { alert(status+ ' - '+ xhr.status); }
  }
});

    timeout   - sets a local timeout (in milliseconds) for the request.
// allow 3000 millisecond timeout for the AJAX request
$.ajax({
  url: "file.php",
  timeout: 3000,
  success: function(){
    $("#response").text('Success');
  }
});

    type   - the type of request: GET or POST (default: GET). Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
$.ajax({
  type: "POST",
  url: "file.php",
  data: 'name=some_name&pass=pasword',
  success: function(response){
    $("#idd").text(response);
  }
});

    url   - a string containing the URL to which the request is sent (default: the current page).
$.ajax({
  url: "file.php",
  success: function(response){
    $("#idd").text(response);
  }
});

Example script jQuery Ajax - PHP

Let's see a complete example with ajax() and PHP.
We create a web page with a form which contains a text field for name, a select list with options, and a text area for comments.
When the user submits the form, we use the jQuery Ajax to send form data to a PHP script (named script.php) that processes these data and returns an HTML string. If the request succeeds, the response will be placed into a <div> (with id="resp") without reloading the page. In case of an error, will be displayed an Alert window with the error.
Here's the code for the PHP script and the web page with jQuery Ajax (for more details, see the comments in code).

The script.php file

<?php
// define an array with address for diferent courses
$crs = array(
  'other'=>'',
  'php-mysql'=>'php-mysql',
  'javascript'=>'javascript',
  'actionscript'=>'actionscript/lessons-as3',
  'jquery'=>'jquery/jquery-tutorials'
);

// check if there are data sent through POST, with keys "nm", "cs", and "cmt"
if(isset($_POST['nm']) && isset($_POST['cs']) && isset($_POST['cmt'])) {
  $_POST = array_map("strip_tags", $_POST);       // removes posible tags from POST

  // get data
  $nm = $_POST['nm'];
  $cs = $_POST['cs'];
  $cmt = $_POST['cmt'];

  // define a variable with the response of this script
  $rehtml = '<h4>Hy '. $nm. '</h4> Here`s the link for <b>'. $cs. '</b> Course: <a href="http://coursesweb.net/'. $crs[$cs]. '">'. $cs. '</a><br />Your comments: <i>'. $cmt. '</i>';
}
else $rehtml = 'Invalid data';

echo $rehtml;        // output (return) the response
?>

The HTML and jQuery code in the web page

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Ajax - PHP</title>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript"><!--
$(document).ready(function() {
  // when the form "#crs" is submited
  $('#crs').submit(function() {
    // get form data
    var nm = $('#crs #nm').val();
    var cs = $('#crs #cs').val();
    var cmt = $('#crs #cmt').val();

    // put form data in a JSON format that will be sent to the server
    var data_json = {'nm':nm, 'cs':cs, 'cmt':cmt};

    // sets the ajax() method to send data through POST to a PHP script
    // if occurs an error, alerts the request status (xhr.status) and the error
    // when the request succeeds, place the response in a HTML tag with id="resp"
    $.ajax({
      type: 'post',
      url: 'script.php',
      data: data_json,
      beforeSend: function() {
        // before send the request, displays a "Loading..." messaj in the element where the server response will be placed
        $('#resp').html('Loading...');
      },
      timeout: 10000,        // sets timeout for the request (10 seconds)
      error: function(xhr, status, error) { alert('Error: '+ xhr.status+ ' - '+ error); },
      success: function(response) { $('#resp').html(response); }
    });

    return false;      // required to not open the page when form is submited
  });
});
--></script>
</head>
<body>
<div id="resp"></div>
<h4>Fill the form:</h4>
<form action="script.php" method="post" id="crs">
 Name: <input type="text" name="nm" id="nm" /><br />
 Course: <select name="cs" id="cs">
  <option value="other">Other</option>
  <option value="php-mysql">PHP-MySQL</option>
  <option value="javascript">JavaScript</option>
  <option value="actionscript">ActionScript</option>
  <option value="jquery">jQuery</option>
 </select><br />
 Comments:<br />
 <textarea name="cmt" id="cmt" cols="20" rows="3"></textarea>
 <input type="submit" value="submit" />
</form>
</body>
</html>

No comments:

Post a Comment

Please Comment Here!

How to backup and download Database using PHP

< ?php $mysqlUserName = 'databaseusername' ; $mysqlPassword = 'databasepassword' ; $mysqlHostNa...