0

I am creating a page that will read, write, and modify data in a mysql database. I am using php with codeigniter to perform the queries however the page that the user will see I am powering with javascript, dynamically filling and changing the data based on the user selections. To do this I am passing lots of data back and forth from php to javascript functions and vice versa, but I am wondering if there is a better way of formatting the data. For example here is a javascript function that uses XMLHttpRequest to call a php function and get the result:

var myarray = new Array(2);
myarray[0] = document.getElementById("my_input").value;
myarray[1] = document.getElementById("my_select").value;
xmlhttp.open("POST", "my_url/my_function/"+myarray.join('|'), false);
xmlhttp.send();
document.getElementById("my_element").innerHTML=xmlhttp.responseText;

I simply do an explode() on the string passed to the php function and execute the necessary queries. This seems like a very awkward interaction between php and javascript. Is there a better, or at least different, way to do this?

4

1 Answer 1

3

JSON (JavaScript Object Notation) seems to be what you are looking for. You can turn pretty much all kind of Javascript variables into a string using JSON.stringify and later recover the original structure in php using json_decode, and viceversa using json_encode and JSON.parse.

See:

Sign up to request clarification or add additional context in comments.

3 Comments

Is this not basically what I am emulating using the javascript .join() and php explode() functions except that it could be used with a datatype that is not a string?
@WillSampson technically yes, but it can handle nested arrays or objects for instance, or named properties, scenarios where your method could break. Plus, json is a pretty common standard used almost everywhere nowadays.
Bear in mind JSON.stringify is not natively supported in IE 7 or 6, so you will need to use a parser like json2 is you wish to support them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.