How to get data from the server with JSON/jQuery


In web development, sending data back and forth between the server is a common occurrence. When using jQuery, sending the data is pretty straightforward, however receiving information back from the server is not so simple. You could receive data in different formats (ie. JSON or HTML), the user may have lost authentication and are no longer permitted to access the page or you may want to send back different information depending on whether or not the task was successful. Over the years, I’ve developed a system for handling these situations that utilizes jQuery and JSON. It’s something that I roll out enough that even if no-one finds this post, it’ll help me to have the basic code posted where I can easily access it. So, I’ve decided to document it here.

Assumptions

Ok, just to lay out the scenario, here’s the assumptions I’m making:

  • The file I’m working on is called main.htm
  • main.htm already includes jQuery
  • main.htm has a button (btnDoStuff) – clicking this will trigger send code
  • The server-side file that the data is posted to is called post.php

The Code

Now that you know what we’re dealing with, let’s get to the code!

JavaScript/jQuery

$(function() {
	$('#btnDoStuff').click(function(evt) {
		$.ajax({
			type: 'POST',
			url: '/post.php',
			data: { "ajax":1, "id":23 },
			dataType:'json',
			success: function(data) {
				if (data) { //Make sure we got a JSON object
					//Make sure we HAVE a status variable
					if (data.s) {
						if (data.s === 0) {
							//Woo hoo! It worked!
						} else if (data.s === 1) {
							//It partially worked
						}  else if (data.s === -1) {
							//Boo! Something went terribly wrong
						} else {
							//Status was unexpected
						}
					} else {
						alert('No status variable returned!');
					}
				} else {
					//Whoops! It looks like we got some HTML
					//  or another format. There was either
					//  an error or the user has been logged
					//  out and the login page was returned.
				}
			},
			error: function(data) {
				//Handle erroneous requests
			}
		});
		evt.preventDefault(); //Stop click event
	});
});

Ok, so what are we doing here? Well, when a user clicks on the button ($('#btnDoStuff').click), we make a POST request (type: 'POST') to the page post.php (url: '/post.php') with the parameter “id” (data: { "id":23 }). We also tell it we’re expecting a JSON object back (dataType:'json').

Then, when we get a response, we check the data to find out what we got back. The first step here is ensuring we got a JSON object back in our data parameter. We do that with this line: if (data). If this is false, something went wrong and the page returned something that wasn’t JSON. If your authentication scheme redirects users to a login page if they’re no longer logged in, this is a good indication that they’ve been logged out.

If we DID get some JSON back (i.e. if (data) is true), we’re going to check for a status value that will indicate how our request went.

  • if (data.s) { ‐ If the value is equal to zero (0), it succeeded. The reason we use zero for success is because, most likely, there’s only one success condition. On the other hand, there are probably many error or informational conditions. Handling those is what the next else statements are for.
  • } else if (data.s === 1) { – If the value is one (1), there was a problem but not necessarily an error. This could be anything. If it’s above zero it may have partially worked or maybe it did something else and was a success. You may have multiples of this or it may not even be necessary, it depends on your needs.
  • } else if (data.s === -1) { – If the value is negative one (-1), there was an error and the post.php reported that it failed what it was trying to do. Like the above condition, there can be many different error messages and I usually like to keep them below zero for clarity.
  • } else { – If the value doesn’t meet one of the above conditions, this will catch it. You probably want to put a debug alert() here so you’ll be warned when an unexpected status value is returned.

php

Now, we’ll take a look at the php code from post.php. This code is pretty straightforward so I’ll just leave it up to the comments to explain it.

//Check if this is an ajax request
if ($_POST["ajax"] == 1) {
    //Get the posted ID variable
    $id = $_POST["id"];
    //Do stuff with it here
    // ...
    
    //Ok, let's let the client know how it went
    if ($success) {
        //It was successful, return a status code of 0 and the data.
        $returnData = array( "s" => 0,
		                     "d" => array("item1","item2","item3"));
    } elseif ($partialsuccess) {
        //It was partially successful, return a status code of 1 and
		//  the data and a message.
        $returnData = array( "s" => 1,
		                     "d" => array("item1","item2"),
							 "m" => "Data was partially updated.");
    } else ($error) {
        //Error Will Robinson! Return a status code of -1 and a
		//  message.
        $returnData = array( "s" => -1,
		                     "m" => "Fatal error. I am dead.");
    }
    //This method converts our associative array into a JSON object
	// that we can use in JavaScript.
    return json_encode($returnData);
} else {
    //Looks like someone didn't post to the page correctly!
    echo "You shouldn't be here.";
}

When the code has executed successfully, we return an array in the “d” property containing whatever information was requested. In the JavaScript, we can access the data using data.d just like we already saw using data.s.
When there was a partial success, we return some data (“d”) and a message (“m”) indicating what wasn’t updated. When there was an error, we return a message (“m”) indicating what happened.

Conclusion

So there you have it: the basics of communicating with the server and getting data back using JSON and jQuery. JSON is really handy and much, much smaller than XML or sending HTML. Keep in mind when you’re sending huge amounts of table data, don’t append the column names to every row or you’ll be adding a ton of excess bytes to your output. The smaller the better!

I hope this has helped you. I’ve had it in the works for a while but just haven’t had a chance to sit down and finish it off. I have a few more posts in the works so hopefully I can get them up soon.

Happy coding!



Be Sociable, Share!

Leave a Reply

%d bloggers like this: