php - json_decode() returns null instead an array ← (PHP, MySQL, HTML)
I am going to INSERT an array of objects into mysql via AJAX but on server side json_decode()
returns null
How can i solve this?
This is the ajax codes:
let mainObj = [
{ username: 'david', password: 33456, email: 'david@gmail.com' },
{ username: 'rose', password: 3333, email: 'rose@gmail.com' },
{ username: 'adam', password: 95112, email: 'adam@gmail.com' },
{ username: 'lisa', password: 'sarlak', email: 'lisa@gmail.com' },
]
let sendMe = JSON.stringify(mainObj);
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('result').innerHTML = xhr.responseText;
}
}
xhr.open("GET", "check.php?x=" + sendMe, true);
xhr.send();
And the php codes (check.php):
$obj= json_decode($_GET['x'], true);
$b= $obj[1]->username;
var_dump($b);
It returns null
but i need it returns an array of objects which be usable in database.
Answer
Solution:
Something like this (others already wrote it..):
$json = '[{"username":"david","password":33456,"email":"david@gmail.com"},{"username":"rose","password":3333,"email":"rose@gmail.com"},{"username":"adam","password":95112,"email":"adam@gmail.com"},{"username":"lisa","password":"sarlak","email":"lisa@gmail.com"}]';
$decodedJson = json_decode($json, true);
// $b= $decodedJson[1]->username; // Wrong, you have an array, not object
// Correct
foreach($decodedJson as $single) {
print_r($single["username"]."\n");
}
// Prints out:
david rose adam lisa
Answer
Solution:
Since you're using the second parameter true
in $obj= json_decode($_GET['x'], true);
your returned $obj
will be an array. You either use:
$obj = json_decode($_GET['x']);
$b = $obj[1]->username;
or
$obj = json_decode($_GET['x'], true);
$b = $obj[1]['username'];
to get "rose".
https://www.php.net/manual/en/function.json-decode.php
Answer
Solution:
You are trying to treat an array as an object, json_decode
returns an array not an object or stdclass... instead of
$b= $obj[1]->username;
should be
$b= $obj[1]['username'];
I'm assuming that you are not using any framework since the thing that you did should throw and exception so it's better to enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);