json_decode() not working - php

I am using ajax to send data with JSON and it keeps returning null. Here is the string I'm sending:
{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}
It is sent via post. Here is the code I send it with:
function slash(strr){
var re = /([^a-zA-Z0-9])/g;
var str = strr;
var subst = '\$1';
var st = encodeURIComponent(str.replace(re,subst));
console.log("st");
return st;
}
function create() {
var info = {};
var code=editor.getValue();
info.username=username;
info.code=slash(code);
var name=document.getElementById('projectName').value;
name2=name;
info.name=slash(name2);
info=JSON.stringify(info);
console.log(info);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "create_project.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("info="+info);
}
When it gets received in the php file it is processed like this:
$info = $_POST['info'];
echo "<pre>".$info."</pre>";
//$info = urldecode($info);
$info = json_decode($info);
echo "<pre>".$info."</pre>";
However for some reason the json_decode() doest work. Again here is the JSON I'm sending:
{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}
the first echo works correctly but the second one doesn't. How do I fix this?

json_decode() must be emitting an error which you are not checking. Functions like json_decode() and json_encode() do not display errors, you must use json_last_error and since PHP 5.5 there is also json_last_error_msg().
<?php
$str = '{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B\'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}';
var_dump($str);
var_dump(json_decode($str));
var_dump(json_last_error());
var_dump(json_last_error_msg());
The above outputs:
string(189) "{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B\'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}"
class stdClass#1 (3) {
public $username =>
string(8) "HittmanA"
public $code =>
string(136) "%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B\'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F"
public $name =>
string(10) "Untitled-1"
}
int(0)
string(8) "No error"
If we try to decode invalid JSON:
<?php
$str = 'foobar{';
var_dump($str);
var_dump(json_decode($str));
var_dump(json_last_error());
var_dump(json_last_error_msg());
The above prints:
string(7) "foobar{"
NULL
int(4)
string(16) "boolean expected"
There must be an error in the JSON when you try to decode it. Check for errors usings the json_* error message functions. The error message will tell you what's wrong and it will be straight to fix once you know what the error is.

hello mister if you echo in php is equal to return or print in some functional programming.
if your using ajax, ajax is one way communication.
$info = $_POST['info'];
//this code will be return
echo "<pre>".$info."</pre>";
//this also will not be triggered cause you already return the above code
//$info = urldecode($info);
$info = json_decode($info);
echo "<pre>".$info."</pre>";

Perhaps setting the xhttp content-type as json like
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data); ?>
As stated in this answer.

Looking at the object it looks like you have a ' inside your code parameter. I think that's invalid for encoding.

Using json_decode like this:
$info = json_decode($info);
Will return a PHP variable.
If you add the associative parameter as true (false by default) like this:
$info = json_decode($info, true);
Then it will return an associative array
http://php.net/manual/en/function.json-decode.php

I was struggling with this on my Windows 10 machine, PHP version 5.5.9 only to find that the php_json.dll file was not in the ext folder of my installation and obviously no extension to uncomment in php.ini file. I found the dll at http://originaldll.com/file/php_json.dll/31989.html. After copying it to my ext folder I added extension=php_json.dll to my php.ini file and restarted my apache server and it started working fine.

Related

Saving data across multiple lines JSON

Currently I have PHP and JS save my data in a JSON.
Below is the code for it:
PHP:
<?php
$jsonString = file_get_contents('passwords.json');
$data = json_decode($jsonString, true);
// get the q parameter from URL
$q = $_REQUEST["q"];
$item = $_REQUEST["item"];
// or if you want to change all entries with activity_code "1"
foreach ($data["passwords"] as $key => $password) {
echo $data["passwords"][$key]['timesToUse'] - 1;
if ($password['password'] == $q) {
$data["passwords"][$key]['timesToUse'] = $data["passwords"][$key]['timesToUse'] - 1;
$data["passwords"][$key]['winningItem'] = $item;
}
}
$newJsonString = json_encode($data);
file_put_contents('passwords.json', $newJsonString);
?>
JS:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "passwords.php?q="+passwords[i].password+"&item="+winningItem.getFullName(), true);
xmlhttp.send();
The issue that I am having is that initially my JSON file looks like this:
{"password":"IS360H","timesToUse":1,"winningItem":""},
{"password":"AGRD33","timesToUse":1,"winningItem":""},
{"password":"4BX0FV","timesToUse":1,"winningItem":""},
{"password":"99NOTX","timesToUse":1,"winningItem":""},
{"password":"X2Z8BO","timesToUse":1,"winningItem":""},
{"password":"R9G4Q0","timesToUse":1,"winningItem":""},
{"password":"CG9RGT","timesToUse":1,"winningItem":""},
As you can see it is nice and neat and is sitting at 1 password per line. However once the file gets modified, it turns to this:
{"password":"IS360H","timesToUse":0,"winningItem":"counterUAV"},{"password":"AGRD33","timesToUse":0,"winningItem":"sentryGun"},"password":"4BX0FV","timesToUse":0,"winningItem":"chopperGunner"},"password":"99NOTX","timesToUse":1,"winningItem":""},{"password":"X2Z8BO","timesToUse":1,"winningItem":""}, {"password":"R9G4Q0","timesToUse":1,"winningItem":""},"password":"CG9RGT","timesToUse":1,"winningItem":""},
What do I need to do to make my JSON file preserve the line breaks?
Thank you!
There is option JSON_PRETTY_PRINT available in json_encode function, if you are using same for encoding json. Try following:
$json_string = json_encode($data, JSON_PRETTY_PRINT);
Read more about json_encode

passing json object with ajax to php

I have set up a basic api and I know its working because requests that come with postman pass normally ,what I am having trouble with is passing the JSON object through AJAX to the php file.
The AJAX part
function add_book(){
if(validate()){
var jsonData = {};
jsonData.Price = document.getElementsByName("Price")[0].value;
jsonData.Title = document.getElementsByName("Title")[0].value;
jsonData.Author = document.getElementsByName("Author")[0].value;
jsonData.Genre = document.getElementsByName("select_dropdown")[0].value;
alert(JSON.stringify(jsonData));
var request = new XMLHttpRequest();
var url = "/books.php";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
}
}
request.send(jsonData);
}
}
For example this is the alert I get from stringifying the object
{"Price":"23","Title":"asdas","Author":"dasda","Genre":"Science fiction"}I can basically copy/paste this string to postman and it works as intended.
Now to the php part
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
if(!empty($json_obj->Price) && !empty($json_obj->Genre) && !empty($json_obj->Author) && !empty($json_obj->Title)){
The if always returns false ,while it should not ,again postman requests pass for true.
========================================================================
EDIT :
I managed to find the source of the problem . I made a function to check if the json is valid , turns out its not , there is no problem in the php part as it turns out . Here is the function in case someone needs it / wonders :
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
=========================================================================Edit 2:
The problem was on the request.send(jsonData); part . Fixed it with request.send(JSON.stringify(jsonData));
Thanks for your time !
This is the problem
$json str = file_get_contents('php://input');
The post parameters should be accessed by $_POST.
Instead try this
$json_str = $_REQUEST['jsonData']`;
and also do a var_dump for $json_str
Does this help?
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
if(!empty($json_obj['Price']) && !empty($json_obj['Genre']) && !empty($json_obj['Author']) && !empty($json_obj['Title'])){
I think the problem is the file_get_contents(). Maybe you try to echo it.
And for the if you could write:
if (!(empty($json_obj->Price) && empty($json_obj->Genre) && empty($json_obj->Author) && empty($json_obj->Title)))

How do I access a JSON-property of a JSON-Object in php?

I've got a really weird problem and I can't figure out why.
The situation is quite simple. My Android app uploads JSON data to a php script on my server. Right now I am trying to parse the data.
This is the JSON-Array passed to the script (via httpPost.setEntity ()):
[{"friends_with_accepted":"false","friends_with_synced":"false","friends_with_second_id":"5","friends_with_first_id":"6"}]
This is the php script:
<?php
// array for JSON response
$response = array();
$json = file_get_contents ('php://input');
$jsonArray = json_decode ($json, true);
foreach ($jsonArray as $jsonObject) {
$firstId = $jsonObject['friends_with_first_id'];
$accepted = $jsonObject ['friends_with_accepted'];
$secondId = $jsonObject ['friends_with_second_id'];
$synced = $jsonObject ['friends_with_synced'];
echo "accepted: ".$accepted."synced: ".$synced;
} ?>
And this is the response I get from the script:
accepted: synced: false
Why is the "synced" property correctly passed, but not the "accepted" property??
I can't see the difference. Btw, firstId and secondId are parsed correctly as well.
Okay, i just found the problem:
Instead of
$accepted = $jsonObject ['friends_with_accepted'];
I deleted the space between jsonObject and the bracket
$accepted = $jsonObject['friends_with_accepted'];

passing a javascript variable to PHP with xmlhttprequest

Im having problem Posting a javascript variable to a php file. Please would someone tell me what's going on?
// Get Cookies
var getCookies = document.cookie;
cookiearray = getCookies.split(';');
SelectedIds = cookiearray[0];
//take key value pair
name = cookiearray[0].split('=')[0];
value = cookiearray[0].split('=')[1]; // The variable(values) i want to pass
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
hr.open("POST", url, true);
var url = "page.php";
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("Comp").innerHTML = return_data;
}
}
hr.send(value); // Request - Send this variable to PHP
document.getElementById("Comp").innerHTML = "loading...";
PHP
$test = $_POST['value'];
print_r($test); // NULL
Thanks
Instead of
print_r($test);
use the echo
echo $test;
As $test is not an array is a string value. print_r is used to print the array. that's why is given the null value.
And your send function in ajax should be like this:
hr.send("value="+value);
In the send function, the parameter that passed must be a string like this:
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
More tutorial is here.
I've been trying work out, for sometime, how to pass quite a long string I have formatted in javascript into php to save in a file and I think I now have the answer. At least it works for me.
The variable 'str' is passed into 'getGame' from another function after it has been formatted. I am using the 'POST' method as the string can get quite long.
The code is:-
function getGame(str){
//Sends data to the php process "save Game".
var test = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send("data="+ test);
}
This sends the "data" to "saveGame.php where it is saved to a file as in the following code and returns a messsage in the alert dropdown.
<?php
$outputString = $_POST["data"];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
if (!$fp){
$message = "Error writing to file. Try again later!" ;
}else{
fwrite($fp, $outputString);
$message = "File saved!";
}
fclose($fp);
echo $message;
?>
This works for me and I hope it is useful to other newbies.

JSON output for mapping data using json_decode() in php

I am attempting to write PHP code to interact with JSON output from Mapquest's Open API / Open Street Map service. I have listed it below. I have been using this code in my Drupal 6 implementation. This code returns no output. When I use it, json_last_error() outputs 0.
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode(var_export($json));
$foo .= $obj->{'fuelUsed'};
$output .= foo;
return $output;
}
You can view the raw JSON output by following the URL. In this function I am expecting to get 1.257899 as my output. I have two questions:
(1) What can I call so I get items out of my array. For instance, how can I get the value represented in JSON "distance":26.923 out of the array?
(2) Is it possible am I running into a recursion limit issue that I've read about in the PHP Manual?
If you read the manual page for json_decode carefully, you'll notice there is a parameter (false by default) that you can pass to have it return an array rather than an object.
$obj = json_decode($json, true);
So:
<?php
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json, true);
//var_dump($obj);
echo $obj['route']['fuelUsed'];
}
json_test_page();
Remove the var_export function from json_decode.
You're trying to convert information about a string to json.
I was able to get the fuelUsed property this way
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json);
return $obj->route->fuelUsed;
}

Categories