json string is not converting into object - javascript

Here is the server side code I am trying to send json
$x = array();
$timestamp = strtotime('22-09-2008');
$x["x"] = $timestamp;
$x["y"] = 22;
$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo json_encode($val);
So output for above code looks like
"[{ \"name\": \"weight\", \"dataPoints\": [{\"x\":1222041600,\"y\":22}] }]"
Below is the client side code I get the data via Jquery getJSON
var jqxhr = $.getJSON( "https://domain/gettracker.php?id="+id, function(data) {
console.log(data);
})
I suppose getJson converts json to object automatically , but it logs the raw json like below
"[ { name: "weight", dataPoints: [{"x":1222041600,"y":22}] } ]"
I tried to do json parse , but i get error.
I guess I am not sending the data properly via php.Can some one guide me ?

Your JSON string is not valid - the property names should be enclosed in double quotes - ", and you don't need to encode the string again.
$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo $val;
Or better yet, use json_encode to create the string for you:
$data = array(
'name' => 'weight',
'dataPoints' => $x
);
echo json_encode($data);

Related

Ajax read PHP generated json

So I want to send a json to an ajax call but I don't know how to read the json when is sent. And also my json looks strange because of the backslashes...
This is my ajax:
function find(){
var type = $('#object_type').val();
$.ajax({
type : 'POST',
url : 'get_user.php',
data : {
'type' : type
},
dataType : 'json',
error : function(response){
alert('SOMETHING WENT WRONG');
},
success : function(response){
This is what I get as a response:
"[{\"name\":\"Test\",\"link\":\"test.php\"},{\"name\":\"Test2\",\"link\":\"test2
.php\"}]"
}
});
}
This is my PHP function:
$type = $_POST['type'];
$user_array;
$user = mysqli_query($conn, "SELECT name,link FROM user WHERE `type` LIKE '%".$type."%'") or die();
while ($row = mysqli_fetch_array($user, MYSQLI_ASSOC)) {
$row_array['name'] = $row['name'];
$row_array['link'] = $row['link'];
array_push($user_array, $row_array);
}
mysqli_close($conn);
$result = json_encode($user_array, 128);
echo json_encode($result);
First change that you should make :
You don't need to encode two times
$result = json_encode($user_array, 128);
echo json_encode($result);
should be
$result = json_encode($user_array, 128);
echo $result;
Now the response should look like
[{"name":"Test","link":"test.php"},{"name":"Test2","link":"test2
.php"}]
which is a valid Javascript Array and can be accessed using following code :
var len = response.length;
for(i=0;i<len;i++){
console.log(response[i].name);
console.log(response[i].link);
}
As provided in techierishi's answer. Do not encode your response twice. Just do
echo $result;
The JSON should be valid and parsed, why?
json_encode is used on a valid PHP array returned from a MySQLi query.
dataType is used, explicitly forcing jQuery to JSON.parse the response and no errors where raised during that process.
The JSON that is returned has the following structure
ROOT
ARRAY
ARRAY OBJECT
OBJECT PROPERTY
To address something like that:
root[array index].property
Will give you the array's value, which is an object. That object has multiple properties.
[] means array
{} means object
So [{name:"value 1"},{name:"value 2"}] is actually
ARRAY
[0].name = value 1
[1].name = value 2
So retrieving information like name from your JSON will be:
response[0].name; // = test

php decode json array

I have a php page that receives a json object from javascript page, but i was not able to decode the json in php. How to decode the json and store in php such that $arr[0]=[1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; in php ?
after removing "myString = JSON.stringify(myObject);"
echo $value; outputs "Array"
echo $value[0]; outputs nothing
echo $value->{"key"}; outputs nothing either
how can i actually get the array contents?
javascript:
var mon=[1,2,34,5,2];
var tue=[2,1,34,5,2];
var wed=[8,1,34,5,2];
var myObject = {'key' :'value','key2':'value','key3':'value'};
myObject.key = mon;
myObject.key2 = tue;
myObject.key3 = wed;
myString = JSON.stringify(myObject); //this line removed
var jsonString = JSON.stringify(myObject);
$.ajax({
type: "POST",
url: "n3.php",
data: {data : jsonString},
cache: false,
success: function(aaa){
alert("OK");
$("#pageContent").html(aaa);
}
});
php:
<?php
$value = json_decode($_POST['data']);
echo $value; //this echos the whole json object
echo $value->{"key"}; //this outputs nothing
?>
You are JSON encoding your data twice on the Javascript side. When you call json_encode in PHP once, you get a JSON encoded object back. That's why echo $value outputs the whole string. If it was a PHP array at this point it would output "Array" or an error in case it was an object, it would not output the whole content.
Either json_decode it again, or don't double encode it in Javascript.

Change JSON_Encode output format (Brackets and Commas)

I have an array that is created in PHP, and then encoded into my javascript via JSON.
The Array is defined here:
$stmt -> bind_result($match_id, $hero, $mmr);
while($stmt -> fetch()){
$grapharray[] = array($hero => $mmr);
}
and JSON encoded here:
$grapharray_labelled = array(
"label" => "MMR Over time",
"data" => $grapharray
);
and here:
var graphdata = <?php echo JSON_encode($grapharray_labelled); ?>;
The output when I run my webpage is that graphdata =:
{
"label":"MMR Over time",
"data":[
{"Rubick":6524},
{"Lion":6550},
{"Magnus":6565},
{"Keeper of the Light":6566}
]
}
However I would like it to be like this:
{
"label":"MMR Over time",
"data":[
["Rubick", 6524],
["Lion", 6550],
["Magnus", 6565],
["Keeper of the Light", 6566]
]
}
Reason:
I would like to change the format because I am trying to get flot to work, and flot accepts an array of arrays as the datatype.
Otherwise: Is there a better way to transfer an array from PHP to JavaScript with my desired format?
Change this:
$grapharray[] = array($hero => $mmr);
TO:
$grapharray[] = array($hero, $mmr);

How to use JSON to retrieve dbpedia json data

In my php code, I am retrieving json data as below.
<?php
$url = "http://dbpedia.org/data/Los_Angeles.json";
$data = file_get_contents($url);
echo $data;
?>
The javascript code consumes this json data returned from php and gets the json object as below.
var doc = eval('(' + request.responseText + ')');
How to retrieve the following json data using dot notations where the keys contain URLs.
My guess is to use encoding. Please guide along these lines
"http://dbpedia.org/ontology/populationTotal" : [
{ "type" : "literal",
"value" : 3792621 ,
"datatype" : "http://www.w3.org/2001/XMLSchema#integer" } ] ,
"http://dbpedia.org/ontology/PopulatedPlace/areaTotal" : [
{ "type" : "literal",
"value" : "1301.9688931491348" ,
"datatype" : "http://dbpedia.org/datatype/squareKilometre" }

split ajax json response errors in each field

i used till now AJAX post with normal dataType 'html' , now i convert it and using dataType 'json' ,
Now before i used json i split response errors with for each span next to the input field .
this is my old ajax succses split errors code using normal datatype 'html' :
success:
function(data){
var data_array = split('*');
for(var i=0; i<data_array.length-1; i++)
{
messgae_array = data_array[i].split(':');
$("#"+messgae_array[0]+"_error").html(messgae_array[1]);
$("#"+messgae_array[0]).css({"border":"1px solid red"});
}
}
this is my input on the form
<input type="text" id="uname" name="uname" value="" class="inplaceError" />
<span id="uname_error"></span>
i have more inputs i puted just ex how it look..
so every input i have span that holds the errors from the ajax response.
and now the problem is my old code know handle html response and not json response , i am javascript/ajax/json newbie , and i dont know how to change the split code so work with json response and not normal html response , any help please?
Edit:
i fire the errors like this :
if(isset($_POST['p']) && !empty($_POST['p']))
{
if($password == $retype)
{
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
// Create salted password (Careful with the chilli)
$password = hash('sha512', $password.$random_salt);
}
else
{
$message['password']=' password not match';
}
and so on .
$message['email']=' wrong email';
and my foreach json array for the errors :
foreach($message as $key => $val) {
$return = array('error' => $key, 'message' => $val );
echo json_encode($return);
}
so somthing is wrong here with the foreach for the errors its fire wrong as the ajax response code any idea?
You should not have to split strings in your data. If it is in the correct JSON format, you can access it easily using object notation (also possible via array notation):
var json = '{
"someVar":true,
"error":"my fatal error message"
}';
var obj = JSON.parse(json);
alert(obj.error);
This is why JSON was created, for ease of access and use. If you're still going to edit and split strings manually to read data from your JSON, you're doing it wrong.
EDIT:
Use nested json, if you need to identify and organise your messages.
var json = "errors": [{
"id": "001",
"field": "textfield1",
"message": "message1."
},
{
"id": "002",
"field": "textfield2",
"message": "message2."
}];
var obj = JSON.parse(json);
You can now apply styles to these fields, and display the messages:
foreach(obj.errors as err) {
$("#"+err.field).html(err.message);
$("#"+err.field).css({"border":"1px solid red"});
}
success:function(data)
{
// consider your data is like this JSON string
// var data= [{"error":"uname","message":" wrong pass."},{"error":"email","message":" wrong name"}];
// instead of this
// var data_array = split('*');
// use this
//change your json parser to this
var data_array = JSON.parse(data);
for (var i in data_array )
{
$("#"+data_array[i].error+"_error").html(data_array[i].message);
$("#"+data_array[i].error).css({"border":"1px solid red"});
}
}

Categories

Resources