I am starting to use the jquery $.ajax() but I can’t get back what I want to…I send this:
$(function() {
$.ajax({
url: "graph_data.php",
type: "POST",
data: "casi=56&nada=48&nuevo=98&perfecto=100&vales=50&apenas=70&yeah=60",
dataType: "json",
error: function(xhr, desc, exceptionobj) {
document.writeln("El error de XMLHTTPRequest dice: " + xhr.responseText);
},
success: function(json) {
if (json.error) {
alert(json.error);
return;
}
var output = "";
for (p in json) {
output += p + " : " + json[p] + "\n";
}
document.writeln("Results: \n\n" + output);
}
});
});
and my php is:
<?php
$data = $_POST['data'];
function array2json($data){
$json = $data;
return json_encode($json);
}
?>
and when I execute this I come out with:
Results:
just like that I used to have in the php a echo array2json statement but it just gave back gibberish…I really don’t know what am I doing wrong and I’ve googled for about 3 hours just getting basically the same stuff. Also I don’t know how to pass parameters to the “data:” in the $.ajax function in another way like getting info from the web page, can anyone please help me?
Edit
I did what you suggested and it prints the data now thank you very much =) however, I was wondering, how can I send the data to the “data:” part in jQuery so it takes it from let’s say user input, also I was checking the php documentation and it says I’m allowed to write something like:
json_encode($a,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP)
however, if I do that I get an error saying that json_encode accepts 1 parameter and I’m giving 2…any idea why? I’m using php 5.2
First: the data you are passing to the PHP script will be in
$_POST, not in$_POST['data'].Next: you need to actually call the
array2jsonfunction with some data… Is that the full code sample?Also, I’m not sure what
array2jsonis supposed to do… why not calljson_encodedirectly?For your example you can simply make your PHP file look like this:
Finally, you should get a tool like Firebug to easily debug your AJAX calls.
EDIT:
In order to send data from the user, all you have to do is have a form anywhere in your page, then catch the submit event of it and serialize the data, or simply get the value of an individual input field. Then you can just construct your data query with it, as a string or an object. There is also the very popular Form plugin for jQuery that makes it all easier.
The reason you are getting an error is because the 2nd argument of
json_encodewas not added until PHP 5.3.0. So if you have anything earlier than that it’s not available to you.