Unable to retrieve JSON value from PHP and Javascript - javascript

I have the following JSON below that I want to parse and get the value of the TotalRows. However, in my PHP and JavaScript it returns an error or undefined when I try to access it and I am not sure why.
For JavaScript:
var data = <?php echo json_encode($customers); ?>;
console.log(data.TotalRows)
I even placed console.log(data) and it gave me the JSON I posted and then I did console.log(data[0].TotalRows) and it give me undefined.
My code for PHP is, where $customers returns the JSON below:
$customers = $customerDB->findCustomer(5, 1);
$arr = json_decode($customers, true);
echo $arr["TotalRows"];
[
{
"TotalRows":91,
"Rows":[
{
"CompanyName":"Ana Trujillo Emparedados y helados",
"ContactName":"Ana Trujillo",
"ContactTitle":"Owner",
"City":"M\u00e9xico D.F.",
"Country":"Mexico"
},
{
"CompanyName":"Antonio Moreno Taquer\u00eda",
"ContactName":"Antonio Moreno",
"ContactTitle":"Owner",
"City":"M\u00e9xico D.F.",
"Country":"Mexico"
},
{
"CompanyName":"Around the Horn",
"ContactName":"Thomas Hardy",
"ContactTitle":"Sales Representative",
"City":"London",
"Country":"UK"
},
{
"CompanyName":"Berglunds snabbk\u00f6p",
"ContactName":"Christina Berglund",
"ContactTitle":"Order Administrator",
"City":"Lule\u00e5",
"Country":"Sweden"
},
{
"CompanyName":"Blauer See Delikatessen",
"ContactName":"Hanna Moos",
"ContactTitle":"Sales Representative",
"City":"Mannheim",
"Country":"Germany"
}
]
}
]

Its an array of object, so you would get TotalRows by
console.log(data[0].TotalRows);

Actually, I figured it out. The following worked:
var data = <?php echo json_encode($customers); ?>;
var data = JSON.parse(data);
console.log(data[0].TotalRows);

Related

Structured data

Hello I am working on the data structure. I have following problems:
when I dump ($ data), I have all the info.
I am looking for how has integrated a php variable in json.
here is my piece of code. I have serious problem with concatenation. thank you in advance
<script type="application/ld+json">
{
"name":"<?php ($data[restaurant_name]);?>"
"author": {
"#type": "<?php.....?>",
"name": "<?php.....?>"
},
"datePublished": "<?php ($data[date]);?>",
"description": "<?php ($data[description]);?>",
}
</script>
Do not construct JSON objects like this, it's error-prone!
just using PHP construct an associative array, then use json_encode() function to create valid JSON object and pass whole to JS.
// variables
$name = 'Foo';
$type = 'bar';
$authorName = 'John';
// array
$data = [
'name' => $name,
'author' => [
'#type' => $type,
'name' => $authorName
]
];
// encode to JSON and display
echo json_encode($data);

Error in performing ajax post data and echoing those data on the console log

i was asked to perform ajax post data to the php script which will include the another script which perform sql connection to the database and get all data and convert data to json format. then the json data will be shown on the console. also i also was asked to modify the ajax to post the values such as name and the religion such as abdullah and muslim respectively.. I want to perform coding on the passwrapper to get and show data on the console.log..
in ajax.html
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: 'Abdullah',
lastReligion: 'Muslim',
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
in passwrapper.php
<?php
include 'student.php';
executePass();
receivePost();
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
echo '<script>console.log("Last='.$_POST["lastName"].' lastReligion='.$_POST["lastReligion"].'");</script>';
}
}
?>
in student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
?>
my question is how to show all data on the console log and also show the post data on the console.log.. please do not modify the student.php... only modify the passwrapper.php
This should output the data from both functions combined, as JSON which your ajax "success" function can log. Your existing code has an issue because one part of it tries to return JSON, and the other part tries to return a <script> block, which is not valid JSON, and also would likely not be executed by the browser anyway for security reasons.
I've also modified the two functions so they return their output to the caller as PHP variables, rather than directly echo-ing JSON strings to the browser. This makes them more re-usable, and also makes it much simpler to then combine the results into a single coherent JSON object to output to the browser.
The console.log(data); command in your existing ajax "success" function will take care of logging all the returned data to your browser console.
$studentArr = executePass();
$postArr = receivePost();
echo json_encode(array("students" => $studentArr, "postvars" => $postArr));
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
return array ("lastName" => $_POST["lastName"], "lastReligion" => $_POST["lastReligion"]);
}
}
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
return $json_array;
}
Now, I don't know the exact structure of your "students" data, so I can't give you an exact example of the output you'll receive, but if I were to assume that your students table had 3 simple fields - "id", "firstname", and "lastname", and there were 4 rows in the table, you would get a final JSON output something like this:
{
"students":
[
{
"id": 1,
"firstname": "firstname1",
"lastname": "lastname1"
},
{
"id": 2,
"firstname": "firstname2",
"lastname": "lastname2"
},
{
"id": 3,
"firstname": "firstname3",
"lastname": "lastname3"
},
{
"id": 4,
"firstname": "firstname4",
"lastname": "lastname4"
}
],
"postvars": {
"lastName": "Abdullah",
"lastReligion": "Muslim"
}
}
You have a JSON object with two properties. The "students" property contains an array of all the students in your table. The "postvars" property is another object containing properties matching the two POST variables you wanted to capture.

How to extract parts of response of AJAX from PHP

Need some help here, i've been searching for related issues here but nothing seems to answer my problem. Ok so here how it goes
I have a simple search function that search through my database and I used an ajax to pass the data and get back the response and I manage to do that but my problem is that I can't seem to display the response the way I wanted to.
Here's my Ajax
$.ajax({
url: url, /// defined url
type: type, ///defined type
data: data, ///defined data
success: function(response){
//here I want to display something like
$('#display').html(the name of the employee);
}
});
Here's the ajax response
{
"employee": [{
"badgeno": "123 ",
"name": "John G. Doe",
"success": true
}]
}
{
"employee": [{
"badgeno": "456 ",
"name": "Jane G. Doe",
"success": true
}
I want to get the employee Name in there and display it in my page. How exactly am I gonna do that?
Thanks in advance. I'm still a newbie BTW
Here's the PHP
$getEmp = $this->Employee_model->search_emp($employee);
$count = count($getEmp);
if($getEmp){
for ($i=0; $i < $count; $i++) {
$data['employee'][$i] = array(
'badgeno' => $getEmp[$i]->BADGENO,
'name' => $getEmp[$i]->NAME,
'success' => true
);
echo json_encode($data);
}
print_r($data);
//$this->load->view('admin/home', $data);
}
Try:
employee_name= data.employee[0].name;
$('#display').html(employee_name);
Link to fiffle:
https://jsfiddle.net/fcz53htw/
If you have more then one name, first add them to array, only then print then json_encode of the array.
Now its wont wont work because you printing twice.
Try change your php to this:
$getEmp = $this->Employee_model->search_emp($employee);
$count = count($getEmp);
if($getEmp){
for ($i=0; $i < $count; $i++) {
$data['employee'][$i] = array(
'badgeno' => $getEmp[$i]->BADGENO,
'name' => $getEmp[$i]->NAME,
'success' => true
);
//echo json_encode($data);
}
echo json_encode($data);
//$this->load->view('admin/home', $data);
}
On php you are write the results twice delete the printr only use json_encode

Cant access data from json

I'm having trouble with JSON. I made this in PHP and I'm sending it to my JavaScript, but I can't get the values.
[
{
"book":[
{
"dir":"extract\/pg1065.epub"
},
{
"dir":"extract\/pg1065.epub\/1065\/0.css"
},
{
"dir":"extract\/pg1065.epub\/1065\/1.css"
},
}
{
"book":[
{
"dir":"extract\/pg6130-images.epub"
},
{
"dir":"extract\/pg6130-images.epub\/6130\/0.css"
},
}
]
I'm trying to access it with
var obj = JSON.parse(result);
alert(obj.book[0].dir[1]);
Anyone have any ideas?
First you need to validate your json, i have validate your json it gives error.
In your json dIr is id.
You have defined 3 dir id for same object this may be error.
EDIT: I missed it but first comment explains your missing your closing square brackets for the book arrays. Add that in and your good to go. Validate the JSON first.
You don't need to do JSON.parse you can simply do
var data = <?php echo "Your generated JSON code"; ?>;
Worth a note you can create your data structure in PHP and then simply use json_encode, then you can be sure it will be valid JSON
var data = <?php echo json_encode($yourData); ?>;
You have output an array so to get the first object you will do something like
var firstObj = data[0];
To get the first dir of the first book
var firstDir = data[0]["book"][0]["dir"];
[
{
"book": [
{
"dir": "extract/pg6130-images.epub"
},
{
"dir": "extract/pg6130-images.epub/6130/0.css"
}
]
},
{
"book2": [
{
"dir": "extract/pg6130-images.epub"
},
{
"dir": "extract/pg6130-images.epub/6130/0.css"
}
]
}
]
Your JSON was not valid i used: http://jsonlint.com/ to sort it!
Now you should be able to acess the data fine.
The code shown in the question is not a valid JSON. There are missing closing square brackets for each of the book arrays and (thanks to #punund) a missing comma between array members. The correct JSON would be this:
[
{
"book":[
{
"dir":"extract\/pg1065.epub"
},
{
"dir":"extract\/pg1065.epub\/1065\/0.css"
},
{
"dir":"extract\/pg1065.epub\/1065\/1.css"
}
]
},
{
"book":[
{
"dir":"extract\/pg6130-images.epub"
},
{
"dir":"extract\/pg6130-images.epub\/6130\/0.css"
}
]
}
]
You should not normally be printing JSON directly, but instead creating a JSON object in PHP and then using json_encode function. The following PHP will produce valid JSON for your scenario:
<?php
$result = array(
(object)array("book" => array((object)array("dir" => "extract/pg1065.epub"),
(object)array("dir" => "extract/pg1065.epub/1065/0.css"),
(object)array("dir" => "extract/pg1065.epub/1065/1.css"))),
(object)array("book" => array((object)array("dir" => "extract/pg6130-images.epub"),
(object)array("dir" => "extract/pg6130-images.epub/6130/0.css")))
);
echo json_encode($result);
?>

jQuery getJSON Undefined Error

Alright, so I've done a bit of searching and trying with no luck. I'm hoping that someone here can point me in the right direction. I have a JSON feed that I'm working with, which is supposed to output a variety of data. Currently, it just sends back and "UNDEFINED" response for all variables. Here is the JS I'm using:
$("#loaduserdata").click(function(){
$("#userdata tbody").html("");
$.getJSON("trendFetch", function(data){
$.each(data.list, function(i, data){
var jsondata = data.action;
console.log (jsondata);
});
}
);
I'm not sure where the problem exists, because console isn't giving me any kind of errors or any reason to think that the JSON isn't formatted correctly: http://i.imgur.com/ySpdR.png
For whatever it's worth, here is the code I'm using to generate the JSON - maybe there is an issue on that end?
$curl = curl_init();
$url = 'http://api.site.com';
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
if($resp){
echo $resp;
header("Content-Type: application/json", true);
}
else {
echo 'Error - no response!';
}
curl_close($curl);
EDIT - including JSON output:
{
"status": "ok",
"list": {
"list_id": "2gz",
"title": "Test List",
"description": "description text...",
"image": [
"http://t2.gstatic.com/images?q=tbn:ANd9GcTz6_4aV6oHsI2kgJRRoSFCTWbew5ChTeBrAmXYh4Gez2J7usm8nwMOsA",
"http://cdn.list.ly/logos/default-list-image.png"
],
"views": 0,
"item_count": 1,
"curator_count": 1,
"follower_count": 1,
"listly_url": "http://api.list.ly/list/2gz-test-list",
"items": [
{
"item": {
"name": "Link 1",
"image": "http://t2.gstatic.com/images?q=tbn:ANd9GcTz6_4aV6oHsI2kgJRRoSFCTWbew5ChTeBrAmXYh4Gez2J7usm8nwMOsA",
"note": null,
"url": null,
"likes": 0,
"dislikes": 0
}
}
],
"suggested_items": []
}
}
echo $resp;
header("Content-Type: application/json", true);
should be:
header("Content-Type: application/json", true);
echo $resp;
You need to send HTTP headers before you output any content.
Set the header before any output
header("Content-Type: application/json", true);
echo $resp;
Musa was able to solve this for me, so in case someone Googles, the problem was that I was trying to use $.each when I didn't need to. Here is the correct code in case anyone is interested:
$.getJSON("trendFetch",function(data){
var tblRow =
"<tr>"
+"<td>"+data.list.list_id+"</td>"
+"<td>"+data.list.title+"</td>"
+"<td>"+data.list.description+"</td>"
+"</tr>"
$(tblRow).appendTo("#userdata tbody");
}
);
It'd help if you provided the JSON response.
When I'm having these types of issues, I typically take a step back (in the code) and console.log() earlier. For example, console.log(data) within the function(data) {}.
I think -- from looking at the output -- that your problem is that list isn't actually a list. data.list is, in fact, an object. Therefore .each() will iterate over the individual items (like list_id, title, etc). None of these have a .action property.
I can't see any action property, so I can't make a solution suggestion. It's possible that it's within the list object -- but you're still treating it like an array (as if it's list: [{}, {}] rather than list: {}). In this case, you either need to fix the returned JSON or get rid of the $.each(), and just console.log(data.list.action).

Categories