I looked for this in previous threads so apologies if has been answered. My javascript is the following, where the data parameter is a string which refers to a table in a MySQL database:
getData("UKnatgas");
function getData(data){
$.getJSON("service.php?action="+data, function(json) {
$.each(json.UKnatgas,function() {
var info = this.UKnatgas;
$('#UKnatgas').append( info );
});
});
}
Firstly, I want to pass the string “UKnatgas” into the sub $.each function so that it would read:
$.each(json.data,function() {
var info = this.data;
$('#data').append( info );
});
But this doesn’t work? Could you tell me why?
The second part is getting rid of all instances of “UKnatgas” in the php file:
if($_GET){
if($_GET['action'] == 'UKnatgas'){
$query = "SELECT UKnatgas FROM UKnatgas order by Date DESC Limit 1 ";
$result = db_connection($query);
$UKnatgas = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
array_push($UKnatgas, array('UKnatgas' => $row['UKnatgas']));
}
echo json_encode(array("UKnatgas" => $UKnatgas));
exit;
}
}
So to summarise, I’d like to initialise the function getData(data) with a string which is propagated into the javascript function and then the php file. Is this possible?
Thanks!
The PHP is easy, although I would allow for some type of check for errors and maybe even check for hack attempts as you are putting a user editable string. This may allow for
MySQL Injectionso be careful.If you can, use
mysql_real_escape_stringwhen ever possible. See link for more information: http://www.php.net/manual/en/function.mysql-real-escape-string.phpAnd not sure exactly but this should work for the JSON
http://api.jquery.com/jQuery.getJSON/
I tested it in your case and you will need to do the following to access the data. Now this is using JSON as an Associative Array which it isn’t, but not 100% how to do it otherwise.