For the sake of argument, let’s assume you have to pass a plethora of JavaScript values to PHP through a POST submission. Maybe it is an array of numbers or simple point objects. You want to do this quickly and don’t want to be bothered with using a hidden form or having to list out a ton of fields in some long data string that you give to a jQuery $.ajax() call. Wouldn’t it be handy if you could just package up the values, make a simple AJAX call and see the values come through on the other side in a PHP $_POST object (and even be able to rebuild the JavaScript object in PHP)? Maybe you are passing location data from a client side JavaScript map or the web site visitor is interacting with a chart and you need to get that data back to a server quickly and easily.
Whatever it might be, we will show you a quick way to do that using JavaScript objects, jQuery’s $.ajax() method and a little JSON. This article is essentially a part 2 to my earlier article titled “The Basics of Passing Values from JavaScript to PHP and Back“.
Before we can transport any data we first have to make sure it is in a form that will transmit easily. Since it is easy to create an object in JavaScript out of just about anything, we can start with a simple object literal. We can add our data to it as we see fit (no functions however, I will explain that in a moment) and then send it on its way. Below is some code to show you how we can create a quick and dirty object and load it with some primitive data.
// Create an object using an object literal. var ourObj = {}; // Create a string member called "data" and give it a string. // Also create an array of simple object literals for our object. ourObj.data = "Some Data Points"; ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];
Ok so we have constructed a simple object. Notice here that we do not have any functions added to the object. Since functions are going to include things like scope, they will not transport easily when we go to “stringify” it in JSON process (as we show in the code below). What this object does show you is that we can include things like string data, arrays and even other object literals. With this code above I am going to be transporting an array of data point objects, each with an “x” and “y” coordinate member. When it comes through on the other side, we will have an array which we could rebuild into a series of objects and access each set of coordinates in turn. However, one trick we will have to watch out for is that even though we may have something like an array of integers, when they are transported through this process they will be converted to strings. Meaning when it comes to the PHP we should watch to make sure they are the correct data types before using them.
I am going to assume you are briefly familiar with the $.ajax() call in jQuery, but if not you can look at this reference to quickly get familiar with it. It is a rather sophisticated object to configure, but luckily for us much of it can be left out and used with just defaults. We are going to setup a URL to submit our data to (this would be the PHP script URL we would use like in the action portion of a form), the method which will use (in our case “post”), the data (which will be our JavaScript object we just built) and lastly what to do with the response from the server. Let’s take a quick look to see how that part will work…
$.ajax({ url: 'process-data.php', type: 'post', data: {"points" : JSON.stringify(ourObj)}, success: function(data) { // Do something with data that came back. } });
First thing to notice about this code is how relatively simple it is. We are not passing a long string of parameters, we are not using a long list of data values. Everything here is going to be encoded to JSON notation and packaged under this item called “points”. The JSON stringify method is well supported in browsers and even goes back to IE 8 with standards mode. When we go to access this data in PHP, “points” is going to be the key in the $_POST array. From there it is just a matter of getting the data converted back from JSON and accessible. But more on that in a second.
I wanted to take a moment to remind you that due to security reasons, many browsers won’t let JavaScript make calls to other pages that are not on the same domain as the calling script. In our example if process-data.php was a full URL to some other web site, we are going to hit a security brick wall. I have written an article on some tricks you can use to get around some of these limitations if you would like to read more about that. For now we will assume process-data.php is on the same domain as the page with this AJAX code in it.
The last part of this whole process is to access the data we just sent on the PHP side. Since we used the “post” method to send this data, we would use the $_POST array in PHP to get at the data. We sent our package marked with the tag “points” so that is the key we are going to use to get the data out. I want to simply print the “data” data member value and print the X/Y coordinate of the first object in our array of objects. This is how that looks…
// Test if our data came through if (isset($_POST["points"])) { // Decode our JSON into PHP objects we can use $points = json_decode($_POST["points"]); // Access our object's data and array values. echo "Data is: " . $points->data . "<br>"; echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y; }
Again the code is not terribly complex here. We are simply testing to make sure that we have a $_POST variable with the key “points” exists. Again, this matches that key we used when sending the data in JavaScript. Once we determined that made it through, we can decode the JSON. Remember this is coming in as a string of data representing the objects in the JavaScript objects. Thus we need to use the json_decode() PHP function to decode this string into objects PHP will then use as normal.
We can access our data property using this new object variable I called “$points” and I can access the array of points using standard array syntax. Each item in the array was an object literal back in our JavaScript. This will translate to them being objects in PHP and each having a “x” and “y” data member. To access the first point we use the array index of zero and grab the X and Y through standard object access notation.
This process is relatively simple for sending a ton of primitive data types across AJAX to PHP. We have shown an example of sending both string data as well as arrays and objects all with a relatively simple notation in JavaScript. We packaged the data up into an object, converted it quickly to JSON, sent it via POST, accepted it in PHP and decoded it into PHP objects we can use. We also briefly touched on some pitfalls to this process including the idea that functions can’t be included when we send the JavaScript, security limitations with AJAX and browser limitations regarding the JSON.stringify method.
I hope this code helps you with your data passing problems and gives you some great ideas to efficiently pass data from JavaScript to PHP. If you haven’t checked out my ebook for project ideas to try some of this code be sure to check it out. Thanks for reading! 🙂