I have a problem and do not know what the problem is. I have a javascript variable in my html. which is:
var people = '{"names": ["Matthew", "Lucas", "Todd", "Roxie", "Kyle", "Ken", "Gideon"], "surnames": ["Patel", "Lee", "Ingram", "Richter", "Katayanagi", "Katayanagi", "Graves"]}';
I parse the variable on one function in my script and use it. Everything works fine.
var mydata = JSON.parse(people);
But then I need to send the data to a php file, I send it by wrtting the data to a hidden input.
var strObject = JSON.stringify(mydata);
var replaced = strObject.replace(/\//g, '');
oFormObject = document.forms['theForm'];
oFormObject.elements["jsonData"].value = replaced;
After which I try to encode it in my decode.php using:
$obj = $_POST['jsonData'];
json_decode($obj);
$s = stripslashes($obj);
var_dump($s);
But when I do a var_dump($s) I get this output:
string(147) "{"names":["Matthew","Lucas","Todd","Roxie","Kyle","Ken","Gideon"],"surnames":["Patel","Lee","Ingram","Richter","Katayanagi","Katayanagi","Graves"]}"
Thus, I cannot output the contents in $s.Any suggestions.Please let me know if you need more information. BTW, its a homework assignment and I am stuck with the last section.
try saving json_decode($obj) to a variable and var_dump that
something like
var $temp = json_decode($obj);
var_dump($temp);
the answer already is in the comments, but since this is the answer, i just post it as an answer.
you need to work with the return value from json_decode(). json_decode($obj) doesn't change the content of the variable $obj by itself:
$obj = $_POST['jsonData'];
$obj = json_decode($obj);
$obj = stripslashes($obj);
var_dump($obj);
If you are looking for name surname pairs from json , you can try this
$a = '{"names": ["Matthew", "Lucas", "Todd", "Roxie", "Kyle", "Ken", "Gideon"], "surnames": ["Patel", "Lee", "Ingram", "Richter", "Katayanagi", "Katayanagi", "Graves"]}';
$b = json_decode($a);
$c = $b->names;
$d = $b->surnames;
for ($i = 0;$i< count($b->names); $i++){
echo $c[$i]." ". $d[$i] ."<br>";
}
Related
I have a php function that will get a list of name from column in users database. What I want to do is to get all the values from the column name and insert it into an array.
What I've done from the php side is :
header('Content-type: application/json');
include ('../Core/Initialization.php');
$courseName = $_POST['courseName'];
$semester = $_POST['semester'];
$sql = mysql_query("SELECT DISTINCT `name` FROM `users` WHERE `programme` = '$courseName' AND `semester` = '$semester'") or trigger_error(mysql_error().$sql);
$column = mysql_fetch_assoc($sql);
$arr = array();
foreach($column as $value) {
$arr[] = array('name' => $value['name']); //I have tried it this way but it didn't work when I try to display the values.
}
echo json_encode($arr);//I have tried to remove the array and just json_encode($column). I have successfully print out the first values, but fail to print out the next values collected from the column.
The js function that will process/print out the name:
function nameProcess(data) {
alert(data.name); //This will only display the full values from the first(?) index
nameArray = data.name;
for (var i=0; i < nameArray.length; i++) {
alert(nameArray[i]); //But, this loop only displays one character each time of the alert. Example: Each character from the word "Hello" will show up one by one as alert.
}
}
});
Is there any better way to do this? What I want to do is, exporting all values from column name into an array, and iterate each of its value as an option of a a select box. But for now, how do I fix the problem?
First of all, don't use mysql_* functions as they are deprecated and
removed totally PHP 7.
Back to your question, you can fetch mysql multi-dimensional array with MySQL only with loop.
Corrected code:
$sql = mysql_query("SELECT DISTINCT `name` FROM `users` WHERE `programme` = '$courseName' AND `semester` = '$semester'") or trigger_error(mysql_error().$sql);
$res = mysql_query($sql); // Missing this.
$column = ;
$arr = array();
while ($value = mysql_fetch_assoc($res)) {
$arr[] = $value['name'];
}
echo json_encode($arr);
Note: The PHP MySQL commands you are using are deprecated. It's recommended to use the PDO class (as MySQLi is also deprecated).
It depends on the pre-processing you are performing, but from what I can see based on the information you provided, you are passing each element of the returned data through to nameProcess.
So a return data of
array(
array('name' => 'John Smith',
array('name' => 'Jane Doe',
array('name' => 'Foo Bar'
);
Will require the nameProcess function to be invoked 3 times.
So each time you go through to define
nameArray = data.name;
nameArray becomes a string since data.name is 'John Smith' the first invoke, 'Jane Doe' the second invoke, and 'Foo Bar' the last invoke.
So when you call
alert(nameArray[i]);
It's calling the character at position i within the string.
nameArray[0]; // 'J'
nameArray[1]; // 'o'
nameArray[2]; // 'h'
nameArray[3]; // 'n'
// etc
If you change it to:
function nameProcess(data) {
alert(data.name);
nameArray = data.name;
alert(nameArray);
}
It will alert the full name.
The way around this would be to ensure that you pass the JSON parsed data to the function without the pre-processing, in which case your original code should work if you change it to:
function nameProcess(data) {
alert(data.name);
nameArray = data.name;
for (var i=0; i < nameArray.length; i++) {
alert(nameArray[i].name);
}
}
I've read a lot of the json_decode questions, tried a variety of different things I can't this to work.
it's the bittrex api
$apikey='4058';
$apisecret='50860';
$nonce=time();
$uri='https://bittrex.com/api/v1.1/public/getticker? apikey='.$apikey.'&nonce='.$nonce.'&market=BTC-LTC';
$sign=hash_hmac('sha512',$uri,$apisecret);
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$json = json_decode($execResult,true);
I do get an output, now I just want the "Last" value
{"success":true,"message":"","result":{"Bid":0.00002130,"Ask":0.00003341,"Last":0.00002121}}
I've tried for each
foreach($json->result as $market) {
$lastPrice = $market->Last;
//this was to see if it was an echo problems, tried storing the last price in the db... I get null
$collectionGamerActions->update(array('gamer'=>$gamer),
array('$set'=>array('lastPrice'=>$lastPrice,'reached'=>1)));
//print "last price is $lastPrice";
}
I tried
$lastPrice = $json->result->Last;
and a variety of
$lastPrice = $json[0]['result']['last']
I gave up on php and tried javascript, 1st stringifying he response, then parsing it
var obj = JSON.stringify(response);
var obj =JSON.parse(obj);
console.log("last is " + obj.result.Last + " obj is " + obj);
nothing works... can I get direction in what I'm doing wrong please.
Tried some of the suggestions below
var obj = JSON.stringify(response);
var json = JSON.parse(response);
console.log(json.result.Last);
on the php side the response is generated here
$execResult = curl_exec($ch);
$json = json_decode($execResult);
echo json_decode($json, true);
results in javascript error
SyntaxError: Unexpected number var json = JSON.parse(response);
With the php suggestions
$json = json_decode($execResult);
$json = json_decode($json, true);
var_dump($json['result']['Last']);
results in NULL
As you use (note the second parameter in json_decode):
$json = json_decode($execResult,true);
You will have an associative array, so your value will be in:
$json['result']['last']
Note that $json->result->Last would work if you use json_decode() without the second parameter (the default value, false).
I may be misunderstanding your problem, but... assuming PHP is giving you the string you pasted above, then you can just use JSON.parse (no need for stringify) and grab the result from the resulting object.
var string = '{"success":true,"message":"","result":{"Bid":0.00002130,"Ask":0.00003341,"Last":0.00002121}}';
var json = JSON.parse(string);
console.log(json.result.Last); // 0.00002121
Array notation (second argument to json_decode() is true):
$string = '{"success":true,"message":"","result": {"Bid":0.00002130,"Ask":0.00003341,"Last":0.00002121}}';
$json = json_decode($string, true);
var_dump($json['result']['Last']);
Object notation (second argument to json_decode() is false):
$string = '{"success":true,"message":"","result":{"Bid":0.00002130,"Ask":0.00003341,"Last":0.00002121}}';
$json = json_decode($string);
var_dump($json->result->Last);
I've looked through various other questions on SO, but can't quite get the right answer. Basically, I have an array that needs data from a MySql database. Here's what I've tried:
var $name = "Foo",
$x = 10,
$bar =
<? php
$barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
$barArray = array();
while ($r = mysql_fetch_assoc($barQuery))
{
$barArray[] = $r['item'];
}
echo json_encode($barArray);
?>;
EDIT: I then post this to a .php file, and print the returned data:
$.post("file.php", {bar: JSON.stringify($bar), name: $name}).done(function(data)
{
$('body').html(data);
window.print();
setTimeout("location.reload(true)", 500);
});
However, I get an error saying "syntax error, unexpected T_VARIABLE". Is it not possible to populate a JS array this way, or is there another way to do it?
var $name = "Foo",
$x = 10,
$bar = "
<?php
$barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
$barArray = array();
while ($r = mysql_fetch_assoc($barQuery))
{
$barArray[] = $r['item'];
}
echo json_encode($barArray);
?>";
You have a superfluous space inside the PHP opening tag:
<? php
^--- this shouldn't be there
As it stands, the <? is parsed as a short open tag, and so the php is parsed as a(n undefined) constant, which is immediately followed by $barQuery—hence the syntax error that you see: unexpected T_VARIABLE.
I'm creating a json in javascript in that way
jsonArr.push({
position: 'WN',
wind: windWN,
wave: waveWN,
sea: seaWN
});
var myJsonString = JSON.stringify(jsonArr);
I'm sending it via an AJAX method with jsonData: jsonData:Ext.encode(myJsonString)
My json array looks like that when I send it :
In PHP side, I'm getting the Json and decoding it that way :
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata, true);
I tried print_r( $rawpostdata2[1]); and got '{', as the second character of the "string", and I can't understand why.
In the other side, I tried print_r($rawpostdata), cut/past the result in a $string and retest my json_decode like that :
$rawpostdata = file_get_contents("php://input");
// print_r($rawpostdata);
$string = '[{"position":"N","wind":"2","wave":"65","sea":"65"},{"position":"E","wind":"3","wave":"5","sea":"6"},{"position":"S","wind":"56","wave":"4","sea":"8"},{"position":"W","wind":"1","wave":"56","sea":"84"},{"position":"NE","wind":"5","wave":"6","sea":"65"},{"position":"ES","wind":"6","wave":"45","sea":"6"},{"position":"SW","wind":"69","wave":"8","sea":"4"},{"position":"WN","wind":"7","wave":"8","sea":"56"}]';
$rawpostdata2 = json_decode($string,true);
print_r ($rawpostdata2[1]);
It gives me the correct result !
Array (
[position] => E
[wind] => 3
[wave] => 5
[sea] => 6 )
Do you have some explanations?
EDIT : I make it working by making another json_decode
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata,true);
$rawpostdata3 = json_decode($rawpostdata2,true);
But I don't really understand...
First, you create json string:
var myJsonString = JSON.stringify(jsonArr);
Then you encode the resulting string into json again:
Ext.encode(myJsonString)
Thus, you have to json_decode() twice in PHP.
Try using $_POST instead of file_get_contets() which gives you a string.
you need to do a type cast on the result of json_decode like this:
<?php
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = (array) json_decode($rawpostdata,true);
?>
I hope this works for you.. Cheers..!!
I have the following javascript file
sample.js
var sampleName = "a nice name";
var sampleObject = {name: 'sample', type: 'text'}
I want somehow to parse this file with php and generate the equivalent values, objects into php in order to use them there.
So for example after pasring the js file I would like somehow to be able to access the values with something like that
echo $javascriptParser->sampleObject->name; //should return sample
echo $javascriptParser->sampleName; //should return a nice name
So far I was not able to find anything like that?
Does anyone know if something like that exists out there?
Thanks in advance.
pass your string and do some replacements....
$json = "{name: 'sample', type: 'text'}";
$search = array(":",", ","{","'");
$replace = array("\":",",\"","{\"","\"");
$json = str_replace($search, $replace, $json);
$obj = json_decode($json);
echo $obj->name;
you can write it to a function like:
function convert($str)
{
$search = array(":",", ","{","'");
$replace = array("\":",",\"","{\"","\"");
$str = str_replace($search, $replace, $str);
$obj = json_decode($str);
return $obj;
}
$obj = convert("{name: 'sample', type: 'text'}");
echo $obj->name;
i guess you should do some about the whitespaces... i just replaced it with it... but better you use something like trim or instead use regexp to replace. so there can be no errors with whitespaces