ajax / json output must be an other format - php

Hi for an jquery map I get the values over ajax. The format for the map must be
var new_sample_data = {"af":"16.63","al":"11.58","dz":"158.97",...};.
I have tested it with var new_sample_data = {"af":16.63,...}; and all works good. But If I take it over jason. It doesn't work. What I must change?
The php testcode:
$sample_data[] = array("de","$de");
echo json_encode($sample_data);
The javascript code:
$.ajax({
type: "POST",
url: '../mail/assets/includes/geodata1.php',
data: {datum1: Date.today().add({days: -29}).toString('yyyy-MM-dd'), datum2: Date.today().toString('yyyy-MM-dd')},
dataType: 'json',
success: function(data)
{
var new_sample_data = data;
In Firebug I see the response is [["de","4"]]. But how I can change it to the format the map need?

You need to create an associative array in PHP:
$sample_data = array("de"=>"$de");
Then encoding it should result in a proper JSON String that can be parsed into a JavaScript Object.
To see the proper content of new_sample_data in JavaScript, use console.dir(new_sample_data);, it will list the object's attributes.
You can access the value of your new attribute this way in JavaScript:
console.log(new_sample_data.de);

Your php array should set the index of de to the variable like such:
$sample_data[] = array("de" => "$de");
That wasy $sample_data["de"] will = "$de";

$sample_data['de'] = $de;
it will work as you expected

Related

how to receive ajax response as array in php [duplicate]

I'm working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One array for each row, containing elements such as id, title, etc). I then want to use json_encode() to encode this array, and pass it back to the javascript which will use it to display the records.
1) How can I return the JSON encoded string to the javascript?
2) How will the javascript loop through the rows and access their fields?
To get JSON with jQuery, just use jQuery.getJSON(). Alternatively, you can use any other AJAX tool and then just eval() the json to get a javascript object.
To loop through an array, I usually use jQuery.each():
var recordList = yourMethodToGetRecordListWithAjax();
jQuery.each(recordList, function()
{
alert(this.Name); // For example
});
1) in the php script:
$return["foo"] = "bar";
$return["blah"] = "bleg";
print json_encode($return);
2) in the javascript:
$.ajax({
type: "POST",
url: URL,
cache: false,
data: values,
dataType: 'json',
success: function(json) {
var foo = json.foo;
if (json.blah == "bleg") {
// do stuff
}
} // end success function
}); // end ajax call
You can return the JSON encoded string to the JS by echoing it with a Content-Type of application/json.
See above answer for the rest.

PHP array to JavaScript using jQuery AJAX

I want to manipulate a PHParray in javascript. This is the code i'm using.
Array.php
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
?>
fx_funciones.js
/*Pre-sentences*/
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
}
});
This is what I want to do but it's not working.
I think , the answer for above question is already addressed in below link. please check them out.
Get data from php array - AJAX - jQuery
I hope it will help you
Try this:
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
echo json_encode($sentido);
And:
$.getJSON('array.php', function(sentido) {
console.log(sentido);
});
You'll need to return the array from your PHP code as JSON, using the json_encode function. Then, in your jQuery code, specify a json dataType so that it's implicitly converted and passed to the callback function as an array:
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
},
dataType: 'json'
});
Use the standard JSON notation. It serializes objects and arrays. Then print it, fetch it on the client and parse it.
On the server:
echo json_encode($sentido);
For more on PHP's json_encode: http://php.net/manual/de/function.json-encode.php
On the client, this is specially easy if you use the jQuery function for ajax that expect JSON-encoded objects, and parses them for you:
$.getJSON('address/to/your/php/file.php', function(sentidos) {
alert(sentidos[0]); // It will alert "ver"
alert(sentidos[1]); // It will alert "tocar"
});
It uses GET but this most probably what you need.
For more on jQuery's $.getJSON: http://api.jquery.com/jQuery.getJSON/

Pass json decode variable to php

I have a JQuery login request as follow using Json encode / decode:
$('#btn_signin').click(function(){
var parameters = $('#signin_form').serialize();
$.ajax({
url: baseurl + 'site/loginRequest',
type: 'POST',
data: parameters,
dataType: 'json',
success: function(output_str){
if(output_str.usertype == "a"){
var sess_email = output_str.email;
window.location.replace(baseurl + 'site/page_a');
}else if(output_str.usertype == "b"){
var sess_email = output_str.email;
window.location.replace(baseurl + 'site/page_b');
}else{
$('#result_msg').html(output_str);
}
}
});
});
As seen on the script with var sess_email how can I pass it to php variable?
Any advise? thanks.
I'm not sure whether I understand this right, but if you want to assign the value of a PHP variable to a Javascript variable you could do something like this:
var sess_email = <?php echo $someVar ?>;
If your looking for the other way around, passing a var from Javascript to PHP, then this is the way to go:
Send it to the server using an AJAX request (I usually JSON encode it then).
JSON decode it on the server and assign it to a PHP variable
Example:
In your case you sended the javascript variable 'parameters' to the server. Then server side you would do this in PHP:
$parameters = $_POST['parameters'];
You can't pass javascript variable to PHP variable. But some workarounds available.
What you are trying to do exactly?

Print array from PHP in the jQuery

How can print date and age (in following array) separate by $.ajax()?
php:
$array = array(
'date' => 2011/9/14,
'age' => 48,
);
return $array // this send for ajax call in the jQuery
I want this output by jquery:2011/9/14 & 48
Use $.ajax Methods and setting parameter dataType to JSON for receive data type JSON from PHP file.
Jquery Code:
$.ajax({
url: "getdata.php",
type: "post",
dataType: "json",
success: function(data){
alert("Date:" + data.date + "\n" + "Age:" + data.age);
}
});
if your array data contains string make sure it's closured with quote then make data type JSON with json_encode() function.
PHP Code (getdata.php):
$array= array('date'=>'2011/9/14','age'=>48);
echo json_encode($array);
Echo the encoded array in php page say mypage.php
using
echo json_encode($array);
And use jQuery.getJson in the client side
$.getJSON('mypage.php', function(data) {
alert(data['date']);
alert(data['age']);
});
You need to encode the array as a valid JSON string using the PHP function json_encode. You can then use the jQuery function $.parseJSON to convert it into a JavaScript object. From there you'll be able to do whatever you want with it.
If you do this, you'll end up with an object like:
ajaxDataObj = {
date: '2011/9/14',
age: 48
}
**Edit**
Please see stratton's comment below about using $.getJSON for a more compact solution.
Also, Ben Everard's comment on your original post about using echo rather than return is critical.
You can't just return $array to the browser, the result will be "Array" as string.
YOu have to use return json_encode($array); which returns a string that could be parsed by browser.
If the server-client communication is working alright, then you should do something like this on the client side:
$.ajax({
//configuration...
'success':function(response){
var dateAge = response.date+' & '+response.age;
//put or append the string somewhere.
}
});

How to use JSON with Jquery?

I'm working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One array for each row, containing elements such as id, title, etc). I then want to use json_encode() to encode this array, and pass it back to the javascript which will use it to display the records.
1) How can I return the JSON encoded string to the javascript?
2) How will the javascript loop through the rows and access their fields?
To get JSON with jQuery, just use jQuery.getJSON(). Alternatively, you can use any other AJAX tool and then just eval() the json to get a javascript object.
To loop through an array, I usually use jQuery.each():
var recordList = yourMethodToGetRecordListWithAjax();
jQuery.each(recordList, function()
{
alert(this.Name); // For example
});
1) in the php script:
$return["foo"] = "bar";
$return["blah"] = "bleg";
print json_encode($return);
2) in the javascript:
$.ajax({
type: "POST",
url: URL,
cache: false,
data: values,
dataType: 'json',
success: function(json) {
var foo = json.foo;
if (json.blah == "bleg") {
// do stuff
}
} // end success function
}); // end ajax call
You can return the JSON encoded string to the JS by echoing it with a Content-Type of application/json.
See above answer for the rest.

Categories