JQuery & AJAX Passing Info to the Server

Here I show you multiple ways you can retrieve text and xml from the server, using JQuery and AJAX technique’s. Of course, this works without a page reload. I’ll also show you how to send data to the PHP server for processing. Like always I’ll walk you through the code and explain everything in blue boxes that lie after the code.

First Here is the XML

Here is the xml code that we will be loading asynchronously onto our web page.

<?xml version=”1.0″ encoding=”iso-8859-1″?>
<customers>
<customer id=”0″>
<firstName>Paul</firstName>
<lastName>Jones</lastName>
<street>123 Main St</street>
<city>Anywhere</city>
<zip>15235</zip>
</customer>
<customer id=”1″>
<firstName>Sally</firstName>
<lastName>Jones</lastName>
<street>123 Main St</street>
<city>Anywhere</city>
<zip>15235</zip>
</customer>
</customers>

If you don’t understand what this all means, see my Learn XML Tutorial.

A Little PHP Code

This is the PHP code we’ll use to double what ever value is passed to it, and then echo the result to the web page. If this doesn’t make sense see my How to Code PHP Video Tutorial.

<?php
$numberToDbl = $_POST[“data”];
echo $_POST[“data”] . ” Times 2 Equals “;
$doubleUp = $numberToDbl * 2;
echo $doubleUp;
?>

The JQuery & AJAX Code for Talking to the Server

!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<head>
<title>JQuery Example</title>

<script type=”text/javascript” src=”http://code.jquery.com/jquery-latest.js”></script>

Here I’m defining the beginning of my HTML file. I then go and retrieve the newest JQuery library.

<script type=”text/javascript”>
window.onload = function() {

$(‘#oneButton’).bind(‘click’,getInfoFromServer);
$(‘#twoButton’).bind(‘click’,getDblFromServer);
$(‘#threeButton’).bind(‘click’,getXmlFromServer);

};

Here I define all of the event handler’s for all of the button’s on the web page. I also define what function’s should be called when the event’s are triggered. For example, when the button named “oneButton” is clicked my code will run the function named getInfoFromServer. This button’s html code looks like this below:

<button type=”button” id=”oneButton”>Get Text</button>

function getInfoFromServer() {
$.ajax({
type: “GET”,
url: “textFromServer.txt”,
success: postToPage});
}

Here I’m using the ajax() function to pull text in a text file, on the server, over to my web page. A set of key/value pairs are used to configure the Ajax request. All options are optional. Here are the options:

  • type: The type of request to make, “POST” or “GET”, default is “GET”.
  • url: contains the URL to which the request is sent.
  • success: A function to be called if the request succeeds. It passes three value’s to the function that proceeds the key success. They are the data returned from the server, textStatus which describes the servers status and the XMLHttpRequest object. XMLHttpRequest, is a object in the OOP sense, that you will use to communicate with the server without reloading the page. See my AJAX What is it Tutorial for more on it.
  • data: Data to be sent to the server.
  • dataType: The type of data that you’re expecting back from the server. (xml, html, script, json, jsonp, text)
  • error: Function to be called if a request fails. This function is passed three arguments: The XMLHttpRequest object, description of the type of error that occurred and an optional exception object
  • And, a bunch more option’s that are not commonly used…

function postToPage(data, status) {
$(‘#first’).text(data);
}

This function receives the text from the text file, as well as the server status. It then adds the text to the element with the identification name ‘first’. This is the code for first:

<p id=”first”>Waiting for Message</p>

function getDblFromServer() {

$(“span”).load(“getDouble.php”,
$(“#theForm”).serializeArray());
}

Here I’m loading a value into a span element, with the load function. The load function is passed the location of the php script, and the data you want passed to that script. You could also pass a callback function that is executed when the request completes.

The function serializeArray(), creates a JavaScript array made up from the elements in the form named ‘theForm’. That is the data passed to the php file named getDouble. You can see the php code above.

function getXmlFromServer() {
$.ajax({
type: “GET”,
url: “customers.xml”,
datatype: “xml”,
success: postToPageTwo});
}

This function is pulling XML data from the server. Notice that I defined that I expect the data returned to be of type xml, with the option dataType: “xml”.

After the ajax() function is executed the function postToPageTwo() is passed the data to be processed.

function postToPageTwo(data) {
$(data).find(‘customer’).each(function(){
var id = $(this).attr(‘id’);
var firstName = $(this).find(‘firstName’).text();
var lastName = $(this).find(‘lastName’).text();
var street = $(this).find(‘street’).text();
var city = $(this).find(‘city’).text();
var zip = $(this).find(‘zip’).text();
$(‘<div></div>’).html(firstName).appendTo(‘#customers’);
$(‘<div></div>’).html(lastName).appendTo(‘#customers’);
$(‘<div></div>’).html(street).appendTo(‘#customers’);
$(‘<div></div>’).html(city).appendTo(‘#customers’);
$(‘<div></div><br />’).html(zip).appendTo(‘#customers’);
}
);}

This function receives all of the xml data for two customer’s and appends that data to the element named ‘customers’. The .find() method allows us to search through the xml data, looking for a tag named ‘customer’. When found I then assign the values, that lie between <customer> and </customer>, to JavaScript variables.

The final 5 lines of code are appending these values passed to the end of the element named ‘customers’.

The rest of the code is straight html code, which I’m sure you understand. This is the end of my JQuery & AJAX Tutorial. I hope it helped? If you have any question’s or would like to see more on JQuery, AJAX, or anything leave them in the comment section below.

Here to Serve

Think Tank

Here is the rest of the code

</script>

</head>

<body id=”theBody”>
<div><h3>Playing with Server Data</h3></div>

<div>
<h4><strong>Message from the Server:</strong></h4>
<p id=”first”>Waiting for Message</p>
</div>

<div>
<h4><strong>Double Number on the Server:</strong></h4>
<span></span><br />
</div>

<form id=”theForm”>
<button type=”button” id=”oneButton”>Get Text</button>
<input type=”text” name=”data” id=”data”></input>
<button type=”button” id=”twoButton”>Double Number</button>
<button type=”button” id=”threeButton”>Get XML Data</button>
</form>

<div>
<h4><strong>XML Data from the Server:</strong></h4>
</div>

<div id=”customers”>Customer Information</div>

</body>
</html>

11 Responses to “JQuery & AJAX Passing Info to the Server”

  1. Chris says:

    Your jquery videos are helping me a lot since I am new to jquery. But I am a little stuck trying to use ajax to grab an xml.string in asp.net is the method similar. Thank you in advance

    • admin says:

      Glad you like the JQuery videos, but sadly Microsoft specific languages are the only ones I don’t know how to use. I program using only free languages. Sorry I wasn’t able to help, but most languages are almost identical in style and only different in syntax

  2. NICO says:

    Is there an easy way to prevent to load and append those xml-data again and again while pressing the Get xml Data – Button?

    • admin says:

      Not sure what you’re looking for here. I’m going to be covering JQuery again step by step in my current tutorial very soon. I’ll improve dramatically over this tutorial and I’ll make it easier to get all of the code. Thanks

  3. Masha says:

    Thank you for a very nice tutorial. It was very helpful!

  4. Arti says:

    Hello, Admin. I would like to say that your lessons very intersting, I mean it’s awesome. But I have a little problem with serialArray() maybe I don’t understand something, but it’s not work for me. I try, and try figure out in this, but I have no idea how to fix it.

    When I click on twoButton on my page between tag . There appear “Times 2 equals 0”, but should be 4 (cuz I write in input “2”.)

    Please help!

  5. Arti says:

    Hello, Admin. I would like to say that your lessons very intersting, I mean it’s awesome. But I have a little problem with serialArray() maybe I don’t understand something, but it’s not work for me. I try, and try figure out in this, but I have no idea how to fix it.

    When I click on twoButton on my page between tag span. There appear “Times 2 equals 0”, but should be 4 (cuz I write in input “2”.)

    Please help!

  6. Mark says:

    Please email me the files with the code.
    Something ain’t working here.
    Thanx!

Leave a Reply

Your email address will not be published.

Google+