Cant read JSON produced by PHP into my javascript [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
Im using AJAX to request a php file that returns JSON
$.ajax({ url: 'php/invoice.php',
dataType: "json",
data: {id: 1},
type: 'post',
success: function(response) {
alert(response);
}
});
The php file im using is echoing json via json_encode:
while($row = mysqli_fetch_assoc($result))
{
$queryResults[] = $row;
}
echo json_encode($queryResults);
an example of what the php is sending back is:
[{"id":"1","firstname":"Brent","lastname":"Doe","telephone":"888888888","zip":"11111"}]
What im getting when I alert(response) is "[object Object]"
What I want is to alert the first name or any other property in the json ie. "Brent"
Iv'e tried alert(response.firstname); and it returns as undefined.
iv'e also tried to remove the dataType: "json" from the ajax request and just parse the json when it gets returned via var obj = $.parseJSON(response) and alert(obj.firstname)
I dont know what im doing wrong, I also dont know why there [ ] around the json when I use json encode. Im assume its because its returning a array from json objects which may be my problem? Im new to this and would appreciate any help or resources!
Iv'e done a couple hours of research and still cant find a answer. Thanks in advance!

The problem lies here (as #echeese first pointed out)
while($row = mysqli_fetch_assoc($result))
{
$queryResults[] = $row;
}
echo json_encode($queryResults);
Notice how the JSON looks (notice the [..] ?)
[{"id":"1","firstname":"Brent","lastname":"Doe","telephone":"888888888","zip":"11111"}]
It translates to this:
0 => {"id":"1","firstname":"Brent","lastname":"Doe","telephone":"888888888","zip":"11111"}
and you need to access it like this:
response[0].firstname

The problem that you're having is that your response is returning an array of objects. You should be able to get the first name by using response[0].firstname

Related

How to receive echoed data from a php file via URL? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm trying to get some basic Javascript and PHP working for a coding challenge I'm taking part in and I need to receive a JSON object from a PHP file to use in my Javascript that displays the current date on a HTML page. I've tried a few different methods and can't seem to get any to work, is there something I'm missing here?
I've tried using jQuery getJSON as well as running the PHP in the same HTML file as the Javascript.
This is the PHP file and its output:
echo json_encode([
"date" => getthedate()
]);
function getthedate() {
return date("Y/m/d");
}
{"date":"2019\/07\/04"}
This is what I've most recently been trying in Javascript:
function getDate() {
var theDate = $.getJSON(
"http://localhost/coding-challenge/get-date.php",
function(data)
);
JSON.parse(theDate);
document.getElementsByClassName("date")[0].innerHTML = theDate;
}
I was expecting this Javascript to retrieve the JSON object that the PHP file echoes and then display it in the HTML file's "date" class, an empty paragraph. However this just results in a blank space where the date paragraph is.
$.getJSON is asynchronous, so you should set the data inside it's success callback:
function getDate() {
$.getJSON("http://localhost/coding-challenge/get-date.php", data => {
document.getElementsByClassName("date")[0].innerHTML = data;
});
}
Try to send the correct HTTP resonse header for JSON. Then jQuery will parse the response for you.
header('Content-Type: application/json');
echo json_encode([
'date' => getthedate()
]);
function getthedate() {
return date("Y/m/d");
}
JS
$.getJSON("http://localhost/coding-challenge/get-date.php", function( data ) {
console.log(data);
alert(data.date);
});

json_decode expects parameter 1 to be string, says array is given. Why doesn't my string pass properly?

So, I've been struggling with this for the entire weekend and I still can't figure out what's wrong. I'm trying to pass some data through json_decode to be able to save it to a file and I keep getting the error it expects a string but an array is given. I'm using jQuery and PHP.
The data I send through the ajax call is, according to console.log(noBrack):
{"ID":2,"LLID":"LLID2","volNaam":"Test - 0","norm":"Zicht","instalDatum":"17-11-2017","endDate":"18-11-2017","serie":"0","klant":"Testklant","file":"data/Testklant (Heerenveen)/LLID2.json","gelDat":"27-10-2018"}
My Ajax call is:
$.ajax({
url: 'quickGrade.php',
type: 'POST',
data: noBrack,
datatype: 'json',
success:function(data){
alert(data );
}
});
My PHP code is:
$testSave = 'data/gradeTest.json';
$decode = json_decode($_POST, true);
file_put_contents($testSave, $decode);
Can anyone find out what I'm doing wrong? I've tested my string with an online json_decode tester and it said it was valid so I'm kinda hardstuck here.
The way you are sending data will give you $_POST array in php code. So actually you do not need to decode because the data is coming as $_POST array not a JSON string.
You should use json_encode to get JSON string to store in file. Because $_POST is an array, so you can't decode it like a Json string.
Your code will become this:
$testSave = 'data/gradeTest.json';
file_put_contents($testSave, json_encode($_POST));
You can read more about:
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php

How to receive data in php sent from javascript [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I am sending some data from my pain page to app.php using javascript
$(document).on('click', '.app' , function(){
var data=$(this).attr("id");
window.location="application/app.php?data="+data; //data send in this statement
});
my php code is this :
<?php
if($_GET['data'])
{
echo $app_id=$_GET["data"]; receiving data
}
?>
It works sometime but now it is giving Notice in an alert box: Undefined index data in app.php. But it is showing the echo.
I want to know how I can receive the data I need using $_POST or $_GET. like we receive by making an Ajax call. But I haven't specified something like this in Javascript. is there any way to this?
I want to clarify that the data exists and it is non empty because echo is successfully printing that on the page
Try this:
<?php
if(!empty($_GET['data']))
{
$app_id = $_GET['data']; // receiving data
}
?>
Please be aware that passing data without validation is not secure. Reccomended reading: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
use isset() to first check if the key exists. data won't exist in $_GET when it's not passed via a parameter in the url
you probably want some logic that looks like this:
if (isset($_GET['data'])) {
if (!empty($_GET['data'])) {
$appId = $_GET['data'];
}
else {
// data exists, but it's empty
}
}
else {
// data does not exist
}
and maybe you even want to check if it's a valid id, like being numeric or something

return a PHP object to an ajax call

I'm learning PHP OOP, and getting used to all of these objects.
When I create an object in a PHP file called via an $.ajax function, I want to deliver the answer back. But how am I supposed to send back the object to my ajax call ? Before OOP, I was putting everything into an array, then json_encode() the array, and everything worked perfectly. How to adapt this using OOP?
Thanks a lot for your answers
Romain
Example:
On the client side
$.ajax(
{
url:"test.php",
type:"POST",
dataType:"json",
success:function(json)
{
// json into template
}
});
On the server side: test.php
require_once("bdd.php");
function loadClass($class)
{
require $class.".class.php";
}
spl_autoload_register('loadClass');
$PersonneM = new PersonneManager($db);
$perso = $PersonneM->get("123456");
$perso = serialize($perso); // ????????????
header('Content-type: application/json');
echo json_encode(array("result",$perso));
either use serialize or __toString to create a JSON-representation of your data that you can send down the tube. You will not be needing an extra array around your object.
However, there is an error in some JSON parsers/interpreters that can mess with your data when not wrapped in an array. But I haven't heared anything of this issue since a couple of years so you should be safe

Phonegap - Send array from mvc controller to Javascript using Ajax

I'm using phonegap and I'm trying to send an array encoded as json from a controller to view.
In my controller (server side):
$users = Model_Users::find(1);
$a=$users->to_array();
return json_encode($a);
In my view (into smartphone application using phonegap):
$(document).ready(function() {
$.ajax({
url: 'my/url...',
method: 'POST',
data: {
},
success: function(data) {
alert(data);
}
});
});
This working fine, infact in the view I get this alert:
data = {"name":"Jhon","surname":"Larry","age":"25"}
This work because the result of the query is only one row.
Instead when I try to get more than one query result, example:
$users = Model_Users::find('all');
$a=array();
foreach ($users as $user){
array_push($a,$user->to_array());
}
return json_encode($a);
In this case an empty response comes up, in fact I get this alert:
data = []
What is the problem?
Thanks in advance
I will try to build an answer with some tips based on what we already know thanks to the comments.
First of all now we are sure that the JSON is valid (jsonlint.com for example).
So,now, we are completely sure that the problem resides on the PHP / server-side.
My solutions:
Pay attention to not echo/return something before the value you need;
Change return with echo;
Add an exit; statement after the echoed value to be sure that no other characters will be included in the server answer;
Not exactly needed, but you can even think to set the header('Content-Type: application/json');
Debug looking at the console and using console.log instead of alert() (there are a lot of threads explaining the difference
Hope this will help!

Categories

Resources