Chris Nizzardini

Salt Lake City, Utah Developer / Human / Blogger

using JSON to pass JavaScript arrays to PHP via Ajax

We don’t use PHP 5.x at work so I needed to install JSON via PEAR. In your PHP script include the JSON.php file and instaniate the object.

1
2
include_once('JSON.php')
$json = new Services_JSON();

In your javascript include a reference to json.js minus the comment marks:

1
(<)script src="json.js" type="text/javascript"(>)(<)/script(>)

Now create a simple javascript method that will perform an HTTP GET and pass an array broken down into JSON to your PHP script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
	function testJSON()
	{
		var testArr = new Array();
		testArr[0] = 0;
		testArr[1] = 1;
		testArr[2] = 2;
		testArr[3] = 3;
		testArr[4] = 4;
		var testJSONArr = testArr.toJSONString();
		var url = "mypage.php?func=testJSON&jsonArr=" + testJSONArr;
		if(XMLHttpRequestObject)
		{
			XMLHttpRequestObject.open("GET", url, true);
			XMLHttpRequestObject.onreadystatechange = function()
			{
				if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
				{
					try
					{
						var txtDocument = XMLHttpRequestObject.responseText;
						txt.innerHTML = txtDocument;
					}
					catch(err)
					{
						txt.innerHTML = "Description not found.";
					}
				}
			}
			XMLHttpRequestObject.send(null);
		}
	}

At the top of mypage.php you should have this:

1
2
3
4
5
6
7
	switch ($_GET[func])
	{
		case 'testJSON':
			echo $myPHPObj->testJSON(urlencode($_GET[jsonArr]));
			break;
	}
	return;

Your PHP object will have a method in it like this:

1
2
3
4
5
6
7
8
9
	function testJSON($jsonArr)
	{
		$json = new Services_JSON();
		$jsonArr = $json->decode(urldecode($jsonArr));
		foreach($jsonArr as $element)
		{
			echo "js array element: $element<br/>"; 
		}
	}

Thats it. My first use of JSON. I was really getting tired of packing data in long strings with strange explode points and felt XML was to bloated for what I was doing.

Chris Nizzardini has been developing web applications since 2006. He lives and works in beautiful Salt Lake City, Utah. If you’re interested in hiring me for contract work please visit IO Spring LLC.

Twitter Google+ 

One thought on “using JSON to pass JavaScript arrays to PHP via Ajax

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>