Category Archives: Ajax

Post() Methods jQuery – AJAX get() and | Examples

  • The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.

HTTP Request: GET vs. POST :

  • Two commonly used methods for a request-response between a client and server are: GET and POST.
  • GET – Requests data from a specified resource
  • POST – Submits data to be processed to a specified resource
  • GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.
  • POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
  • To learn more about GET and POST, and the differences between the two methods, please read our HTTP Methods GET vs POSTchapter.

jQuery $.get() Method :

  • The $.get() method requests data from the server with an HTTP GET request.

Syntax:

$.get(<i>URL,callback</i>);
  • The required URL parameter specifies the URL you wish to request.
  • The optional callback parameter is the name of a function to be executed if the request succeeds.
  • The following example uses the $.get() method to retrieve data from a file on the server:

Example :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>

<button>Send an HTTP GET request to a page and get the result back</button>

</body>
</html>
  • The first parameter of $.get() is the URL we wish to request (“demo_test.asp”).
  • The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
  • Tip: Here is how the ASP file looks like (“demo_test.asp”):
<%
response.write("This is some text from an external ASP file.")
%>

jQuery $.post() Method :

  • The $.post() method requests data from the server using an HTTP POST request.

Syntax:

$.post(<i>URL,data,callback</i>);
  • The required URL parameter specifies the URL you wish to request.
  • The optional data parameter specifies some data to send along with the request.
  • The optional callback parameter is the name of a function to be executed if the request succeeds.
  • The following example uses the $.post() method to send some data along with the request:

Example :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>
  • The first parameter of $.post() is the URL we wish to request (“demo_test_post.asp”).
  • Then we pass in some data to send along with the request (name and city).
  • The ASP script in “demo_test_post.asp” reads the parameters, processes them, and returns a result.
  • The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
  • Tip: Here is how the ASP file looks like (“demo_test_post.asp”):
<%
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
Response.Write("Dear " & fname & ". ")
Response.Write("Hope you live well in " & city & ".")
%>

jQuery AJAX Reference :

For a complete overview of all jQuery AJAX methods, please go to our jQuery AJAX Reference.

Example : 1

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>

Example : 2

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>

<button>Send an HTTP GET request to a page and get the result back</button>

</body>
</html>

Load() Method in jQuery – AJAX |Example

jQuery load() Method :

  • The jQuery load() method is a simple, but powerful AJAX method.
  • The load() method loads data from a server and puts the returned data into the selected element.

Syntax: 

$(<i>selector</i>).load(<i>URL,data,callback</i>);
  • The required URL parameter specifies the URL you wish to load.
  • The optional data parameter specifies a set of querystring key/value pairs to send along with the request.
  • The optional callback parameter is the name of a function to be executed after the load() method is completed.

Here is the content of our example file: “demo_test.txt”:

<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
  • The following example loads the content of the file “demo_test.txt” into a specific <div> element:

Example :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt");
});
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>
  • It is also possible to add a jQuery selector to the URL parameter.
  • The following example loads the content of the element with id=”p1″, inside the file “demo_test.txt”, into a specific <div> element:

Example :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt #p1");
});
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>
  • The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:
  • responseTxt – contains the resulting content if the call succeeds
  • statusTxt – contains the status of the call
  • xhr – contains the XMLHttpRequest object
  • The following example displays an alert box after the load() method completes. If the load() method has succeeded, it displays “External content loaded successfully!”, and if it fails it displays an error message:

Example :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("External content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

jQuery AJAX Reference :

For a complete overview of all jQuery AJAX methods, please go to our jQuery AJAX Reference.

Example : 1

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt");
});
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

Example :  2

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt #p1");
});
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

How to Loading external files, AJAX, XML|Reading XML File Using jQuery AJAX Method |

AJAX :

AJAX (Asynchronous JavaScript and XML) is a technique for communicating with a server and dynamically altering a page without leaving the page. It can be used to send as well as receive information in a variety of formats, including JSON, XML, HTML, and text files. It is made possible with the XMLHttpRequest object, a built-in feature of your browser.

This diagram illustrates the basic flow:

AJAX is a bit difficult to get working in a cross platform manner (see an example here) but there are quite a few libraries out there that have done the hard work. Following are some examples with p5.js and jQuery, but first, a brief note about callbacks.

Callbacks :

A callback is a function that is passed to another function as a parameter, and called by that other function. A callback function is useful when working with asynchronous functions because it allows us to specify some code to execute after the first asynchronous task has completed.

We’ve actually already used callbacks when we used setTimeout, setInterval, and addEventListener. For example, “doSomething” below is a callback function:

function</span> <span class="pl-en">doSomething</span>() {
  <span class="pl-en">console</span><span class="pl-c1">.log</span>(<span class="pl-s"><span class="pl-pds">"</span>doing something!<span class="pl-pds">"</span></span>);
}

<span class="pl-c1">setTimeout</span>(doSomething, <span class="pl-c1">5000</span>);

You will see callbacks used in p5.js and jQuery to tell the program what to do after the external data is received.

XML :

XML (Extensible Markup Language) is another popular format for providing machine readable data to and from web services. XML is made up of tags, similar to HTML, but unlike HTML, there are no predefined tags (like h1, p, html, etc), instead you make up your own.

<<span class="pl-ent">breakfast_menu</span>>
  <<span class="pl-ent">food</span>>
    <<span class="pl-ent">name</span>>Belgian Waffles</<span class="pl-ent">name</span>>
    <<span class="pl-ent">price</span>>$5.95</<span class="pl-ent">price</span>>
    <<span class="pl-ent">description</span>>
      Two of our famous Belgian Waffles with plenty of real maple syrup
    </<span class="pl-ent">description</span>>
    <<span class="pl-ent">calories</span>>650</<span class="pl-ent">calories</span>>
  </<span class="pl-ent">food</span>>
  <<span class="pl-ent">food</span>>
    <<span class="pl-ent">name</span>>Strawberry Belgian Waffles</<span class="pl-ent">name</span>>
    <<span class="pl-ent">price</span>>$7.95</<span class="pl-ent">price</span>>
    <<span class="pl-ent">description</span>>
      Light Belgian waffles covered with strawberries and whipped cream
    </<span class="pl-ent">description</span>>
    <<span class="pl-ent">calories</span>>900</<span class="pl-ent">calories</span>>
  </<span class="pl-ent">food</span>>
  <<span class="pl-ent">food</span>>
    <<span class="pl-ent">name</span>>French Toast</<span class="pl-ent">name</span>>
    <<span class="pl-ent">price</span>>$4.50</<span class="pl-ent">price</span>>
    <<span class="pl-ent">description</span>>
      Thick slices made from our homemade sourdough bread
    </<span class="pl-ent">description</span>>
    <<span class="pl-ent">calories</span>>600</<span class="pl-ent">calories</span>>
  </<span class="pl-ent">food</span>>
</<span class="pl-ent">breakfast_menu</span>>

AJAX with p5.js :

p5.js has a variety of methods for using AJAX to retrieve files from a server. These include:

  1. loadStrings – loads .txt files
  2. loadJSON – loads .json files
  3. loadXML – loads .xml files
  4. loadTable – loads .csv files

loadStrings :

  • loadStrings loads a text file and returns an array of strings. It takes two arguments, the path to the file, and the callback function. When the server has returned the text data and it has been parsed, doText is run with the result automatically passed in as the variable “data”.
function</span> <span class="pl-en">setup</span>() {
  createCanvas(<span class="pl-c1">600</span>, <span class="pl-c1">400</span>);
  fill(<span class="pl-c1">0</span>);

  loadStrings(<span class="pl-s"><span class="pl-pds">"</span>lines.txt<span class="pl-pds">"</span></span>, doText);
}

<span class="pl-k">function</span> <span class="pl-en">doText</span>(<span class="pl-smi">data</span>) {
  <span class="pl-k">for</span> (<span class="pl-k">var</span> i<span class="pl-k">=</span><span class="pl-c1">0</span>; i<span class="pl-k"><</span>data.<span class="pl-c1">length</span>; i<span class="pl-k">++</span>) {
    text(data[i], <span class="pl-c1">5</span>, <span class="pl-c1">20</span><span class="pl-k">*</span>i<span class="pl-k">+</span><span class="pl-c1">20</span>);
  }
}

Note  : that if you tried to do something like the following, nothing shows up. This is because the program starts and calls loadStrings, but it moves on to doText before loadStrings completes. At the point where doText runs, the variable “data” is not yet set to anything. This is that asynchronous thing we were talking about.

function</span> <span class="pl-en">setup</span>() {
  createCanvas(<span class="pl-c1">600</span>, <span class="pl-c1">400</span>);
  fill(<span class="pl-c1">0</span>);

  <span class="pl-k">var</span> data <span class="pl-k">=</span> loadStrings(<span class="pl-s"><span class="pl-pds">"</span>lines.txt<span class="pl-pds">"</span></span>);
  doText(data); <span class="pl-c">// this won't work!</span>
}

<span class="pl-k">function</span> <span class="pl-en">doText</span>(<span class="pl-smi">data</span>) {
  <span class="pl-k">for</span> (<span class="pl-k">var</span> i<span class="pl-k">=</span><span class="pl-c1">0</span>; i<span class="pl-k"><</span>data.<span class="pl-c1">length</span>; i<span class="pl-k">++</span>) {
    text(data[i], <span class="pl-c1">5</span>, <span class="pl-c1">20</span><span class="pl-k">*</span>i<span class="pl-k">+</span><span class="pl-c1">20</span>);
  }
}

JS file:

function</span> <span class="pl-en">setup</span>() {
  createCanvas(<span class="pl-c1">600</span>, <span class="pl-c1">400</span>);
  noStroke();
  textSize(<span class="pl-c1">20</span>);
  loadJSON(<span class="pl-s"><span class="pl-pds">"</span>data.json<span class="pl-pds">"</span></span>, drawData);
}

<span class="pl-k">function</span> <span class="pl-en">drawData</span>(<span class="pl-smi">data</span>) {
  <span class="pl-c">// person 1 bubble</span>
  fill(<span class="pl-c1">155</span>, <span class="pl-c1">30</span>, <span class="pl-c1">180</span>, <span class="pl-c1">180</span>);
  ellipse(<span class="pl-c1">250</span>, <span class="pl-c1">200</span>, data.person1.age <span class="pl-k">*</span> <span class="pl-c1">5</span>, data.person1.age <span class="pl-k">*</span> <span class="pl-c1">5</span>); <span class="pl-c">// person1.age = 30</span>
  fill(<span class="pl-c1">255</span>);
  text(data.person1.<span class="pl-c1">name</span>, <span class="pl-c1">210</span>, <span class="pl-c1">200</span>); <span class="pl-c">// person1.name = Morgan</span>

  <span class="pl-c">// person 2 bubble</span>
  fill(<span class="pl-c1">180</span>, <span class="pl-c1">180</span>, <span class="pl-c1">34</span>, <span class="pl-c1">180</span>);
  ellipse(<span class="pl-c1">350</span>, <span class="pl-c1">200</span>, data.person2.age <span class="pl-k">*</span> <span class="pl-c1">5</span>, data.person2.age <span class="pl-k">*</span> <span class="pl-c1">5</span>); <span class="pl-c">// person2.age = 32</span>
  fill(<span class="pl-c1">255</span>);
  text(data.person2.<span class="pl-c1">name</span>, <span class="pl-c1">330</span>, <span class="pl-c1">200</span>); <span class="pl-c">// person2.name = Joss</span>
}
var</span> bubbles <span class="pl-k">=</span> [];

<span class="pl-k">function</span> <span class="pl-en">setup</span>() {
  createCanvas(<span class="pl-c1">600</span>, <span class="pl-c1">400</span>);
  noStroke();
  loadJSON(<span class="pl-s"><span class="pl-pds">'</span>http://api.openweathermap.org/data/2.5/weather?q=NewYork,USA<span class="pl-pds">'</span></span>, drawWeather); 
}

<span class="pl-k">function</span> <span class="pl-en">drawWeather</span>(<span class="pl-smi">weather</span>) {

  <span class="pl-c">// Get the loaded JSON data</span>
  <span class="pl-en">console</span><span class="pl-c1">.log</span>(weather); <span class="pl-c">// inspect the weather JSON</span>
  <span class="pl-k">var</span> humidity <span class="pl-k">=</span> weather.main.humidity; <span class="pl-c">// get the main.humidity out of the loaded JSON</span>
  <span class="pl-en">console</span><span class="pl-c1">.log</span>(humidity); <span class="pl-c">// inspect the humidity in the console</span>

  background(<span class="pl-c1">40</span>, <span class="pl-c1">90</span>, <span class="pl-c1">200</span>);
  fill(<span class="pl-c1">0</span>, <span class="pl-c1">255</span>, <span class="pl-c1">255</span>, humidity); <span class="pl-c">// use the humidity value to set the alpha</span>
  <span class="pl-k">for</span> (<span class="pl-k">var</span> i <span class="pl-k">=</span> <span class="pl-c1">0</span>; i <span class="pl-k"><</span> <span class="pl-c1">50</span>; i<span class="pl-k">++</span>) {
    ellipse(<span class="pl-c1">random</span>(width), <span class="pl-c1">random</span>(height), <span class="pl-c1">30</span>, <span class="pl-c1">30</span>);
  }
}

loadXML :

  • loadXML loads an XML file and returns an XML object. It takes two arguments, the path to the file, and the callback function. It’s a little messier to work with XML objects, but you can learn about how to do that here.

preload :

  • If you’d prefer not to deal with asynchronous callbacks, p5.js also has a function called “preload” that lets you load external files synchronously before setup is run. If a preload function is defined, setup will wait until any load calls within have finished. This allows you to access the file data in setup and draw without needing a callback. Nothing besides load calls should be inside preload (loadImage, loadJSON, loadStrings, loadXML, etc).
var</span> lines;

<span class="pl-k">function</span> <span class="pl-en">preload</span>() {
  lines <span class="pl-k">=</span> loadStrings(<span class="pl-s"><span class="pl-pds">"</span>lines.txt<span class="pl-pds">"</span></span>);
}

<span class="pl-k">function</span> <span class="pl-en">setup</span>() {
  createCanvas(<span class="pl-c1">600</span>, <span class="pl-c1">400</span>);
  textSize(<span class="pl-c1">20</span>);
  fill(<span class="pl-c1">0</span>);
  noLoop();
}

<span class="pl-k">function</span> <span class="pl-en">draw</span>() {
  <span class="pl-k">for</span> (<span class="pl-k">var</span> i<span class="pl-k">=</span><span class="pl-c1">0</span>; i<span class="pl-k"><</span>lines.<span class="pl-c1">length</span>; i<span class="pl-k">++</span>) {
    text(lines[i], <span class="pl-c1">5</span>, <span class="pl-c1">20</span><span class="pl-k">*</span>i<span class="pl-k">+</span><span class="pl-c1">20</span>);
  }
}

AJAX with jQuery :

  • Rather that p5.js, you can also use jQuery to help with loading external files. jQuery is a JS library that helps with handling DOM manipulation, events, animation, and AJAX. In order to use the jquery library, you will need to include a link to it in the head of your html file.
<</span>script src<span class="pl-k">=</span><span class="pl-s"><span class="pl-pds">"</span>//code.jquery.com/jquery-1.11.1.min.js<span class="pl-pds">"</span></span><span class="pl-k">><</span>/script<span class="pl-k">>
$(<span class="pl-c1">document</span>).ready(<span class="pl-k">function</span>(){

  $.ajax({
    url<span class="pl-k">:</span> <span class="pl-s"><span class="pl-pds">"</span>lines.txt<span class="pl-pds">"</span></span>, <span class="pl-c">// path to file</span>
    dataType<span class="pl-k">:</span> <span class="pl-s"><span class="pl-pds">'</span>text<span class="pl-pds">'</span></span>, <span class="pl-c">// type of file (text, json, xml, etc)</span>
    <span class="pl-en">success</span><span class="pl-k">:</span> <span class="pl-k">function</span>(<span class="pl-smi">data</span>) { <span class="pl-c">// callback for successful completion</span>
      $(<span class="pl-s"><span class="pl-pds">"</span>#sentences<span class="pl-pds">"</span></span>).html(data);
    },
    <span class="pl-en">error</span><span class="pl-k">:</span> <span class="pl-k">function</span>() { <span class="pl-c">// callback if there's an error</span>
      <span class="pl-c1">alert</span>(<span class="pl-s"><span class="pl-pds">"</span>error<span class="pl-pds">"</span></span>);
    }
  });     

});
$(<span class="pl-c1">document</span>).ready(<span class="pl-k">function</span>(){
  $.ajax({
    url<span class="pl-k">:</span> <span class="pl-s"><span class="pl-pds">"</span>http://api.openweathermap.org/data/2.5/weather?id=5128581&units=imperial<span class="pl-pds">"</span></span>,
    dataType<span class="pl-k">:</span> <span class="pl-s"><span class="pl-pds">'</span>json<span class="pl-pds">'</span></span>,
    <span class="pl-en">success</span><span class="pl-k">:</span> <span class="pl-k">function</span>(<span class="pl-smi">data</span>) {
      <span class="pl-c1">alert</span>(<span class="pl-s"><span class="pl-pds">"</span>Temperature is: <span class="pl-pds">"</span></span> <span class="pl-k">+</span> data.main.temp );
    },
    <span class="pl-en">error</span><span class="pl-k">:</span> <span class="pl-k">function</span>() {
      <span class="pl-c1">alert</span>(<span class="pl-s"><span class="pl-pds">"</span>error<span class="pl-pds">"</span></span>);
    }
  });        
});