post json array via jquery.post? - php

After a series of attempts working on json, now I have another challenge - How can post this type of json array,
[{"success":true,"filename":"agard.jpg"}]
jquery.post,
$.post("process.php", json ,function(xml){
});
So I can get this array in process.php using print_r($_POST):
Array
(
[success] => true
[filename] => agard.jpg
)

You need to pass an object not an array, you can put the array in your object though.
{"0":[{"success":true,"filename":"agard.jpg"}]}

Related

How to access stdClass Multi level object or array?

I had to make a particularly complex SOAP request in PHP and seem to have received back objects within objects. I need to get a particular value for example "session_token". I can var_dump the request and even turn it in to an array but I can't access individual elements. Please help!
Objects:
stdClass Object ( [login_response] => stdClass Object
( [response_context] => stdClass Object
( [session_token] => b1043dcb82625701188ffff03572
[response_status] => OK [response_message] => Login successful
))))
Converted array:
Array ( [0] =>
Array ( [response_context] =>
Array ( [session_token] => b1043dcb82625701188ffff03572
[response_status] => OK [response_message] => Login successful
) ) )
Once it's an array, it's JUST an array, e.g.
$obj->foo->bar->baz
will simply be
$arr['foo']['bar']['baz']
So in your case
$arr[0]['response_context']['response_status'] -> "OK"
If you leave it as an object, and there is not reason not to.
echo $obj->login_response->response_context->session_token;
echo $obj->login_response->response_context->response_status;
echo $obj->login_response->response_context->response_message;
will output
b1043dcb82625701188ffff03572
OK
Login successful
Normally to access any key of an object, need to call it like this
echo $obj->key;
But, as this is a multi-level object, to access the element, you have to code like bellow.
echo $obj->login_response->response_context->session_token;
And the result will be b1043dcb82625701188ffff03572
As same, normally to access any key of an array, need to call it like this
echo $arr['key'];
But, as this is a multi-level array, to access the element, you have to code like bellow.
echo $arr[0]['response_context']['session_token'];
And the Output is b1043dcb82625701188ffff03572
Here,
0 is the key of $arr array.
response_context is the key of 0.
session_token is the key of response_context.
You can use this service, array visualizer, this will help you target and extract only what you need. Just past the print_r output in it. That's it.
Give it a try

cakephp read get variable

I am parsing a value from a HTML element in cakephp and is being sent via Ajax to the following url;
getquestion.json?data[Job][qs1]=2
Now I am trying to access data[Job][qs1] in the controller but can't figure it out.
The returned array is;
Array ( [data] => Array ( [Job] => Array ( [qs1] => 2 ) ) )
$_GET['data[Job][qs1]']; is not working which is rather odd.
You are nesting data in your $_GET parameters. To access nested array, just try with:
$_GET['data']['Job']['qs1']

Print json decoded array

I'm trying to print a value from a object array, but I'm facing some problems. I want to echo in php the value of [title] but i am not getting it!
stdClass Object (
[result] => success
[records] => stdClass Object (
[500272328] => stdClass Object (
[nif] => 500272328
[pc4] => 2775
[pc3] => 372
[seo_url] => solnave-restaurantes-e-alimentacao-s-a
[title] => Solnave - Restaurantes e Alimentação S.a
[city] => Cascais
[racius] => http://www.racius.com/solnave-restaurantes-e-alimentacao-s-a/
[portugalio] => http://www.portugalio.com/solnave-restaurantes-e-alimentacao-sa-2/
)
)
)
How can i retrieve?
Thank you!
I am assuming you are calling json_decode to decode the JSON string.
You should call it as json_decode($thestring_to_be_decoded, true). This will convert the objects to associative arrays and you will be able to access the title field.
Your stdClass is a PHP object or a Javascript encoded object?
It seems a PHP, so to echo title element you must navigate at there:
echo $yourobjarray->records->500272328->title;
or
echo $yourobjarray->records->500272328['title'];
(not evident in your question)
But to echo into <script> section of a HTML page,
<script> ...
var x='<?= $yourobjarray->records->500272328['title'];?>';
...</script>
and, if a AJAX context, to JSON response you need
echo json_encode($x);
where $x is your array or the title string, or what you want.
You can make use of a foreach construct to loop through your JSON decoded object array or If you want to print individual elements you can simply do like this.
echo $yourobjarray->result; //"prints" success

How to pass the array value in jquery code?

Array
(
[0] => Array
(
[price_id] => 1
[website_id] => 0
[all_groups] => 1
[cust_group] => 32000
[price_qty] => 2
[price] => 90.0000
)
[1] => Array
(
[price_id] => 2
[website_id] => 0
[all_groups] => 1
[cust_group] => 32000
[price_qty] => 5
[price] => 80.0000
)
.......
)
the array element maybe one or two or more, if i want to pass [price_qty] and [price] value to the jquery code. how should i do? could someone make me an example. thank you
you should consider using JSON strings in order to use key based arrays in JavaScript.
http://php.net/json
json_encode your php arrays to json
Use json_encode to convert your php array to json :)
A possible solution is to convert php array structures into JSON before passing the data to the client.
Have a look at php json.
And also have a look at this post.
Try with Json:
json_encode($array);
This will encode the array into a json object, that is friendly with javascript (and Jquery).
If you are passing it through an ajax request just echo it in the php and return that as response.
If it's in the same script you could do:
$object = json_encode($array);
echo "var myObject = $object;";
And for accessing the information in javascript/jquery you would do:
alert(myObject[0].price_id);
you use myObject[0] to access positions as in php arrays, and myObject[0].name to access what would be associative array key in an array.
For more information visit json documentation page
Well while you ask to move from [php]array to [javascript]array, this is how to. You should ue json_encode how the previous answer said, but in you javascript you can use the following code to convert a json into an array:
function json2Array = function(json){
var a = [];
for(var o in json){
a.push(json[o]);
}
return a;
}
var myArray = json2Array(youPhpJsonEncode);
and you will have your array in javascript

Passing Multidimensional JSON Array to jQuery Function

I have a PHP array that I want to pass to the jQuery function that called it. However when I tried to retrieve the value of 'lat' the way i did below, I get the error Cannot read property 'lat' of null, obviously because I dont know how to access a multidimensional JSON array. Can anyone show me how?
PHP Array
Array
(
[0] => Array
(
[price] => 1600
[bedroom] => 1
[lat] => -71.119385
[lng] => 42.373917
[distance] => 6.65195429565453
)
[1] => Array
(
[price] => 1800
[bedroom] => 1
[lat] => -71.104248
[lng] => 42.368172
[distance] => 4.957829810472103
)
}
This gets encoded into
JSON
[{"price":"1600","bedroom":"1","lat":"-71.119385","lng":"42.373917","distance":"6.65195429565453"},{"price":"1800","bedroom":"1","lat":"-71.104248","lng":"42.368172","distance":"4.957829810472103"}]
jQuery
$(function() {
$("#search_button").click(function(e){
e.preventDefault();
var search_location = $("#search_location").val();
$.getJSON('index.php/main/get_places', {search_location: search_location}, function(json){
$("#result").html(json.lat);
console.log(json.lat);
});
});
});
json is an array, so it won't have the property lat.
Try:
json[0].lat
To get the first object's lat property, for example.
$.getJSON('index.php/main/get_places', {search_location: search_location}, function(json){
$.each(json, function(key, val) {
console.log(val.lat);
});
});
Your json is returning as an array of objects, so you need to reference the scalar first. Change your references to json.lat into json[0].lat.
Then, if you need to you can write a for loop and reference it as json[i].lat, assuming that i is your iterator variable.
json is an array of objects, just as it is in your php code.
So there are two lat values:
json[0].lat // and
json[1].lat
The json variable itself is null, as stated by the error message. All the answers about accessing subindexes of json or iterating over it like an array will fail because of this.
Look at the documentation for jQuery's getJSON and parseJSON. getJSON passes the server's response through parseJSON to convert it to a Javascript object. parseJSON returns null "if you pass in nothing, an empty string, null, or undefined."
I would use your browser's debugger to look at the raw http response from the server, because that is likely the culprit.
http://api.jquery.com/jQuery.getJSON/
http://api.jquery.com/jQuery.parseJSON/

Categories