PHP Cannot access property value of an object using json_decode - javascript

So I have 2 php files, let's call it UploadImages.php and Caller.php
so in the UploadImages.php I have a function like so
<?php
function UploadImages(){
$result = [
"UploadOk" => 0,
"UploadMsg" => "Upload successful" ];
echo(json_encode($result));
}
?>
and this is how I handle it in the Caller.php
<?php
include "UploadImages.php";
$uploadResult = json_decode(UploadImages(), true);
if($uploadResult["UploadOk"] == 1) {
// do something else
}
else {
echo $uploadResult["UploadMsg"];
}
?>
using ajax from javascript, I have this result:
"{"UploadOk":1,"UploadMsg":"Upload successful"}"
what i expected is only UploadMsg property instead it returns an object, note that I actually need to process the UploadOk in the Caller.php instead of just dumping a whole object to javascript, so the JSON.parse method in javascript would not be the correct way to handle this situation.

echo inside UploadImages returns the object, As PHP echo send response headers, thus calling via ajax you get the response from this method.
Change the method with following and then try:
function UploadImages(){
$result = [
"UploadOk" => 0,
"UploadMsg" => "Upload successful" ];
return json_encode($result);
}
Note: Also you don't need to use json_encode inside UploadImages just return the the array as follow:
function UploadImages(){
$result = [
"UploadOk" => 0,
"UploadMsg" => "Upload successful" ];
return $result;
}
and in Caller.php
<?php
include "UploadImages.php";
$uploadResult = UploadImages();
if($uploadResult["UploadOk"] == 1) {
// do something else
}
else {
echo $uploadResult["UploadMsg"];
}
?>

Related

json_encode() Data Being Automatically Converted Into A Javascript Object Without JSON.parse() Being Used

I have some PHP and JavaScript that works by PHP updating a MySQL database, and then outputting the updated code back onto the page without a hard refresh using the JavaScript fetch() method. This code works, but there is a part I don't understand — why is it when the json_encode() PHP method is used, which converts the data to a JSON string, when it is then used in the JavaScript it is automatically being converted into a JavaScript object without JSON.parse() being used?
In the Javascript when I use JSON.parse() it understandly throws an error, because the data isn't a string (which initially caused some confusion), when I console log the json variable being used in the JavaScript it does indeed return a JavaScript object where I can access its properties and methods etc.
There is no other JSON or json_encode() being used on the page (or indeed the site).
Also in the PHP script it echoes the JSON with echo json_encode($board_row); when the data is fetched from the database, before any HTML content is outputted. When I try and echo this in the HTML to see the value of json_encode($board_row); it just outputs the word false. I don't understand what is going on there either?
If I manually add a simply array into the HTML such as $arr = array('a' => 1, 'b' => "hello", 'c' => null); and then echo that in the HTML with echo json_encode($arr); as excepted it outputs a JSON string.
If someone could kindly explain why this is happening, that would be wonderful.
PHP
if (isset($_POST['submit-board-name'])) {
$create_board_name = $_POST['create-board-name'];
try {
// insert into database
$createBoardSQL = "
INSERT INTO boards (board_name, user_id)
VALUES (:board_name, :user_id )
";
$bstmt = $connection->prepare($createBoardSQL);
$bstmt->execute([
':board_name' => $create_board_name,
':user_id' => $db_id
]);
// ----- fetch as JSON
if(isset($_POST['json_response'])) {
$board_stmt = $connection->prepare("
SELECT * FROM `boards` WHERE `user_id` = :user_id
AND `board_name` = :board_name
ORDER BY `board_id` DESC");
$board_stmt -> execute([
':user_id' => $db_id,
':board_name' => $create_board_name
]);
$board_row = $board_stmt->fetch();
header('Content-type: application/json');
echo json_encode($board_row);
exit;
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
JavaScript
let boardModuleForm = document.querySelector('.board-module-form');
// URL details
let myURL = new URL(window.location.href),
pagePath = myURL.pathname;
if (boardModuleForm) {
boardModuleForm.addEventListener('submit', function (e) {
if (e.submitter && e.submitter.classList.contains('js-fetch-button')) {
e.preventDefault();
var formData = new FormData(this);
formData.set(e.submitter.name, e.submitter.value);
formData.set('json_response', 'yes');
fetch (pagePath, {
method: 'post',
body: formData
})
.then(function(response) {
if (response.status === 200) {
response.json().then(function(json){
const newBoardName = json.board_name,
boardId = json.board_id;
const newButton = `
<button name="board-name" type="submit">
<span>${newBoardName}</span>
<span style="margin:0" class="add-icon flex">+</span>
</button>
<input class="board-id-value" type="hidden" value="${boardId}">
`
// add new button from above onto page
document.querySelector('.board-list').insertAdjacentHTML('afterbegin', newButton);
});
}
})
.catch(function(error) {
console.error(error);
})
}
})
}
In the handler for your fetch response, you call response.json().then(...). This is already doing the JSON parsing for you without needing to call JSON.parse manually.

jQuery Ajax PHP Array Blank Response No Errors

I have the weird Problem that I get no response from my Ajax Call. I get the data but when im trying to return it I only get an blank screen. There are 3 Files in my project which are needed because my project has so many DB calls and functions so its easier to read.
So this one of many functions which calls my ajaxCall function
$.when(ajaxCall("getOutlets", '', null)).done(function(res) {
if(res) {
console.log(res);
this is my global ajaxCall Function for the whole project:
function ajaxCall(functionName, params, answers) {
return jQuery.ajax({
type: "POST",
url: '/ajax/ajax.php',
dataType: 'json',
data: {
functionIdentifier: functionName,
functionParams: params,
},
my Ajax.php file then calls based on the functionName Param the function in my database.php file. Ajax.php:
$response = array();
switch ($functionIdentifier) {
case 'getOutlets':
$response = $database->getSearchOutletsFromDatabase($functionParams);
break;
.... many switch cases
}
echo json_encode($response);
die();
?>
and finally in my database.php It calls the mysqli functions which looks like this:
public function getSearchOutletsFromDatabase() {
$result = mysqli_query($this->conn, "CALL `sp_outlets_get`()") or die(mysqli_error($this->conn));
while($row = $result->fetch_assoc()) {
$response[] = $row;
}
#mysqli_next_result($this->conn);
return $response;
}
and here is the weird part. If im returning only one Object from $result like return $result->fetch_object() I return the first Object successfull. BUT when I just save the row in an array and want to return my array the whole response is empty. No errors. Nothing.
If you need more information just say it Ill try to add more.
Edit:
If Im putting this on top of my ajax.php file where the response gets returned I get following error on Developers Network Tab:
header('Content-Type: application/json');
$response = array();
switch ($functionIdentifier) {
case 'getOutlets':
$response = $database->getSearchOutletsFromDatabase($functionParams);
break;
.... many switch cases
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data
I found what caused the error (and sometimes it is one of the easiest things). Well it was ö,ä,ü etc in my response.
Adding a utf8_encode before I return my data to ajax solved the problem.
public function getSearchOutletsFromDatabase() {
$result = mysqli_query($this->conn, "CALL `sp_data_get`()") or die(mysqli_error($this->conn));
$response = array();
while($row = $result->fetch_assoc()) {
$res['ID'] = $row['ID'];
$res['Name'] = utf8_encode($row['Name']);
array_push($response, $res);
}
#mysqli_next_result($this->conn);
return $response;
}

PHP + JS + AJAX: Unexpected token { in JSON

On trying to return some data from a GET request via AJAX, I'm continuously greeted with this nasty error message ...Unexpected token { in JSON... and I can clearly see where it's coming from. Note that this only happens if I have more than one(1) item being returned from the database. If I only have one(1) item I am able to access it data.id, data.user_name, so on and so forth.
{
"id":"39",
"user_id":"19",
"user_name":"Brandon",
"content":"Second Post",
"date_created":"2018-01-24 21:41:15"
}/* NEEDS TO BE A ',' RIGHT HERE */ {
"id":"37",
"user_id":"19",
"user_name":"Brandon",
"content":"First",
"date_created":"2018-01-24 15:19:28"
}
But I can't figure out how to fix it. Working with data, arrays, and objects is an artform I have yet to master.
JAVASCRIPT (AJAX)
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost/mouthblog/test.php');
xhr.onload = () => {
if (xhr.status == 200) {
const data = xhr.responseText;
const jsonPrs = JSON.parse(data);
console.log(jsonPrs);
} else {
console.log('ERROR');
}
};
xhr.send();
PHP (this is where the data is coming from)
<?php
class BlogRoll extends Connection {
public function __construct() {
$this->connect();
$sql = "SELECT `id`, `user_id`, `user_name`, `content`, `date_created`
FROM `posts`
ORDER BY `date_created` DESC";
$query = $this->connect()->prepare($sql);
$result = $query->execute();
if ($result) {
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
header('Content-Type: application/json;charset=UTF-8');
echo json_encode($row);
}
} else {
echo 'NO POSTS TO DISPLAY';
}
}
}
I've been at this for a couple of hours now, everything similar to my problem on SO seems to be something different and I can't really find a decent plain JavaScript tutorial on returning real data. Everyone wants to use jQuery.
The reason why your code is failing is because you are using
echo json_encode($row);
This will echo an array for every row, but it is not valid JSON. I have corrected your PHP code (note: it has not been tested)
<?php
class BlogRoll extends Connection {
public function __construct() {
$this->connect();
$sql = "SELECT `id`, `user_id`, `user_name`, `content`, `date_created`
FROM `posts`
ORDER BY `date_created` DESC";
$query = $this->connect()->prepare($sql);
$result = $query->execute();
$returnArray = array(); // Create a blank array to put our rows into
if ($result) {
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
array_push($returnArray, $row); // For every row, put that into our array
}
} else {
// Send the JSON back that we didn't find any data using 'message'
$returnArray = array(
"message" => "No data was found"
);
}
header('Content-Type: application/json;charset=UTF-8'); // Setting headers is good :)
exit(json_encode($returnArray)); // Exit with our JSON. This makes sure nothing else is sent and messes up our response.
}
}
Also, you stated this:
If I only have one(1) item I am able to access it data.id, data.user_name, so on and so forth.
That is correct because the array only contains that one item. The example you would access it via data.0.id, data.1.id, data.2.id, etc as each row is in its own array.
You must print only once, e.g. a data "package" from which you will reference the items on the client-side correspondingly. But in your code you're actually printing for each row a data "package".
The solution is to create an array and save the whole fetched data into it. After that the array should be json-encoded and printed.
if ($result) {
// Save the fetched data into an array (all at once).
$fetchedData = $query->fetchAll(PDO::FETCH_ASSOC);
// Json-encode the whole array - once.
// header('Content-Type: application/json;charset=UTF-8');
echo json_encode($fetchedData);
} else {
echo 'NO POSTS TO DISPLAY';
}

Load data from table using PHP & AJAX

I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:
{data: [{IdProduct: "1", Name: "Name here..........",…}]}
For example I want to select only Name, I tried doing this:
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
success: function (data) {
var aRC = JSON.parse(data);
for (var i = 0; i < aRC.length; i++) {
console.log(aRC[i].Name);
}
}
});
}
But this doesn't shows anything, how can I do this? This is my PHP code:
while($row = mysqli_fetch_array($registros)) {
$table.='{
"IdProduct":"'.$row['IdProduct'].'",
"Name":"'.$row['Name'].'",
"Description":"'.$row['Description'].'",
"ImagePath":"'.$row['ImagePath'].'"
},';
$table = substr($table, 0, strlen($table) -1);
echo '{"data":['.$table.']}';
}
There are couple of things you need to change in your code, such as:
That's not how you should create a json string. Create an empty array before the while() loop and append the row details to this array in each iteration of the loop. And after coming out of the loop, simply apply json_encode() function to the resultant array to get the final json string.
$table = array();
while($row = mysqli_fetch_array($registros)) {
$table[]= array(
'IdProduct' => $row['IdProduct'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
);
}
echo json_encode($table);
Since you're expecting a json string from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, simply loop through the json result to get the relevant data.
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
alert(data[i].Name);
}
}
});
}
First off, your shouldn't echo the json data in the loop. It should be outside the loop.
You shouldn't build your own json data either.
Let's build an array that looks like the json response you want. Then we'll use the function json_encode() to encode it as a proper json-string:
// Define the response array
$response = [
'data' => []
];
while($row = mysqli_fetch_array($registros)) {
// Push a new array to 'data' array
$response['data'][] = [
'IdProduct' => $row['IdProduct'],
'Name' =>.$row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
];
}
// Now, let's encode the data:
echo json_encode($response);
In you PHP file make changes according to this:-
$outp = array();
$outp = $res->fetch_all(MYSQLI_ASSOC);
For make sure that json_encode don't return null
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
echo json_encode(utf8ize($outp));
You JavaScript is okay You just need to change code in PHP.

jQuery post callback function set variable returning nothing

I am trying to use a localStorage variable in a php function so I decided to use jquery post() to do so. Afterwards, I want to echo back data to my original file and set it inside a global variable. I have 3 files that connect to each other (its just a bit complicated).
quick_match.php
dataString = "";
$.post("ajaxCtrl.php", {action: "doQuickMatch", numCard: localStorage['numCard'], UI: "<?php echo $_REQUEST['UI']; ?>"}, function(data){ dataString = data; });
ajaxCtrl.php
if($action == "doQuickMatch")
{
//Start Quick Match
$result = $user->getQuickMatch($numCard);
echo $result;
}
User.php
(A big query here but I guarantee it works)
// Perform Query
$result = mysql_query($query);
//Hold the array objects in a string
$string = "";
// Iterate through results and print
while ($row = mysql_fetch_assoc($result)) {
$string .= '{ image: \'http://personals.poz.com'.$row['my_photo'].'\', user_id: \''.$row['id'].'\', user_prof: \'http://127.0.0.1/personalz.poz/v2/member.php?username='.$row['id'].'\'};';
}
return $string;
After all of this, I'm supposed to use the string and split it so I can get an array and continue on with what I was doing. However, the callback keeps on returning nothing so I am not sure what I did wrong. Can anyone offer insight to this please? Thank you in advance.

Categories