Getting Data Back From an AJAX Call

Programmers

AJAX Data Return

AJAX is a beautiful thing; being able to send information and receive it back without reloading the page is priceless.

However, while sending the information can be pretty basic, getting information back can be confusing. This post is about a basic way of returning information. It’s great for debugging or returning a simple variable.

The Basic Setup

First we’ll setup the basic AJAX call, as well as the variable string to pass to the page.

The first variable below, “dataString”, is setup like the GET strings in a URL.

Next we call all the regular items: the type of information (POST or GET), the URL we’re sending it to, the variable with the data string (“dataString”) we’re sending.

Here’s the full code below:

var dataString = 'ID='+ID+'&descript='+value+'&picSrc='+picSrc;
$.ajax({
    type: "POST",
    url: "pageToProcessInfo.php",
    data: dataString,
    error:function (xhr, ajaxOptions, thrownError){
          console.log(xhr.status);
          console.log(thrownError);
    } ,
    complete: function(data) {
          var Resp = data.responseText;
          console.log(Resp);
    }
});

Checking jQuery Errors

This handy section of the code:

error:function (xhr, ajaxOptions, thrownError){
      console.log(xhr.status);
      console.log(thrownError);
} ,

let’s us know if there is any issue with the jQuery coding we’re using. All your debugging in jQuery/Javascript should be done using console.log(), which is what we’ve done in the above coding.

Receiving Information Back

The actual coding that allows us to get information back is this section of the above code:

complete: function(data) {
       var Resp = data.responseText;
       console.log(Resp);
},

The “complete:” says that when the coding is done, we’ll start a function with a “data” variable being passed. This receives any text on the PHP page. We then put that information inside of a variable (“Resp”), and “console.log” that variable to see what shows up.

So if you “echo” anything on the PHP page, it will be put into the “Resp” variable using the above coding.

This is great for debugging. For example, if the information isn’t being added to your database, or the email isn’t being sent, just echo the different variables in PHP on that page, and this will allow you to find the issue.

Not Working?

If the coding above isn’t working, check the following:

  • Each “item: function(){ } ” needs a comma after it, except the last one. Without it, ¬†your code will break
  • Confirm you have the correct amount of parenthesis everywhere
  • Make sure your data string is being passed with the following format: variableName=variable&variableName2=variable2

Here’s the coding in jsFiddle:

Comments