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.
Related
I am using currencylayer JSON API to get realtime currency conversion value - does anybody know how I could grab both the "result" value and the "quote" value from the API response below using PHP?
I am new to PHP, and I am wondering if it's possible to store it in a variable.
This is the JSON:
{
"success":true,
"terms":"https:\/\/currencylayer.com\/terms",
"privacy":"https:\/\/currencylayer.com\/privacy",
"query":{
"from":"CAD",
"to":"GBP",
"amount":234
},
"info":{
"timestamp":1432829168,
"quote":0.524191
},
"result":122.660694
}
I have played around with file_get_contents("URL") but I didnt understand how to get a single value out.
Request URL looks like this:
https://apilayer.net/api/convert?access_key=...&from=CAD&to=GBP&amount=234
Thanks for the help!
Ok, lets say that json response is in a variable named $response, you must use json_decode and then do as follows:
$decoded = json_decode($response);
$result = $decoded->result;
$quote = $decoded->info->quote;
var_dump($result, $quote);
Try this
$jsonArray = file_get_contents($yourUrl);
$jsonObject = json_decode($jsonArray);
echo $jsonObject->result;
echo $jsonObject->info->quote;
I am new to jQuery. I have got an error when I try to get data from fileresult.php.
fileresult.php
$return_arr = array();
$row_array['status'] = 'Ok';
$row_array['message'] = 'good'
array_push($return_arr, $row_array);
echo json_encode($return_arr);
JSON output
[{"date":"2014-03-15","status":"ok","message":"good"}]
get_result.js
$.post('file.php', $("form").serialize(), function(data) {
var status = data['status'];
alert(status);
});
When I alert data, it shows undefined. Somebody please help me. How can I show the correct data.
You have two problems.
You are outputting "HTML"
PHP defaults to claiming that its output is HTML. jQuery will see this claim and treat it as such instead of parsing it as JSON.
Override PHP's default with:
header("Content-Type: application/json");
You have an array
You are accessing data.status but the top level data structure you are outputting is an array so you need data[0].status with that data.
You don't have multiple objects though, so (unless you plan to add more in the future) it would make more sense to return
{"date":"2014-03-15","status":"ok","message":"good"}
instead of
[{"date":"2014-03-15","status":"ok","message":"good"}]
So remove everything to do with $return_arr and:
echo json_encode($row_array);
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"];
Pardon me if I am making a silly mistake here... But I am little new to PHP...
I have been stuck at this for long time.
I have tried several methods but I am only able to pass ONe table row , not multiple rows
I've even tried with the following approach, but I landed with the same error.
http://www.electrictoolbox.com/json-data-jquery-php-mysql/
Here's what I am trying to do :
1) Make Ajax call using JQuery, to fetch data from server.
$.ajax({
url: 'test.php', //the script to call to get data
data: "",
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
//use "data"
}
2) fetch table data from MySql database, using PHP.
$result = mysql_query("SELECT username,characterType FROM usertable");
3) pass ALL of the rows as JSON data, back to the calling function.
//This works , Returns one row and I am able to get the result back at AJAX end
$array = mysql_fetch_row($result);
echo json_encode($array);
mysql_fetch_assoc($result) FAILS with the following error :
XML Parsing Error: no element found Location: moz-nullprincipal:{6b1***-****somecrap numbers****-***86} Line Number 17, Column 3:
$array = mysql_fetch_assoc($result);
echo json_encode($array);
I have even tried using mysql_fetch_array($result, MYSQL_NUM) as suggested in the other relevant questions, but I am not able to workaround the problem.
Any Help is greatly appreciated.
============
UPDATE:
I may be wrong but just wanted to know, if this could be the possibility or not... Can this be a local setup related issue ? A Configuration mistake .. ?
I have done my localhost setup using "XAMPP installation" [ Apache / MySQL / Tomcat ... bundled in one package ] ...
When I run the file as "PHP application" it runs just fine ... I am able get "all rows" But when I deploy the code on my apache servers it doesn't run ... The whole php file comes as a response , with "XML parsing Error" [ I am using firebug to track the response ]
Thanks
Pranav
A few things to note here:
As Rup mentioned, $array = mysql_fetch_row($result); only returns a single row.
The other thing is that test.php does not currently return a JSON object; to see whats going on, it helps to comment out dataType: 'json', and use console.log(data); to see what is being returned. Your response probably looks something like this:
["someUsername","someChartype"]
The format of the object you are expecting is probably something more like:
[{"username":"foo","chartype":"admin"},
{"username":"bar","chartype":"user"},
{"username":"fum","chartype":"guest"}]
To get the format of the associative array, use mysql_fetch_assoc($result) instead; that will give
{"username":"someUsername","chracterType":"someChartype"}
To summarize, update your php code to:
Loop through your results, pushing them onto an array.
Encode the entire array at the end
$outputArray = array();
while( $row = mysql_fetch_assoc( $result ) ){
array_push($outputArray, $row);
}
echo json_encode($outputArray);
Take a look at How to build a JSON array from mysql database for more info. Also, as one of the answers mention, its worth using PDO rather than mysql_*
Don't start manually composing a JSON string as #Tuanderful indicated. Let json_encode() handle that -- just give it the right data. Try something like this:
$records = array();
while ( $record = mysql_fetch_assoc( $result ) ) {
$records[] = $record;
}
echo json_encode( $records );
Well I would to like this:
$.ajax({
url: 'test.php', //the script to call to get data
//data: "",
dataType: 'json', //data format
success: somevar
})
var somevar = function(data) //on recieve of reply
{
//use "data"
somevar2 = jQuery.parseJSON(data)
//now You can enter each row/cell from db(/php) like this
// somevar2[0] would be the first row from php
//if You want to do something with every line You can use:
//$.each(somevar2, function(key,value){
//$('#divname').html(value.cellnameoftable)
}
I hope it will help ;)
So I'm posting an array of objects in a JSON string using javascript to a PHP script and I'm having real problems decoding it in the php.
My javascript is as follows:
$.ajax({
type: 'POST',
url: "question_save.php",
data: {myJson: JSON.stringify(jsonArray)},
success: function(data){
alert(data);
}
});
The string sent to the PHP looks like this:
[{"content":"Question text"},{"answerContent":"Some answer text","score":"234","responseChecked":0,"responseContent":""},{"answerContent":"","score":"0","responseChecked":0,"responseContent":""}]
If I echo $_POST['myJson'] I get this:
[{\"content\":\"Question text\"},{\"answerContent\":\"Some answer text\",\"score\":\"234\",\"responseChecked\":0,\"responseContent\":\"\"},{\"answerContent\":\"\",\"score\":\"0\",\"responseChecked\":0,\"responseContent\":\"\"}]
Yet when I want to decode the JSON and loop through it like this...
$json = $_POST['myJson'];
$data = json_decode($json, true);
foreach ($data as &$value) {
echo("Hi there");
}
...I get this error:
Warning: Invalid argument supplied for foreach() in /home/thecrime/public_html/test1/question_save.php on line 15
I really don't understand what silly mistake I'm making, is it something to do with the back slashes?
Any help much appreciated!
Thanks,
-Ben
Use stripslashes ( $string ) - http://php.net/manual/en/function.stripslashes.php
This should work
$json = $_POST['myJson'];
$json_string = stripslashes($json)
$data = json_decode($json_string, true);
// simple debug
echo "<pre>";
print_r($data);
However, as already pointed by the others, it's better to disable magic_quotes_gpc.
Open your php.ini file and search for this row:
magic_quotes_gpc = On
Set it to Off and restart the server.
This has to do with Magic Quotes
Is better to disable this annoying old feature and forget those problems.
You can disabled following these instructions.