Reputation: 715
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: '[email protected]' },
{ username: 'rose', password: 3333, email: '[email protected]' },
{ username: 'adam', password: 95112, email: '[email protected]' },
{ username: 'lisa', password: 'sarlak', email: '[email protected]' },
]
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.
Upvotes: 0
Views: 64
Reputation: 683
Something like this (others already wrote it..):
$json = '[{"username":"david","password":33456,"email":"[email protected]"},{"username":"rose","password":3333,"email":"[email protected]"},{"username":"adam","password":95112,"email":"[email protected]"},{"username":"lisa","password":"sarlak","email":"[email protected]"}]';
$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
Upvotes: 1
Reputation: 2059
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);
Upvotes: 1
Reputation:
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
Upvotes: 1