why i am getting object object result from my ajax to php? - php

here's my jquery:
$.ajax({
url: 'function.php',
type: 'post',
datatype: 'json',
success: function(data){
var toAppend = '';
if(typeof data === "object"){
for(var i=0;i<data.length;i++){
toAppend += '<li>'+data[i]["asin"]+'</li>';
}
$('.results').append(toAppend);
}
}
});
here's my php:
echo json_encode($items_from_amazon);
I already use the firebug and i get successfully the json values from response but why i am getting object object output?what wrong?am i missing something?

From what i see in your print_r($items_from_amazon); output, you have Array-Object-Object, try use this code:
for(var i=0;i<data.length;i++){
toAppend += '<li>'+data[i]["asin"][0]+'</li>';
}

echo json_encode(array_values($items_from_amazon));
This should make sure your JSON will be an array. However, it drops any string keys.
If $items_from_amazon is an object, you can cast it to an array:
echo json_encode(array_values((array)$items_from_amazon));
EDIT:
If I misunderstood the question and you want to know why your ASIN elements have objects:
You may want to change the code that generates $items_from_amazon so it doesn't append, but assign the ASIN.
// This appends
$item['asin'][] = $asin;
// This assigns
$item['asin'] = $asin;
// Note: make sure $asin is a string, not an object or array...
You could also use data[i]["asin"][0] in client code instead.

Related

Array values returns null

I am making post request with ajax and sending data with json format.Then I am fetching json with php and decode it into an array.When I print out whole array there is no problem. I can see the key value pairs.But when I try to print out this array's one of index value it returns null.What could be the problem?Here is my ajax request
$(function() {
$("#del").click(function() {
var file_id = 32
var file_update = 1321321
var obj = {
file_id: file_id,
file_update: file_update
};
$.ajax({
type: "post",
url: "config/ajax.php",
data: {
"file_update": JSON.stringify(obj)
},
success: function(response) {
alert(response);
}
})
})
})
Here is my php code
if (isset($_POST["file_update"])) {
$file_update = json_decode($_POST["file_update"], true);
$x = $file_update[0];
var_dump($x);
var_dump($file_update);
}
The $file_update array is associative, therefore it doesn't have integer keys, its keys are strings.
$file_update[0] does not exist and this statement should throw an error given you have proper error reporting configured.
If you want to access specific array values use:
$file_update['file_id'];
$file_update['file_update'];
If you want to access the first element of an associative array you can use the following:
$key = array_keys($file_update)[0];
$value = $file_update[$key];

How to create a two-dimensional array in PHP and iterate through it with Javascript

Im currently trying to do the follow:
Request a PHP file from my image.js code
In the request call - query out data from my mysql database and save
it in a PHP array
Return the array to image.js as a JSON object.
I got nr 1 + nr 3 covered - what im strugling with is how to save my database attributes correctly into the PHP array and afterwards iterate through each record from the json callback.
Database attribute example:
player_id (unique key) || player_name || player_country || player_image || player_league ||
Question/Challenge 1: Saving the Array (this is what im not sure of)
while ($row = mysql_fetch_assoc($res))
{
$myCallbackArray[] = array($row['player_id'], $row['player_name'], $row['player_country'], $row['player_image']);
}
- The following array, will just be one "flat-array" with no dimension based on saving all corresponding attributes under seperate player_id's?
To give some some context - and assuming the array is fine, we then in a 'next-step' send it back to JS
$callback = $myCallbackArray;
echo json_encode(array('returned_val' => $callback));
Question/Challenge 2: Accessing the array values in JS (this is what im not sure of)
//Save the data
var url = "request.php"; //
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: { user_id: id},
success: function(data)
{
//HERE WE HANDLE THE RETURNED ARRAY
if(data.returned_val) {
for( var i = 0; i < data.returned_val.length; i++ ){
//HERE I WOULD LIKE TO MAKE THE DIFFERENT ATTRIBUTES ACCESSABLE
}
},
error:function() {
//FAILURE
}
});
return false;
-So in this part im not sure how to actually handle the multi-dimensional array from PHP. I assume we need to save it out in a Javascript array and then we can probably iterate / access each value through an foreach loop - but yet again,- how im not entirely sure?
I'll suggest to use json_encode:
$myCallbackArray []= (object) array(
"player_id" => '...',
"player_name" => '...',
"player_country" => '...',
"player_image" => '...',
"player_league" => '...'
);
$json = json_encode($myCallbackArray);
$json is actually the following:
[{"player_id":"...","player_name":"...","player_country":"...","player_image":"...","player_league":"..."}]
which is valid JSON and you could easily use it in javascript.
I think your accessing the data wrong in your success function, the data comes back as an array. Here is an example:
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: {user_id: id},
success: function(data){
var myval = data["returned_val"];
alert(myval);
},
error:function() {
//FAILURE
}
});

jQuery parse/display json data from php json_encode

Initial .ajax call in jquery:
$.ajax({
type: 'post',
url: 'items_data.php',
data: "id="+id,
dataType: 'json',
success: function(data){
if(data){
make_item_rows(data);
}else{
alert("oops nothing happened :(");
}
}
});
Sends a simple string to a php file which looks like:
header('Content-type: application/json');
require_once('db.php');
if( isset($_POST['id'])){
$id = $_POST['id'];
}else{
echo "Danger Will Robinson Danger!";
}
$items_data = $pdo_db->query ("SELECT blah blah blah with $id...");
$result_array = $items_data->fetchAll();
echo json_encode($result_array);
I am catching the $result_array just fine and passing it on to another function. I double checked that there is indeed proper values being returned as I can just echo result to my page and it displays something like the following:
[{"item_id":"230","0":"230","other_id":"700"},{"item_id":"231","0":"231","other_id":"701"},{"item_id":"232","0":"232","other_id":"702"}]
I am having trouble figuring out how to iterate through the results so I can inject values into a table I have in my HTML. Here is what I have for my function:
function make_item_rows(result_array){
var string_buffer = "";
$.each(jQuery.parseJSON(result_array), function(index, value){
string_buffer += value.item_id; //adding many more eventually
$(string_buffer).appendTo('#items_container');
string_buffer = ""; //reset buffer after writing
});
}
I also tried putting an alert in the $.each function to make sure it was firing 3 times, which it was. However no data comes out of my code. Have tried some other methods as well with no luck.
UPDATE: I changed my code to include the parseJSON, no dice. Got an unexpected token error in my jquery file (right when it attempts to use native json parser). Tried adding the json header to no avail, same error. jquery version 1.9.1. Code as it is now should be reflected above.
Set the dataType:"JSON" and callback in your ajax call.
For example:
$.ajax({
url: "yourphp.php?id="+yourid,
dataType: "JSON",
success: function(json){
//here inside json variable you've the json returned by your PHP
for(var i=0;i<json.length;i++){
$('#items_container').append(json[i].item_id)
}
}
})
Please also consider in your PHP set the JSON content-type. header('Content-type: application/json');
function make_item_rows(result_array){
var string_buffer = "";
var parsed_array=JSON.parse(result_array);
$.each(parsed_array, function(){
string_buffer += parsed_array.item_id;
$(string_buffer).appendTo('#items_container');
string_buffer = "";
});
}
You need to parse it with jQuery.parseJSON
function make_item_rows(result_array){
var string_buffer = "";
$.each(jQuery.parseJSON(result_array), function(index, value){
string_buffer = value.item_id;
$(string_buffer).appendTo('#items_container');
});
}
Try this.
function make_item_rows(result_array){
var string_buffer = "";
$.each(result_array, function(index, value){
value = jQuery.parseJSON(value);
string_buffer += value.item_id;
$(string_buffer).appendTo('#items_container');
string_buffer = "";
});
}
Assuming you already parsed the json response and you have the array. I think the problem is you need to pass a callback to $.each that takes and index and an element param
function make_item_rows(result_array){
$.each(result_array, function(index, element){
document.getElementById("a").innerHTML+=element.item_id;
});
}
(Slightly modified) DEMO
for starters within the $.each you need to access the properties of the instance of object contained within result_array, not result_array itself.
var string_buffer = "";
$.each(result_array, function(index, object){
/* instance is "object"*/
alert( object.item_id);
});
Not entirely sure what you are expecting from this line: $(string_buffer).appendTo('#items_container');
$(string_buffer) does not create a valid jQuery selector since nothing within string_buffer has a prefix for class, tagname or ID, and values from json don't either
If just want the string value of the item_id appended :
$('#items_container').append( object.item_id+'<br/>');
If you are receiving this using jQuery AJAX methods you don't need to use $.parseJSON as other answers suggest, it will already be done for you internally provided you are setting correct dataType for AJAX

How Print json Array in Javascript

PHP: Code:
$category_searchresult = $db->db_query("SELECT category_code, category_name, category_comment FROM qa_categories WHERE ".$search_by." LIKE '%".$search_string."%'");
$i=1;
$qa = array();
while($categories_query_result = mysql_fetch_array($category_searchresult))
{
$qa[$i][] = $categories_query_result['category_code'];
$qa[$i][] = $categories_query_result['category_name'];
$qa[$i][] = $categories_query_result['category_comment'];
$i++;
}
echo json_encode($qa);
JS Code:
$.ajax({
type: "POST",
url: "ajax_js.php",
data: search_data,
cache: false,
success: function(search_result) {
//Print Here
});
Current Output IS from PHP:
{"1":["4BA3CC","Fontaneria","Para la Casa"],"2":["CF0345","Herramientas","Herramients de Hogar"],"3":["1265CA","Luces","Luces de todo tipo"],"4":["4C4C9F","Vidrios","Reflectores de auto"]}
Many Thank's
Add a
dataType: 'json'
to your .ajax() call. That will tell jQuery to decode the JSON string from PHP back into a native Javascript data structure. Alternatively, you can take the data parameter in the success handler and explicitly do the decoding yourself:
success: function(data) {
var data = jquery.parseJSON(data);
}
Not quiet sure what the output should be but this is the code you can use to traverse a json object:
for(var key in search_result) {
var result = search_result[key];
//result is an array, so you can traverse or access each value by the key
// or you can join all the values together
var joinedValues = result.join(' | ');
//joinedValues will be something like '4BA3CC|Fontaneria|Para la Case'
}
You may want to set those values into a container object in the page to diplay them of course.
Hope this helps.

JSON returned as individual string and not objects

I am using Codeigniter and trying to use the jQuery autocomplete with it. I am also using #Phil Sturgeon client rest library for Codeigniter because I am getting the autocomplete data from netflix. I am return correct JSON and I can access the first element with
response(data.autocomplete.autocomplete_item[0].title.short);
but when I loop through the results
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short)
}
it acts like a string. Lets say the result is "Swingers", it will return:
Object.value = s
Object.value = w
Object.value = i
and so on.
the js:
$("#movies").autocomplete({
source: function(request, response) {
$.ajax({
url: "<?php echo site_url();?>/welcome/search",
dataType: "JSON",
type:"POST",
data: {
q: request.term
},
success: function(data) {
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
}
});
}
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
$(ul).attr('id', 'search-autocomplete');
return $("<li class=\""+item.type+"\"></li>").data( "item.autocomplete", item ).append(""+item.title+"").appendTo(ul);
};
the controller:
public function search(){
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// set var equal to results
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'));
//$this->rest->debug();
//$json_data = $this->load->view('nice',$data,true);
//return $json_data;
echo json_encode($netflix_query);
}
the json return
{"autocomplete":
{"autocomplete_item":[
{"title":{"short":"The Strawberry Shortcake Movie: Sky's the Limit"}},
{"title":{"short":"Futurama the Movie: Bender's Big Score"}},
{"title":{"short":"Daffy Duck's Movie: Fantastic Island"}}
...
any ideas?
thanks.
there are some console logs with the return
the url
in, as you've noticed, doesn't do what you'd like with arrays. Use $.each
As far as I know, for (property in object) means that you want to access each of its properties rather than accessing them via the index. If you want to access them via the index, you probably want to use the standard for loop.
for (i = 0; i <= 10; i++) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
or if you still want to use your code, try this:
for (i in data.autocomplete.autocomplete_item) {
response(i.title.short);
}
I haven't test them yet but I think you have the idea.
ok I figured out the correct format that I need to send to the autocomplete response method:
the view
$("#movies").autocomplete({
minLength: 2,
source: function(request, response) {
$.post("<?php echo base_url();?>welcome/search", {q: request.term},
function(data){
//console.log(data);
response(data);
}, 'json');
}
});
the controller:
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// Pull in an array
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'),'json');
$json = array();
foreach($netflix_query->autocomplete->autocomplete_item as $item){
$temp = array("label" => $item->title->short);
array_push($json,$temp);
}
echo json_encode($json);
what was needed was to send back to the view an array of objects. Thank you guys for all your answers and help!!

Categories