Display object in javascript - php

I write a script to make an ajax call here is my code
function ajax_post(obj) {
obj = '#'+ obj;
var formData = $(obj).serializeArray();
$.ajax({
url: '__core/info.php',
type:'get',
dataType: 'json',
data: formData,
success: function(resp){
alert(resp);
}
})
}
and here is my info.php
$last_Res = theme::get_last_themes_desk(); //$last_Res is an array
echo(json_encode($last_Res));
but when alert it shows return object object ..... what should i do if datatype is json should i convert it to another format ? $last_Res is an array

In response to your comment (showing the response data, which is an array, containing a single object):
//resp = [{"id":"2","name":"babak_theme","sh_describ":"support css3 and ie 9 ","rate":"3","time":"2"}];
resp = resp[0];
alert('id => ' + resp.id + ', Name => ' + resp.name);//etc...
Will serve you just fine...
$last_Res is an associative array, most likely. JS doesn't have assoc arrays, but converts these to objects/ object literals:
//php:
$foo = array('foo' => 'bar');
//in JS:
var foo = {foo: 'bar'};
alert(foo);//alerts [object Object]
console.log(foo);//shows you what properties/prototypes/methods the object has
That's all there is too it. To access the data:
for (var prop in resp)
{//for "assoc arrays"
if (resp.hasOwnProperty(prop))
{
alert(prop + ' => '+resp[prop]);
}
}
for (var i=0;i<resp.length;i++)
{//for regular arrays
alert(i + ' => ' + resp[i])'
}

In your info.php, you should set the Content-Type header to application/json to indicate what you are returning:
header('Content-Type: application/json');

you haven't posted the json format. usually you can access resp. values like this:
if the json format is:
data['index']['subindex1'] = 'value1'
data['index']['subindex2'] = 'value2'
you can
alert(resp.index.subindex1);

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];

having issue on Accessing Ajax Post data on PHP

I am having some issue on accessing Ajax Post data on server side. I have
var data = {
ox:'A',
oy:'B',
dx:'C',
dy:'D',
method:null
};
I have a jQuery event hamdler like
$("#route").on("click", function(){
var request = $.ajax({
type: "POST",
url: "assets/app.php",
data: data,
cache: false,
dataType: "JSON",
beforeSend: function() {
console.log(data);
}
});
request.done(function( data ) {
console.log(data);
});
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
});
I am able to send the data correctly as it is logging out at beforeSend
{ox: A, oy: B, dx: C, dy: D, method: null}
On PHP side I have
$method = $_POST['method'];
$ox = $_POST['ox'];
$oy = $_POST['oy'];
$dx = $_POST['dx'];
$dy = $_POST['dy'];
now only accessing to one of the $_POST[] data is working like echo $ox; but when I try to access all $_POST[] data like
echo $ox;
echo $dy;
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
I am getting Request failed: parsererror error on .fail()
From the docs:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
So, your response isn't a valid JSON.
What you can do is to create an array, like you are doing:
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
Then encode into json and echo it
echo json_encode(['startPoint' => $startPoint, 'endPoint' => $endPoint]);
On the frontend (javascript) you will get and JSON like
{
'startPoint' : ['ox','oy'],
'endPoint' : ['dx','dy'],
}
the values of ox, oy, dx and dy, of course, will be the values sent before.

Ajax + PHP: null instead of an array

Ajax call is made in the background
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
var data = {elementID: value};
var json = JSON.stringify(data);
$.ajax({
url: 'php/validator_signup.php',
dataType: 'json',
type: 'post',
data: json,
success: function(data){
var parsedResponse = JSON.parse(data);
console.log(parsedResponse);
/*
if(data.response === 1){
$('#'+elementID+'-status').css("background-image", "url(img/signup/no.png)");
}else if(data.response === 0){
$('#'+elementID+'-status').css("background-image", "url(img/signup/yes.png)"); }
*/
}
});
}
}
validator_signup.php received the call. So far in test mode PHP will receive the string, parse it and encode again to return to JS:
$post = $_POST['data'];
$data = json_decode($post, true); //decode as associative array
$details = $data[0];
echo json_encode($details);
JS then needs to print this in console.
I get this:
null
instead of the value which I expect back.
Result is same whether I parse returned data or not.
If I understand it correctly, the problem is on PHP side?
There does not appear to be any value in converting to json when your data is so simple, you can just use a regular js object that jquery will convert to form data.
Also, as both the key and value you send are unknown, i would suggest sending the data in a different structure so its easy to retrieve:
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
$.ajax({
url: 'php/validator_signup.php',
type: 'post',
// ▼key ▼value ▼key ▼value
data: { id: elementID, val: value},
success: function(response){
console.log(response.message);
}
});
}
}
In php you can access the data via $_POST, and as you know the keys, its simple:
<?php
$id = $_POST['id'];
$val = $_POST['val'];
//set correct header, jquery will parse the json for you
header('Content-Type: application/json');
echo json_encode([
'message'=>'Request received with the id of: ' . $id . 'and the value of: ' . $val,
]);
die();
Change:
data: json,
To:
data: { data: json},
This is because you aren't giving the sent data a POST parameter to then be used server side to retrieve it.
Then, you can simply fetch the code server-side like this:
$data = json_decode($_POST['data']);
Hope this helps!
Here, since you are checking whether data is being post, if you see in Network, no data is being posted. To fix it, change this part:
var data = {elementID: value};
To this:
var data = {data: {elementID: value}};
Consider removing conversion of Data
PHP automatically handles the $_POST as an array! So you don't need to use the reconversion. Please eliminate this part:
var json = JSON.stringify(data); // Remove this.
And in the server side:
$data = json_decode($post, true); // Remove this
$data = $_POST['data']; // Change this
Update
OP said data[elementID]:gh is sent to the PHP file.
If this is the case, then if the data needs to be "gh" in JSON, then:
$res = $_POST["elementID"];
die(json_encode(array("response" => $res)));
This will send:
{
"response": "gh"
}
And in the client side, you don't need anything other than this:
$.post('php/validator_signup.php', function (data) {
var parsedResponse = JSON.parse(data);
console.log(data);
});
JSON data is sent to the server as a raw http input it is not associated with query name like $_POST['data'] or anything like that which means you must access the input string not a data post value to do so you need to use
$rawInput = json_decode(file_get_contents('php://input'), true);
$elementValue = $rawInput['elementId'];
thats it
$_POST = json_decode(file_get_contents('php://input'), true);
$data = $_POST['data'];

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
}
});

why i am getting object object result from my ajax to 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.

Categories