How to include a php variable in json and pass to ajax - php

My Code
var json = xmlhttp.responseText; //ajax response from my php file
obj = JSON.parse(json);
alert(obj.result);
And in my php code
$result = 'Hello';
echo '{
"result":"$result",
"count":3
}';
The problem is: when I alert obj.result, it shows "$result", instead of showing Hello.
How can I solve this?

The basic problem with your example is that $result is wrapped in single-quotes. So the first solution is to unwrap it, eg:
$result = 'Hello';
echo '{
"result":"'.$result.'",
"count":3
}';
But this is still not "good enough", as it is always possible that $result could contain a " character itself, resulting in, for example, {"result":""","count":3}, which is still invalid json. The solution is to escape the $result before it is inserted into the json.
This is actually very straightforward, using the json_encode() function:
$result = 'Hello';
echo '{
"result":'.json_encode($result).',
"count":3
}';
or, even better, we can have PHP do the entirety of the json encoding itself, by passing in a whole array instead of just $result:
$result = 'Hello';
echo json_encode(array(
'result' => $result,
'count' => 3
));

You should use json_encode to encode the data properly:
$data = array(
"result" => $result,
"count" => 3
);
echo json_encode($data);

You're using single quotes in your echo, therefore no string interpolation is happening
use json_encode()
$arr = array(
"result" => $result,
"count" => 3
);
echo json_encode($arr);
As a bonus, json_encode will properly encode your response!

Try:
$result = 'Hello';
echo '{
"result":"'.$result.'",
"count":3
}';

$result = 'Hello';
$json_array=array(
"result"=>$result,
"count"=>3
)
echo json_encode($json_array);
That's all.

Related

how to prnt json data printed from get_file_contents php function

I printed this json from a get_file_contents output.
{"status":"INVALID_CREDENTIALS"}
Now I want to echo the content of "status" and I used
echo $status
but not working. Please help.
First, use json_decode to convert to php object:
$json = '{"status":"INVALID_CREDENTIALS"}';
$obj = json_decode($json);
Then:
echo $obj->status;

Read JSON Data Have Token With PHP

How can I read a JSON data response using php?
This is Code :
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
and give me this json data :
{
"original": "This sentnce has some probblems.",
"suggestion": "This sentence has some problems.",
and ...
}
I want to return "suggestion" in a url with $
this is an example :
$user_id = '123456789'
$mytext = '?' // I WANT RETURN "suggestion" HERE !
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
You can use json_decode().
See:
http://php.net/manual/en/function.json-decode.php
You just need to do:
$response = json_decode($response,1);
echo $response['suggestion'];
Setting the second parameter of json_decode() to 1 (true) will return an associative array of the JSON data.
If you want to include it in a URL using your code example:
$user_id = '123456789'
$json = json_decode($response,1);
$mytext = $json['suggestion'];
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
Use json_decode to convert json_response to array.Add second parameter of 'true' to make it an array that you should be familiar with.
Access suggestion variable by specifying it.
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
$data=json_decode($response,true);
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$data['suggestion'];
echo $url;

How to receive JSON data from PHP or JSP to Extjs

I've a JSON string, I want to get it in store of Extjs by a PHP url. How to get this string as a JSON from a php file. Something like this:
Extjs file:
PHP file:
The result is blank.
What I do now for this work?
An example of what I believe you mean to do:
$array = array();
$test = '{ "firstName":"John" , "lastName":"Doe" }';
$array[] = json_decode($test);
$test = '{ "firstName":"Jane" , "lastName":"Doe" }';
$array[] = json_decode($test);
$test = '{ "firstName":"Random" , "lastName":"Guy" }';
$array[] = json_decode($test);
print json_encode($array);
exit;
Will give you:
[{"firstName":"John","lastName":"Doe"},{"firstName":"Jane","lastName":"Doe"},{"firstName":"Random","lastName":"Guy"}]
As for the Ajax, maybe this will help - How to get "data" from JQuery Ajax requests, or maybe try the Jquery Ajax documentation.

how to remove back slashes from json output in php

The code I have used:
$val = json_encode(array("test"=>test1,"test2" =>test,"description" => description));
return $val;
The result im getting
{\"test\":\"test1\",\"test2\":\"test\",\"description\":\"description\"}
I need this to fix api
Try with stripslashes()
echo stripslashes('{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}');
stripslashes()
Tried this.
$val = json_encode(array(
"test"=>'test1',
"test2" =>'test',
"description" => 'description'
));
$data = json_decode($val, true, JSON_UNESCAPED_SLASHES);
return $data;
This is the result I received.
In php "stripslashes" function is present using that you can remove backslash.
Link for more details.
Example:
echo $strnew = stripslashes('{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}');
Use stripslashes() And read stripslashes
<?php
$srt="'{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}'
";
echo stripslashes($srt);
OUTPUT
'{"test":{"test1":{"test1":[{"test2":"1","test3":
"foo","test4":"bar","test5":"test7"}]}}}'
you can use JSON_UNESCAPED_SLASHES
json_encode($yourjson, JSON_UNESCAPED_SLASHES);
Use string find and replace function
$str="{"test":{"test1":{"test1":[{"test2":"1","test3": "foo","test4":"bar","test5":"test7"}]}}}";
str_replace("\'","'",$str);
Try the following code. It works perfectly fine for me $cha a string with backslashes
$cha = "{\"ashen\":\"143\"}";
$chachi = json_decode($cha,JSON_UNESCAPED_SLASHES);
return $chachi['ashen'];
output: 143
Actually, only Khachornchit Songsaen answer is correct.
stripslashes does not work on unescaping escaped " in json encoded strings inside another json.
es.
{ "key1" :"value1", "key2": "{\"key\":\"Text \\\"text\\\" text\"}" }
using json_decode($var, true, JSON_UNESCAPED_SLASHES) does the job correctly.
this is the right method when your result is coming in slashes do this
$data = [
"message" => '',
"data" => $product
];
$response[] = $data;
return $response;
do this it's really work because after 5 day i fund this solution or it is right .
I was facing same issue, it is resolved by using echo and exit;
$response = json_encode(array("test"=>"test1","test2"
=>"test","description" => "description"));
echo $response;
exit;

Return JSON inside data[] php

I'm using the following to pull some data fro facebook:
$tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token);
echo $tagData;
This produces e.g.:
{"data":
[
{"name":"Jonathan Montiel","id":"28125695"},
{"name":"Jackson C. Gomes","id":"51300292"}
],
"paging":{"next":"https:\/\/graph.facebook.com\/123456789\/friends?access_token=5148835fe&limit=5000&offset=5000&__after_id=100060104"}}
QUESTION How I can just return ONLY what's inside the [...] including the [ ]?
Desired result:
[
{"name":"Jonathan James","id":"28125695"},
{"name":"Jackson C. Cliveden","id":"51300292"}
]
Try this:
$tagData = json_decode( $tagData, true );
$data = $tagData['data'];
echo json_encode( $data );
This basically converts the JSON to an array, extracts the desired part and returns this again as JSON-encoded.
EDIT
Example Fiddle
json_decode and reencode with json_encode necessary part of the response. Following is going to work for you:
$tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token);
$tagData = json_decode($tagData);
echo json_encode($tagData->data);
Thanks to Sirco for the inspiration, this works although how its different to answer given I have no clue!
$tagData = json_decode(file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token), true );
$data = $tagData['data'];
echo json_encode( $data );

Categories