So I'm in the midst of a rather sticky problem. I'm coming close - so close! - to solving it but not quite there. I've seen lots of examples but none that do just exactly what I want.
On a php page myreqpdo.php, I recover some data lines from a MySQL table and store them in a two-dimensional array. On my page index.php, I need to access this array via JavaScript and play with it a bit before sending it to what I need to fill.
Here is myreqpdo.php:
$locWanted = $_POST['searchTerm'];
echo json_encode(getVillesCPs($locWanted));
function getVillesCPs ($searchTerm) {
// code to access DB here
return $resultats;
}
I found this example using jQuery, but it's for an instance in which one would just like to insert the list directly into the code without any further manipulation:
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>
<!-- this UL will be populated with the data from the php array -->
<ul></ul>
<script type='text/javascript'>
$(document).ready(function(){
/* call the php that has the php array which is json_encoded */
$.getJSON('json_encoded_array.php', function(data) {
/* data will hold the php array as a javascript object */
$.each(data, function(key, val) {
$('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + val.email + ' ' + val.age + '</li>');
});
});
});
</script>
</body>
</html>
That won't work for me, because this function is one that is triggered based on search parameters. I need something like the following pseudocode:
<script>
var myArray = {code to recover PHP array};
// manipulations for myArray here, using data to fill values of items on page
</script>
I keep thinking the answer is right under my nose, but I am really not seeing an example like what I want! Any ideas?
var myArray = data;although you don't really need a new variable of course...$.getJSON('json_encoded_array.php', {searchTerm: ???}, function(data) {