JSON jQuery PHP - php

I don't understand one thing. If I want to get JSON data (key-value-pairs) from PHP to jQuery using Ajax, which of the following ones should I use?
$.get
$.post
$.getJSON
Do I need to use getJSON if I want to use json_encode in a PHP file? But what if I want to send with post (there is no postJSON)?
And one more thing:
In a PHP file I wrote:
<?php
if($_GET['value'] == "value")
{
$array['firstname'] = 'Johnny';
$jsonstring=json_encode($array);
return $jsonstring;
}
?>
In the jQuery file:
$.getJSON("php.php", {value: "value"}, function(data){
alert(data.firstname);
});
Why doesn't this work?

The problem lies with the line in PHP:
return $jsonstring;
You should echo it instead:
echo $jsonstring;
As for which jQuery method to use, I suggest $.getJSON() if you can return a pure json string. It really depends on how you use it.
When using $.getJSON(), your server file should return a JSON string. Thus echoing the string returned by json_encode() would be appropriate for the $.getJSON() method to take in the response.

You can use .ajax, this allows you to do both get and post.

I always use $.ajax.
$.ajax({
url: "script.php",
type: "POST",
data: { name : "John Doe" },
dataType: 'json',
success: function(msg){
alert(msg);
}
});
in PHP:
$name = $_POST['name']
echo $name
this will alert "John Doe"
also, if it's not working, use firebug to see values being passed around.

Related

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/

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

Cant Post JSON Object using Jquery.post()

I have the following object that gets created in my javascript application.
poll_data[active_question] = {
'question': $('div.question_wrap textarea').attr('value'),
'answers': [
$('div.answer_wrap input#0').attr('value'),
$('div.answer_wrap input#1').attr('value'),
$('div.answer_wrap input#2').attr('value'),
$('div.answer_wrap input#3').attr('value'),
$('div.answer_wrap input#4').attr('value'),
$('div.answer_wrap input#5').attr('value')
]
};
active_question is set to 'poll', 0, 1, 2, 3, 4, or 5 depending on the question being worked on at the moment. I am trying to post this object to a php script using the following JS code.
$.ajax({
url: '/somewebsite/poll/create?json=show',
type: 'POST',
// dataType: 'json',
data: poll_data,
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data);
}
});
My PHP code is very simple.
echo json_encode($_POST); exit;
When I run the script and click the button that triggers the submission of the data, I receive the alert (so the actual ajax code works), but the result from my PHP script is just an empty array. I think that this is an issue with the way the object is constructed, but I am not sure, and have not been able to find a work around.
Thanks in advance.
Okay, a few things:
poll_data is not a valid JSON object. You would have to use poll_data[active_question], which IS a valid JSON object. jQuery should serialize this correctly. Remove the contentType -- I am pretty sure that is for php (not positive) but your code wouldn't work for me until I removed it. Finally, the appending of json=show to the query string doesn't do anything..it will just be ignored.
A couple minor things too: you can use .val() instead of .attr('value'), and have you looked into .serialize() to create your post data for you?
do this on server
$data;
$data->question=$_POST['question']
$data->answer=$_POST['answers']
echo json_encode($data);
do this for ajax request
$.ajax({
url: '/somewebsite/poll/create?json=show',
type:'POST',
//modified data proprty
data:poll_data[active_question],
success: function(data) {
alert(data);
}
});

How to collect jquery.ajax() data in PHP?

I send data from javascript to PHP like this:
$.ajax({'url': 'my.php',
'type': 'POST',
'data': JSON.stringify(update_data),
'success': function(response) {
alert(response);
}
});
Using HTTPFOX Firefox plug-in I see the following data in the POST DATA tab:
{"file_id":["1","2","3"],"description":["lala","kuku","wow!"],"tags":[["julia","paper"],["Very nice car"],[]]}
however, if I do in my.php print_r($_POST) I see an empty array. Why is that ? How could I collect the data ?
The data needs to be in the form name=value.
try...
$.ajax({'url': 'my.php',
'type': 'POST',
'data': 'mydata=' + JSON.stringify(update_data),
'success': function(response) {
alert(response);
}
});
Then you should have your json string in $_POST['mydata']
You'll then need to use json_decode to actually get at the individual values in your string.
http://php.net/manual/en/function.json-decode.php
The response you are getting is in JSON format. Use the json_decode function to convert it to array.
print_r(json_decode($_POST['description'], true));
I'd expect your data to be in $HTTP_RAW_POST_DATA. Then json_decode to make sense of it.

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