To create an HTML form, submit it and return an array of values from the external program, I'm using JSON to help in this task. If you've been to the JSON website, it's pretty nebulous from the introduction.
I just want to know the structure of the data JSON creates and how to decipher it.
- In Prototype, collect the form elements to send to the external program using Form.serialize('myform') where 'myform' is the form's id= value. You can use that as the parameter value in the options field for the Ajax.Updater.
- Send that to the external program with a post method so you don't send it in the url parameters (more secure for login programs).
- The external program can refer to the form elements from a post command using the form element id= value as the parameter. E.g., in PHP, you'd use $thefield = $_POST['theformfield'];
- To send the data back to the Prototype Javascript, create a hash array. E.g., in PHP, you can do something like this.
<?
$thefield = $_POST['theformfield'];
// ... Some code here to select from a database or other stuff...
$data[] = array(
'access' => 'y',
'firstname' => $results['db_firstname']
);
header('Content-type: application/x-json');
echo json_encode($data);
?>
The header tells the receiving program that the output is JSON formatted.
Yes, the json_encode() is a PHP command to format the return data.
The echo sends the data back to whatever script called this routine. - Back at the Prototype script, you need to decipher the incoming data from the external PHP file. I did this with the following line:
onSuccess: function(returndata) {
var reply = returndata.responseText.evalJSON(true);
Where evalJSON parses the incoming array and true will render the input safe.
Okay, so now we have something back at the Prototype Javascript. What now? - To use the parsed array in the Prototype Javascript, your parameter will look something like this.
myname = reply[0].firstname;
Now, you can use the returned array elements in the Prototype Javascript.
That's it for now.
No comments:
Post a Comment