Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog. You can find information on programming, linux, documentation, tips for code and database optimization, my thoughts and rants, and whatever else I feel like sharing. Feel free to contribute to the blog by posting comments and asking questions.
JavaScript and Ajax

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.

Related posts:

  1. HTTP POST via AJAX HTTP Request Object
  2. ajax and the xmlhttprequest object
  3. More JavaScript Array Methods (push and join)
  4. JavaScript forEach
  5. Doing Math in JavaScript umm…sucks

One Response to “using JSON to pass JavaScript arrays to PHP via Ajax”

  1. [...] In this article I gave a brief intro to using JSON to pass JavaScript arrays to PHP via Ajax. I’ve done a bit more with json since then and with the help of a co-worker discovered how to get javascript objects working together with php utilizing json. [...]

Leave a Reply