Parsing JSON in PHP
My variable jsonvar is in the form of {"rating":"good"}
Once I push it through with this $.ajax code to submit, I'm a bit confused at what my PHP (jsonproc.php) should look like.
$.ajax({
url: 'jsonproc.php',
data: {js:jsonvar},
dataType: 'json',
type: 'post',
success: function (j) {
if (j.ok){
alert(j.msg);
} else {
alert(j.msg);
}
}
});
I have it set up as
$decoded = $_GET['js'];
$response = array(
'ok' => true,
'msg' => $decoded['rating']);
However when I echo it back,
echo json_encode($response);
using alert(j.msg) shows a "null" value.
Assuming that I am passing JSON in correctly, how can I point to the rating and get the value of "good"?
Thanks
EDIT
SOLVED, USING $_REQUEST I was able to get the JSON, however $_GET did not work.
Also, the key was using $decoded->{'rating'} as $decoded is no longer just an array i don't think or rather it's a diff type of one?
It looks like you're mixing data types here:
data: "js="+jsonvar,
jQuery will convert JSON if you pass an object, but you're mixing query string with JSON.
Try:
data: {js: jsonvar},
You may also need to do json_decode($_GET['js']).
edit: You can double check what jQuery is POSTing with Firebug/Web Inspector. Easiest way to know for sure.
Try adding this to the top of your PHP file:
header('Content-type: application/json');
Related
I'm pretty unfamiliar with JSON, as I haven't used it too much and I'm trying to learn some of it.
So I have an ajax request that gives me this: [{"palvelu_id":"1","palvelu_nimi":"Meikkikoulutus","palvelu_kuvaus":"Kuvaus","palvelu_hinta":"10"}]
And I'm trying to use jQuery.parseJSON to use it on a page.
var palveluData = $.parseJSON(d);
$("#ajanvarausInfo").html(palveluData.palvelu_kuvaus+"<br>"+palveluData.palvelu_hinta);
But I get undefined as answer, what am I doing wrong here?
You should get the first element of the array:
$("#ajanvarausInfo").html(palveluData[0].palvelu_kuvaus+"<br>...");
If the array has more than 1 element you should iterate through the array, you can use jQuery $.each() utility function.
EDIT::
Wow, looks like ive kept the window open for to long before replying -.-
You have an outter array there, so you need to take that into account ( your php side might be not correct )
$("#ajanvarausInfo").html(palveluData[0].palvelu_kuvaus+"<br>"+palveluData[0].palvelu_hinta);
Usually you not need that when properly setting everything up
$.ajax ({
url: 'myurl',
type: 'POST',
data: { key_value pairs here },
dataType: 'json',
success: function(response){
$("#ajanvarausInfo").html(response.palvelu_kuvaus+"<br>"+response.palvelu_hinta);
});
});
On the php side
$response = array(
"palvelu_id" => "1",
"palvelu_nimi" => "Meikkikoulutus",
"palvelu_kuvaus" => "Kuvaus",
"palvelu_hinta" => "10"
);
echo json_encode($response);
I have the below code running to send data as a JSON object
var jdata = JSON.stringify(grid.serialize());
$.ajax({
'type': 'POST',
'url': 'print.php',
'data': jdata, //assuming you have the JSON library linked.
'contentType': "application/json",
'success': function (data) {
alert(data);
},
'error': function (x, y, z) {
alert(x.responseText);
// x.responseText should have what's wrong
}
});
alert(JSON.stringify(grid.serialize()));
Currenty the alert after the ajax function prints
[{"id":"1","col":"1","row":"1","size_y":"1","size_x":"1"},{"id":"2","col":"2","row":"1","size_y":"1","size_x":"1"}]
On the receiving page I am using <?php print_r($_POST) ?> to see what the page is being sent and it keeps outputting
Array
(
)
I must be missing something simple but have been unable to figure out what. Maybe a fresh set of eyes will see a simple mistake I have made.
I think $_POST is only populated if you send the data encoded as x-www-form-urlencoded. So, just assign the JSON string to a key (jQuery takes care of encoding it properly):
'data': {data: jdata}
and remove the 'contentType': "application/json" part.
Then you get the data in PHP with:
$data = json_decode($_POST['data'], true);
Alternatively, get the raw body of the request in PHP and process it: How to retrieve Request Payload
If you are sending JSON to the server, on the back-end grab your JSON using:
json_decode(file_get_contents('php://input'));
It won't be in the $_POST super global.
I want to compare two values (both are simple strings) on ajax success. Value1 is echo from php, value2 is javascript variable. But when I try something like:
$.ajax({
type: "POST",
url: proccessPage,
data: dataString,
dataType: "text",
success:function(result){
alert (result);
}
});
I will get message "[object Object]". When i try change alert (result); for
var response = $(result);
document.getElementById("div1").innerHTML = result;
then div with id "div1" has proper value. I know I can make the div hidden and use value from it, but is there some way to work with result directly? Or somehow convert result to string? Code in php:
if (isset($_POST['submit']) && $_POST['submit']=="true")
echo "string";
Thanks.
In your script, change the datatype to html.
dataType: "text",
to
dataType: "html",
The dataType of text is perfectly ok. Make certain that your PHP script is setting the mime type for the return to text/plain.
PHP Code:
header('Content-type: text/plain');
jQuery will process the return according to what the server says it is. The dataType field is only a hint. http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
If all else fails use something like Firefox with Firebug. It will give you the ability to place a break pint within your success closure and then you may inspect the value of your result variable.
I am having success by creating a json response from the PHP function, and loading it with whatever I need. Comparing known values from the Json Object handles your [object Object] return issue by giving you known object properties- declared with JSON:
$response = json_encode( array( 'success' => true , 'value1' => $my_result,);
header( "Content-Type: application/json" );
echo $response;
exit;
I use the success bool to ensure that $my_result is a successful response, because AJAX may execute properly, but this allows me to specifically check valid value1
Now, back in your $.ajax:
...
success: function(result){
if(result['success']) {
document.getElementById("removeme").innerHTML = (result['value1'] == value2)? value1 : "Uh-oh. Something went wrong!";
}
}
...
Or you can put whatever is appropriate in your success function body, whatever you need to compare or do. I just gave 1 example to show a complete implementation.
The first A in AJAX means asynchronous, this means that your request will be executed as normal but the callback only gets executed when the requests gets a response. the script doesn't pause waiting for the response.
with that said, if you want to use information from an AJAX request you must use it in its callback, or it will not be available.
something like this:
$.ajax({
type: "POST",
url: proccessPage,
data: dataString,
dataType: "text",
success:function(result){
document.getElementById("removeme").innerHTML = result;
}
});
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.
}
});
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.