Jump to content

PHP AJAX Help Requested!


spoonraker

Recommended Posts

Quite simply, I am trying to pass a php array to javascript...I am using the sajax.php script (http://www.modernmethod.com/sajax/) to add php functions to javascript for data updating without using form posts.Basically what I want to happen is when I click a button a javascript function is run, which runs a php function, which returns a multidimensional array of data pulled from an SQL database to a javascript callback function that can then display the data in whatever method I choose.Here's some code in case that didn't make sense...

<?phpinclude("ajax/php/Sajax.php");include("functions_noclass.php"); // this is the file that contains the getAll() php method											 //that method just querys a DB and stores the data in a multidimensional arraysajax_init();sajax_export("getAll");sajax_handle_client_request();?><html><head><title>AJAX Table Display</title><script><?phpsajax_show_javascript();?>function displayNames(){	x_getAll(stringDisp);}function stringDisp(result){		 /*	 Right now I simply have this method outputting the array parameter.	 What I want this method to do is to take a php array as the parameter, put it	 in a javascript array, and then the displaying will be done however I want.	 */	document.getElementById("div").innerHTML += result;}</script></head><body><input type="button" value="Click me" onClick="displayNames();"><div id="div"></div></body></html>

The getAll() php method isn't shown here, but all it does query a database and store the results in a multidimensional array. $array[0]['first_name'] for example would be the first_name value for the first row of data.Now...I came up with a rather low-tech solution to this by simply taking the array generated by the SQL query and converting it to a massive string and passing the string to the javascript...see belowthe getAll() php method does this

while($row = mysql_fetch_array($rs)){			$fname = $row['first_name'];			$lname = $row['last_name'];			$email = $row['email'];			$city = $row['city'];			$state = $row['state'];			$zip = $row['zip'];			$phone = $row['phone'];			$ptype = $row['pet_type'];			$pname = $row['pet_name'];			$arrayString .= "[\"$fname\",\"$lname\",\"$email\",\"$city\",\"$state\",\"$zip\",\"$phone\",\"$ptype\",\"$pname\"],";	}	closeConnection($conn);	return $arrayString;

and the javascript callback looked like this...

function stringDisp(result){		eval("var arr=new Array("+result+"[]);");	var x = 0;	var y = 0;	while(x<(arr.length-1)){		while(y<(arr.length-1)){			document.getElementById("div").innerHTML += arr[x][y];			y++;		}	x++;	document.getElementById("div").innerHTML += "<br>";	y=0;	}	}

That worked, believe it or not. I could access my entire SQL query from inside javascript using arr[ROW][FIELD]. I no longer had my associative keys like 'first_name' to access data with, but it was all there and it worked.My boss tells me that I'm setting myself up for all sorts of trouble if somebody enters their name with a special character like " ' \...whatever. I tell him php has a htmlentities() function that will convert those to their safe versions like & quot ; and such...He tells me it's still not good enough and I need to figure out how to serialize the array in php and then pass it to javascript for usage.I have absolutely not even the slightest clue how to do that. If I use serialize($array) in the php getAll() function and then return that and spit it out it looks like this...

a:9:{i:0;a:23:{i:0;s:5:"Spoon";s:9:"last_name";s:5:"Spoon";i:1;s:4:"Paul";s:10:"first_name";s:4:"Paul";i:2;N;s:6:"suffix";N;i:3.......................

Any ideas? Or was I on the right track originally?

Link to comment
Share on other sites

You can't serialize a structure with PHP and then expect to be able to unserialize it with a different language, serialized objects in PHP are meant to be unserialized with PHP also and converted back to a PHP data structure. You're sort of serializing the array yourself. The only character that can cause a problem is a double quote, so you might need to make sure you escape double quotes when you serialize the array.

Link to comment
Share on other sites

I don't think it's impossible. People can already pass javascript arrays to php, just not the other way around. Also from reading it seems that there are ways to do it, I hear a lot about this JSON script that I have yet to figure out.check this outhttp://www.modernmethod.com/sajax/forum/vi...highlight=array http://www.sitepoint.com/blogs/2004/04/22/...for-javascript/they seem to be on track with what I'm trying to do, but that article makes no sense to me lolI'm not too worried about it, since my method did work I can always use it along with some escape character removal/conversion function, I was just told that it is in fact possible to unserialize data in a different language and was wondering if anybody knew how to apply that to my particuar problem.

Link to comment
Share on other sites

Well, theoretically there's no problem with unserializing a PHP object in Javascript, assuming that Javascript understands this syntax:a:9:{i:0;a:23:{i:0;s:5:"Spoon";s:9:"last_name";s:5:"Spoon";i:1;s:4:"Paul";s:10:...I don't know if it does though. Someone might have written some type of library that can parse that up and convert it back to an array in Javascript though. But your original solution is fine if you just add escaping for double quotes in the values.

Link to comment
Share on other sites

Serializing it is the best way to go. That's what your original code was doing, it just serializes it manually instead of using the PHP function, and does it in a way that Javascript can reassemble it. I'm not aware of another way to move a complex data structure from PHP to Javascript.

Link to comment
Share on other sites

You can escape the double quotes like this:

$fname = str_replace('"', '\"', $row['first_name']);

Javascript will convert that back to a double quote automatically, that is the escape character for Javascript as well as PHP.

Link to comment
Share on other sites

htmlentities will work, but it's making the string a lot longer then it needs to be. It's sort of overkill. Instead of sending this:""""<<>>><""()*#* (18 bytes)You're sending this:""""&lt,&lt,>>><""()*#* (66 bytes)When you could just be sending this:\"\"\"\"<<>>><\"\"()*#* (24 bytes)It wouldn't matter too much, but the longer string means it's going to take longer for the page to get the response back.

Link to comment
Share on other sites

true....but I like htmlentities since it converts every single special character, plus html code all in one method, as opposed to just changing double quotes. Plus I'm not intending anything in any of the fields to be very long, or contain any special characters, I'm just trying to prevent crashes if somebody does decide to do it.If somebody where to enter their name as "<h1>I HATE YOU</h1>" instead of actually displaying a huge message it would just display the literal string "<h1>I HATE YOU</h1>" whereas if I just replaced the quotes the html would still display their name really hugeI guess since this is just a learning exercise it doesn't really matter, i'm not going to crash my own server, and if it were an actual website I would simply not allow any special characters to be entered as opposed to converting them.anyway thanks again for the help

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...