Getting JSON data out of PHP using .get() in jQuery - javascript

I'm trying to get JSON data out of a $.get() jQuery call, but I can't seem to make it work properly.
Here's what my code looks like:
var url = "getDetailsJSON.php?ImageID=" + escape(itemName);
$.get(url, function (data) {
console.log("Success!");
var $detailDiv = $("#description");
var itemDetails = $.parseJSON(data); // Is this how I would get the JSON object in the php code?
console.log("success" + data);
var children = $detailDiv.children();
for (var i = children.length; i > 0; i--) {
$detailDiv.remove(children[i - 1]);
}
var descriptionP = $("<p></p>");
descriptionP.text("Description: " + itemDetails.description);
$detailDiv.append(descriptionP);
var priceP = $("<p></p>");
priceP.text("Price: $" + itemDetails.price);
$detailDiv.append(priceP);
var list = $("<ul></ul>");
$.each(itemDetails.urls, function (index, value) {
var url = itemDetails.urls[index];
var li = $("<li></li>");
var a = $("<a></a>");
a.attr("href", url);
a.text(url);
li.append(a);
list.append(li);
});
$detailDiv.append(list);
});
Here's the PHP code:
<?php
require_once('JSON.php');
$json = new Services_JSON();
$itemGuitar = array(
'id' => 'itemGuitar',
'description' => 'Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it.',
'price' => 5695.99,
'urls' => array('http://www.thewho.com/',
'http://en.wikipedia.org/wiki/Pete_Townshend')
);
$itemShades = array(
'id' => 'itemShades',
'description' => 'Yoko Ono\'s sunglasses. While perhaps not valued much by Beatles fans, this pair is rumored to have been licked by John Lennon.',
'price' => 258.99,
'urls' => array('http://www.beatles.com/',
'http://johnlennon.com/',
'http://www.yoko-ono.com/')
);
$itemCowbell = array(
'id' => 'itemCowbell',
'description' => 'Remember the famous "more cowbell" skit from Saturday Night Live? Well, this is the actual cowbell.',
'price' => 299.99,
'urls' => array('http://www.nbc.com/Saturday_Night_Live/',
'http://en.wikipedia.org/wiki/More_cowbell')
);
$itemHat = array(
'id' => 'itemHat',
'description' => 'Michael Jackson\'s hat as worn in the "Bille Jean" video. Not really rock memorabilia, but it smells better than Slash\'s tophat.',
'price' => 1699.99,
'urls' => array('http://www.michaeljackson.com/',
'http://music.yahoo.com/vid-2143030--Billie-Jean')
);
$details = array (
'itemGuitar' => $itemGuitar,
'itemShades' => $itemShades,
'itemCowbell' => $itemCowbell,
'itemHat' => $itemHat
);
$itemDetail = $details[$_REQUEST['ImageID']];
$output = $json->encode($itemDetail);
print($output);
?>
The 500 internal server error shows:
Connection close
Content-Encoding gzip
Content-Length 20
Content-Type text/html
Date Sun, 01 Sep 2013 22:47:32 GMT
Server Apache/2.2.22 (Ubuntu)
Vary Accept-Encoding
X-Powered-By PHP/5.3.10-1ubuntu3.7
One of the problems with this code is that $.get() doesn't work as expected, because I keep getting a 500 internal server error. Once that is solved, I'm not sure how I'm suppose to extract that JSON data in a PHP file that contains JSON data (see the comment question in code). Any solutions for this?

as pointed out by #joshjwalker, you might use
$itemDetail = $details[$_GET['ImageID']];
echo json_encode($itemDetail);
and your js script might be
getJSON("getDetailsJSON.php",
{"ImageID" : escape(itemName)},
function(data){
console.log(JSON.stringify(data))
}
);

The first step is to find your apache error log. That will usually tell you what your 500 server error is, because there is some sort of error happening on your php side code.
Secondly, that is how you parse a json array from php, but are you using json_encode to encode your php data as json in your php file?
http://php.net/manual/en/function.json-encode.php

Related

How to parse a JSON data that has been received by a PHP scipt

I have sent data from my php script using `json_encode' function.
if I console.log(resp) below is the O/P I get.
data: "{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}" status: "success"
however, if I console.log(resp.data) I get the below data
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}
Now I'm trying to display this data in the data tables for which I am using the below code.
$('#grpList').DataTable().row.add([
resp.data.dept_name,
resp.data.city_name,
resp.data.emp_id,
resp.data.emp_name
]).draw(false);
I'm receiving the following error
DataTables warning: table id=grpList - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
when I am single handed displaying only console.log(resp.data.dept_name) it says undefined
I'll be having multiple JSON response if the data increases, for now, I only have two. I'm not able to figure out how to display multiple data using a loop and appending it to the data table.
I'm using below php code to generate JSON
$jsonArray = "";
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$jsonArray .= json_encode(
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
Because resp.data is an array of objects. You need to get the index first - let's say index 0, or the first object in the array:
$("#grpList").DataTable().row.add([
resp.data[0].dept_name,
resp.data[0].city_name,
resp.data[0].emp_id,
resp.data[0].emp_name
]).draw(false);
And if you want the second object:
$("#grpList").DataTable().row.add([
resp.data[1].dept_name,
resp.data[1].city_name,
resp.data[1].emp_id,
resp.data[1].emp_name
]).draw(false);
Of course, row.add() accepts an array argument as well - so this would work too:
$("#grpList").DataTable().row.add(resp.data).draw(false);
The issue is on server side.
You define $jsonArray as a string ! That's wrong.
Try this instead:
$jsonArray = []; // An ARRAY here!
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
array_push($jsonArray, json_encode( // Use array_push here
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
EDIT
I don't if the above works... Since I did not test it.
But here's how I would have writen it (I guess you'll have more chances with it):
$jsonArray = [];
if($data->num_rows > 0) {
while($row = $data->fetch_assoc()) {
// A temp array to rename the one of the keys...
$tempArray = [];
$tempArray = ["dept_name"] = $row['department_name'];
$tempArray = ["city_name"] = $row['city_name'];
$tempArray = ["emp_id"] = $row['emp_id'];
$tempArray = ["emp_name"] = $row['name'];
// Push to the jsonArray now...
array_push($jsonArray,$tempArray);
}
// And finally the result array... To be json encoded
$result = [];
$result = ["status"] = "success";
$result = ["data"] = jsonArray;
echo json_encode($result);
}
Note that without renaming one key and if there's only 4 data per rows from the DB... You could have done array_push($jsonArray,$row); directly, without using the $tempArray.
So try this... AND then apply Jack's answer. ;)

How to get values of encoded json using php in ajax response?

echo json_encode(array('out' => $out, 'total' => $total ));
Hi, I am getting a JSON data as below using the above PHP code.
var result = {"out":"[{\"tax\":\"SGST#9%\",\"percent\":7.75},{\"tax\":\"CGST#9%\",\"percent\":7.75},{\"tax\":\"SGST#2.5%\",\"percent\":3.11},{\"tax\":\"CGST#2.5%\",\"percent\":3.11}]","total":210}
I need to get the elements in a separate variable like below
var out = [{"tax":"SGST#9%","percent":7.75},{"tax":"CGST#9%","percent":7.75},{"tax":"SGST#2.5%","percent":3.11},{"tax":"CGST#2.5%","percent":3.11}];
var total = 210;
I tried so far with the below codes.
result = JSON.stringify(result);
result = result.replace(/\\/g, "");
var obj3 = JSON.parse(result);
alert(obj3[0]);
But i am not getting any output.
The basic problem is that $out is JSON to start with (so it ends up being double encoded), but it doesn't make sense for it to be JSON in the context.
You could just convert it to a PHP data structure before converting the wider array to JSON:
$out = json_decode($out, true);
$json = json_encode(array('out' => $out, 'total' => $total ));
echo "var result = $json;";
If you don't want to touch the PHP, you can work around that in JavaScript:
$out = json_decode($out, true);
$json = json_encode(array('out' => $out, 'total' => $total ));
echo "var result = $json;";
?>
var out_json = result.out;
var out = JSON.parse(out_json);
In your Ajax setup, add JSON
dataType: 'JSON',
Then in your success function,
success: function(result) {
console.log(result.tax);//gives you the value for the tax key provided it's defined in the php response array
},

unable to get json data from server

My server side code is:
$bus = array(
'meaning' => $name
);
$jsonstring = json_encode($bus);
echo $_GET['callback'].'(' . $jsonstring. ')';
the value displayed on the screen is correct - ?word=heart({"meaning":"heart"})
but when I am reading it with following code its printing the value of meaning as 11200665987893779229_1460521505942
$(document).ready(function(){
$.getJSON('http://mydomain?callback=?','word=heart',function(res){
document.getElementById('print').innerText=''+res.meaning;
});
});
but when I do this:
$bus = array(
'meaning' => 'heart'
);
it's printing the correct value i.e heart
I am not getting why this is happening and how to get the correct value (I am accessing data from my different domain).
JSON.parse() converts any JSON String passed into the function, to a JSON Object.
$(document).ready(function(){
$.getJSON('http://mydomain?callback=?','word=heart',function(res){
obj = JSON.parse(res);
document.getElementById('print').innerText=''+obj.meaning;
});
});
a similar post is here

Associative php array sent via jquery returns [Object object]

I have to pass a php multidimensional array via ajax/jQuery to another php file.
I have encoded the array using
I expected theat every item in the array would have been an array itself. Instead it returns [Object object].
How can I access the data using php?
here's my code:
in the first php file:
<script type="text/javascript">
var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function(){
$.post("send_test.php", {"my_array_data[]":my_array_data}, function( data ) {
alert(data);
});
});
</script>
the other php file:
<?php
$my_array_data = $_POST['my_array_data'];
?>
if I try to retrieve the first row ($my_array_data[0]) I get [Object object]
I just want to access to $my_array_data[0]['category'] etc.
A couple of errors here:
the data you are passing to ajax has an incorrect key using brackets[]
you are not passing the correct object through ajax since my_array_data is never defined
redo your code like this:
PHP
$itemsData = array(
array(
"test" => 30,
"test2" => 10,
),
array(
"test" => 90,
"test2" => 50,
)
);
JS
var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function () {
$.post("send_test.php", {my_array_data: arr_data}, function (data) {
console.log(data);
});
});
Then in send_test.php
$data = $_POST['my_array_data'];
print_r($data);
Result:
Array
(
[0] => stdClass Object
(
[test] => 30
[test2] => 10
)
[1] => stdClass Object
(
[test] => 90
[test2] => 50
)
)
You're putting json-encoded data into the arr_data javascript variable - however you don't appear to be sending that to the other php file.
In the other php file, try using json_decode on the data you're receiving in the POST request:
$my_array_data = json_decode($_POST['my_array_data']);
Yes, as Aric says, name array consistently like this:
var my_arr_data = <?php echo json_encode($itemsData); ?>;

ajax, json, external url load data

i have a problem, help please
i have 2 sites and i want send data each other
first site :
var site_adres = $(location).attr('href');
var myArray = site_adres.split('/');
var site_adi_al = myArray[2];
$.getJSON('xxx.com/site/admin.php?site_adres='+ site_adi_al +'',
{},
function (data) {
$.each( data, function ( i, val ) {
var id=val['id'];
var site_adi=val['site_adi'];
$(".site_adi").append('<li>'+id+' >> <a href="'+site_adi+'"
target="_blank">'+site_adi+'</a></li>');
});
second site:
$site_adi = $_GET["site_adi"];
/* query */
$query = mysql_query("SELECT * FROM site WHERE site_adi = '$site_adi'");
if ( mysql_affected_rows() ){
$row = mysql_fetch_object($query);
$json = array(
"id" => $row->id,
"site_adi" => $row->site_adi
);
}else{
$json["hata"] = "Nothing !";
}
header("access-control-allow-origin: *");
echo json_encode($json);
result zero, what is wrong, help please
You have two basic problems (aside from the security issues explained in the comments on the question).
You are sending site_adres but reading $_GET["site_adi"]. You can't use different names for the same thing without explicitly writing code to link them somehow.
You are looping over data with $.each( data, function ( i, val ) { as if it was an array of objects, but your PHP is only sending a single object (which isn't in an array). You should be accessing the properties of data directly and not using each or val.
You should set up CORS on your webservers to allow them to fetch data from each other, since you're using php, i'm gonna assume you're using apache:
Header set Access-Control-Allow-Origin "*"
replace the * with the ip adress of your other website and vice versa.

Categories

Resources