not receiving JSON from php with getJSON - php

I am trying to pass an array to the browser using php and jquery but I the when I try to use the 'data' returned from php's encode_json, it comes up undefined. I'm just learning php, jquery, and json and so far haven't found very good documentation on alot of this stuff, especially json, even in the books I have. Thanks in advance!
Here is a stripped down version of the jquery I have
$(document).ready(function(){
var jsonResult;//I will want to be able to use the data in other functions
$.getJSON("json.php", function(data){
jsonResult = data;
var str;
var nuts = [203,204,205,207];
str = '<p>' + data[nuts[0]].NutraDesc + '</p>';
$('#stuff').html(str);
}
);
});
This is the php:
include_once 'databasePHP.php';
$json_tst = $db->query( "SELECT def.Nutr_No, NutrDesc, Nutr_Val, Units
FROM nutr_def as def JOIN nut_data as data ON def.Nutr_No = data.Nutr_No
WHERE data.NDB_No = 1001 LIMIT 0, 2");
$food = array();
while($row = $json_tst->fetch(PDO::FETCH_ASSOC))
{
$Nutr_No = $row['Nutr_No'];
$food[$Nutr_No][] = array(
'NutrDesc' => $row['NutrDesc'],
'Nutr_Val' => $row['Nutr_Val'],
'Units' => $row['Units']
);
};
echo json_encode($food);
?>
which returns this json which I checked on jsonlint.com and it said it was valid:
{"203":[{"NutrDesc":"Protein","Nutr_Val":"0.85","Units":"g"}],"204":[{"NutrDesc":"Total lipid (fat)","Nutr_Val":"81.11","Units":"g"}]}

It probably doesn't work because the numbers should be strings. Try to add quotes around the numbers in nuts, like this:
var nuts = ["203","204","205","207"];
The following probably works as well:
str = '<p>' + data[String(nuts[0])].NutraDesc + '</p>';
Also, have you tried adding console.log(data); to the getJSON function to make sure it receives the JSON?
EDIT:
Here is a working JSFiddle from your code:
http://jsfiddle.net/rKLqM/
Things that were wrong:
you weren't parsing the result as JSON (JSON.parse)
NutraDesc was spelled wrong
You didn't convert the numbers to strings
You needed to add [0] to the jsonResult because there's an extra array within it (see the [])

In Javascript object property can be accessed with obj["propName"]
So, change
var nuts = [203,204,205,207];
to
var nuts = ["203","204","205","207"];

Related

Using array_push to add elements to array

I have an array & I'd like to add data to the array using PHP. I can't add it directly.
How would I do this using array_push?
<script type="text/javascript">
var parks = [{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png"}]
</script>
You can try:
//if your JSON string on server side <--PHP-->
$park = json_decode([{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png"}],true);
$park['key'] = 'someValue';
$newJSON = json_encode($park);
// if your JSON string on client side <--JS-->
var parkObj = JSON.parse(park);
parkObj.key = 'someValue';
console.log(JSON.stringify(parkObj));
//[{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png","key" : "someValue"}]
I found http://www.php.net/manual/en/function.array-merge.php and feel this will do the job for me - thanks for your input.

Regex find string inside json string on html page

I have some html code, which also includes a javascript tag and some json inside.
The json object looks like this:
var data = {"service_notice":"111111-aa-bb-222222"}
I would like to extract the value for service_notice. How can this be done with regex?
I am also concerned that it could be formatted slightly differently:
var data = {"service_notice" : "111111-aa-bb-222222"}
or
var data = {
"service_notice" :
"111111-aa-bb-222222" }
You can use json_decode
json_decode(substr($code, strpos($code, "{")-1, strpos($code, "}") - strpos($code, "{") + 2), true)
will yield an array that looks like
array("service_notice"=>"111111-aa-bb-222222");
Thanks #HamZaDzCyberDeV

JSON object "undefined" error in Javascript

I am uploading a file using PHP and want to return the file name and the file status to javascript. In PHP I create the json object by:
$value = array('result' => $result, 'fileName' => $_FILES['myfile']['name']);
print_r ($value);
$uploadData = json_encode($value);
This creates the json object. I then send it to a function in javascript and recieve it as a variable called fileStatus.
alert (fileStatus);
It displays
{"result":"success","fileName":"cake"}
which should be good. But when I try and do
fileStatus.result or fileStatus.fileName
I get an error saying that they are undefined. Please help I'm really stuck on this. Thanks.
The fileStatus is just a string at this point, so it does not have properties such as result and fileName. You need to parse the string into a JSON object, using a method such as Firefox's native JSON.parse or jQuery's jQuery.parseJSON.
Example:
var fileStatusObj = jQuery.parseJSON(fileStatus);
If the alert displays {"result":"success","fileName":"cake"} then you probably still have to turn the string into a JSON object. Depending on the browsers you are developing for you can use the native JSON support or the JSON.org implementation to turn your string into an object. From there on it should work as expected.
When you are setting the variable, do not put quotes around it. Just set the variable like this:
var fileStatus = <?php echo $uploadData; ?>;
or:
var fileStatus = <?=$uploadData?>;
Do not do this:
var fileStatus = '<?php echo $uploadData; ?>';

Suggestive Search From JS Array, Possible?

Ok so what i want to be able to do is to perform a suggestive style search using the contents of an array instead of a doing a mySQL database query on every keyup.
So imagine a javascript object or array that is full of people's names:
var array = (jack,tom,john,sarah,barry,...etc);
I want to then query the contents of this array based on what the user has typed into the input box so far. So if they have typed 'j',both jack and john will be pulled out of the array.
I know this is possible via php mysql and ajax calls, but for reason of optimization I would like to be able to query the js array instead.
Hope someone can help me with this!
W.
as the name suggests, this finds elements of an array starting with the given string s.
Array.prototype.findElementsStartingWith = function(s) {
var r = [];
for(var i = 0; i < this.length; i++)
if(this[i].toString().indexOf(s) === 0)
r.push(this[i]);
return r;
}
// example
a = ["foo", "bar", "fooba", "quu", "foooba"];
console.log(a.findElementsStartingWith("fo"))
the rest is basically the same as in ajax-based scripts.
http://wwwo.google.com?q=autosuggest+using+javascript
AJAX calls fetch the contents from another serverside script files. You already have your data in the JS. Read a AJAX tutorial doing this. Then, just remove the parts where AJAX calls are made and replace it with your array's contents, and you're good to go.
I ended up using the following function to build my AJAX free instant search bar:
Example JS object being searched:
var $members = {
"123":{firstname:"wilson", lastname:"page", email:"wilpage#blueyonder.co.uk"},
"124":{firstname:"jamie", lastname:"wright", email:"jamie#blueyonder.co.uk"}
}
Example of function to search JS object:
$membersTab.find('.searchWrap input').keyup(function(){
var $term = $(this).val(),
$faces = $membersTab.find('.member'),
$matches = [];
if($term.length > 0){
$faces.hide();
$.each($members,function(uID,details){
$.each(details,function(detail,value){
if(value.indexOf($term) === 0){//if string matches term and starts at the first character
$faces.filter('[uID='+uID+']').show();
}
});
});
}else{
$faces.show();
}
});
It shows and hides users in a list if they partially match the entered search term.
Hope this helps someone out as I was clueless as to how to do this at first!
W.

Parsing javascript arrays in PHP

I can't seem to figure out how to get a JS array into PHP.
What I have to work with looks like this:
var arrLow = [
{
"e": "495864",
"rank": "8678591",
"rankmove": "<p><img src='up.php?uStyle=144'> UP 495864"
},
{
"e": "104956",
"rank": "-",
"rankmove": "<p><img src='up.php?uStyle=145'> DOWN 1"
},
{
"e": "0",
"rank": "0",
"rankmove": "<p><img src='up.php?uStyle=975'> NEW"
}
]
json_decode and others just return NULL, google only returns some strange way to use serialize() with a HTTP POST from a JS-understanding browser which really can't work here
Does anyone have any clue how :x
==========================================================================
edit: Thanks guys! Didnt know it was so easy
<?php
$json = file_get_contents('24d29b1c099a719zr8f32ce219489cee.js');
$json = str_replace('var arrLow = ','' ,$json);
$data = json_decode($json);
echo $data[0]->e;
?>
You can use json_decode() for this. The trick is to leave away the var arrLow = part (so that only the array itself is left). You can assign the value to the php variable $arrLowlike this:
$js = '[ {"e" : "495864", ...';
$arrLow = json_decode($js);
A quick'n'dirty hack to remove the beginning would be to use the strstr() function.
$js = strstr('var arrLow = [ {..', '[');
2 options:
Just remove the var arrLow = at the front (might need a regex if its variable), and parse as json.
Go for full on javascript parsing
//define javascript array
>var mainArray = {};
> // inner loops
mainArraySub['XXX'] = [];
mainArray = JSON.stringify(mainArray);
passing javascript array content in jquery ajax request as
$.ajax({
type: "POST",
data:{paramval:mainArray},
dataType: "json",
url: url,
success: function(msg){
}
});
in POST request you will get as below
{"row1":{"0":{"nnnn":"aaaa"},"1":{"Movie":"aaaa"},...}
// in a.php file call as below
$Info = $_REQUEST['rowdata'];
$tre = json_decode(stripslashes($Info),true);
var_dump($tre);
According to the JSONLint validator this is valid JSON (without the var arrLow =). So any good json_decode() implementation should do the trick. Maybe the implementation you are using has certain limitations? The JSON.org website has a neat list of links to implementations of json_decode in PHP (and lots of other languages too). You can be sure to find one that does work.

Categories