I need to pass a php variable to a jquery function. the php variable is an array of unknown size. is there a way to pass each member of the array to be processed individually by the function?
2 Answers
You can use JSON to print the array and parse that to receive a JS object.
I assume you use AJAX (directly printing into the javascript source is possible but ill-advised).
Your php script needs to print output directly:
print_r(json_encode($data_array));
And on the receiving end use $.parseJSON:
var data_array = $.parseJSON(ajax_result);
2 Comments
Fabrício Matté
echo instead of print_r for passing it to a JS var/Ajax response btw.Maxim Kumpan
@FabrícioMatté There is little difference in this case. print_r does not format the data in any way unless it is an object or an array. Also, you can rig print_r to return the value and use it in expressions, which is impossible for echo.