Getting Started With jQuery - Ajax Post
Getting Started With jQuery - Ajax Post
Written by Ian Elliot   
Monday, 14 September 2015
Article Index
Getting Started With jQuery - Ajax Post
Ajax and Forms

Now that we know all about how to get a file, it is time to post some data back to the server. In this chapter we look at both get and post as ways of sending data and see how to send form data under Ajax control. 

  

jquerycover

Chapter List 

  1. The DOM
  2. CSS Selectors
  3. Filters
  4. Advanced Filters
  5. Manipulating The DOM
  6. Promises & Deferred
  7. Promises, Deferred & WebWorkers
  8. Ajax the Basics - get
  9. Ajax the Basic -  post
  10. Ajax - Advanced Ajax To The Server 
  11. Ajax - Advanced Ajax To The Client
  12. Ajax - Advanced Ajax Transports And JSONP
  13. Ajax - Advanced Ajax The jsXHR Object
  14. Ajax - Advanced Ajax Character Coding And Encoding
  15. jQuery - Easy Plugins
  16. jQuery UI
  17. jQuery UI Custom Control - Widget Factory
  18. Getting Started With QUnit Testing
 

As explained in the previous chapter, both get and post retrieve data and both can send data to the server we tend to use get to retrieve data and post to send data.  

Let's take a look at the simplest uses of post. 

Post

The jQuery post command is very easy to use but it can be difficult to get everything right on the client and on the server. 

The basic command is works exactly like get:

$.post(url)

which retrieves the file specified by the url and returns a jqXHR Promise object. You can specify a success callback as a parameter but as in the case of get it is easier to use the Promise object to define any callback.

For example:

$.post("myData.txt").done(
      function(data){

        alert(data)

      });

this simply asks the server for the file myData.txt stored in the same directory as the page making the request.

You can use the done, fail and always Promise methods as described in the previous chapter. 

This all works but it is unusual to simply use a post request to retrieve the contents of a file. A post usually sends data to the server in the body of the request and jQuery lets you specify this data a the second parameter. In principle you can send the data in any format you like as long as the server is able to deal with it. In practice jQuery provides automatic processing for a number of stanard formats and it is easier to stick with these. 

For example the simplest format to use is to send key value pairs which jQuery will extract from an object you supply. So for example if you want to send a first name, second name and an id number you could use:

var sendData={first:"ian",second:"elliot",id:27};

$.post("myData.txt",sendData).done(
      function(data){
       alert(data)
      });

This sends the data to the server but of course the server just ignores it and sends the requested page back to the client. 

To make use of the data there has to be a custom handler on the server to process the data. There are so many ways of doing this ranging from traditional CGI, JavaServlets, Node.js and so on. 

For the sake of a concrete example we will use PHP to provide the server side processing. 

The key idea is that the page that the post requests is best regarded as a program that processes the data and optionally returns a result to the client. 

As long as you send data to a PHP page in key value pairs PHP will do you the favour of decoding them and will make them available as an associative array $_POST. This means that you have virtually no extra work to do on the server side to extract the data from a post. 

You can also check that the request sent to the server was a post by testing the $_POST variable:

if($_POST){process data};

You also need to know that dots and spaces in the key will be converted to underscores e.g. a key like "I Programmer.info" is automatically converted to "I_Programmer_info". 

You can handle the data sent by the previous example using a PHP file process.php something like;

<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
 </head>
 <body>
  <?php
   echo( $_POST['first']);
  ?>
 </body>
</html>

which sends the first name back to the client within a web page.

PHP also automatically processes the value that you pass into either a string or an array according to its format. Notice that how and how much the data is preprocessed is a function of PHP not of the post request or Ajax transactions in general.

So for example if we post the data:

var    sendData={first:"ian",
                 second:"elliot",
                 id:27.5,array:[1,2,3]};

It could be processed in a PHP file something like:

echo(gettype($_POST["array"][1]));

Notice that the array is a string array even though the values are numbers. If you want to work with numeric values then it is up to you to convert the data.

Once again it is worth mentioning that it is the serverside system you use that provides the data processing facilities and hence these are going to vary according to what you use. 

If you are using PHP then it is worth looking up the filter_input function which can perform validation and conversion as well as sanitization of input. For example if you want the id field to be returned as an integer you could use:

 $id=filter_input(INPUT_POST,"id",
                     FILTER_VALIDATE_INT);

This is by far the best way to work with any input data - post, get, cookie or server. 

So to sumarize:

  • Post sends data in the body of the request and retrives data from the server but the file specified from the URL is expected to process the data sent. 
  • The data sent to the server can have any format but there are formats that are better supported than others inparticular a string of key value pairs. 

Sending Data With Get

As mentioned in the previous chapter you can send data to the server with get almost as easily as with post but there are disadvantages. 

When you send data to the server with get the data are encoded as the query string as part of the URL. 

However from the point of view of using jQuery there is no real difference between sending data using post or get. For example to send some data to be processed by process.php you would use: 

$.get("process.php",sendData).done(
       function(data){
        alert(data)
       });

which apart from the change from post to get is identical to the earlier program.

At the server side you simply have to change the $_POST to $_GET:

<?php  echo( $_GET['first']);
 echo(filter_input(INPUT_GET,"id",
                    FILTER_VALIDATE_INT));
?>

This might well lull the beginner into a false sense of security because both the client and the server side systems are doing a lot of work to make things look this easy.

In particular jQuery does a lot of work for you and unpacks the key value pairs and URL encodes them. If you use the PHP instruction:

echo($_SERVER['REQUEST_URI']);

to send the URL back to the client for disply then you will discover that it reads something like: 

/process.php?first=ian&second=elliot&
   id=27&array%5B%5D=1&array%5B%5D=2&array%5B%5D=3

The good news is that PHP automatically un-URLencodes the data for you and presents you with an array of key value pairs as in the case of post.

Notice that when you get all of the data is sent using the URL as a query string. Different browsers limit the lenght of a URL in different ways but traditionally a limit of around 2000 characters has been suggested. However why risk things not working when you can use a post instead. 

If you want to manually URL encode some data use JavaScript's urlencode function or jQuery's param() function. The urlencode function will only code up a string and it up to you to construct the full query string. The jQuery param() function will accept an array, object or jQuery object and do more of the work for you. 

For example:

var q= $.param(sendData));

returns

first=ian&second=elliot&id=27
  &array%5B%5D=1&array%5B%5D=2&array%5B%5D=3

If you want to URL encode a form use jQuery's serialize method.

It is also worth knowing about the serializeArray method which will convert form into an array of name, value pairs. This is often useful if you need to do a lot of processing before sending the data. 

The bottom line is that there is little reason to use a get to send a lot of complext data - you are better of with a post. 

  • If you are sending data to the sever for processing use a post.
  • If you are retrieving data from the server use a get. 


Last Updated ( Monday, 14 September 2015 )
 
 

   
Banner
Copyright © 2017 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.