I'm posting form data that includes some checkboxes and other input to a PHP script with jQuery's .serialize().
post.js:
$(function(){
$("#button").click(function(){
$.ajax({
type: "POST",
url: "post.php",
data: $("form#input").serialize(),
success: function(data){
$.getJSON('post.php', function(data) {
$.each(data, function(key, val) {
})
})
}
})
})
})
post.php:
$tags = array();
foreach($_POST['checkboxes'] as $key => $value){
$tags[] = "$value";
}
$json = array(
array(
"tags" => $tags,
),
);
echo json_encode($json);
If I point the getJSON to post.php I get a PHP warning in my error log that says "PHP Warning: Invalid argument supplied for foreach()" and this causes the data from the input form to not be properly passed (i.e. a fwrite after the foreach doesn't write anything). If I reference another file for the getJSON, say data.php, or if I don't include it at all, the post works fine. Why is this happening? I could just store the data and make a second script to return the JSON data but it would be easier to do it all in one script.
Here's the deal:
success: function(data){
In the above piece, the data you are recieving is the returned json_encoded string containing key:value pairs of $tags, as you defined.
$.getJSON('post.php', function(data) {
Now, in your getJSON request you are passing over no values, and your foreach statement expects you to post the values of checkboxes so they can be parsed, and the tags be made. I'm not really sure I understand why you would want to do this, as the success: function(data) will natively parse the JSON being returned from the server and will be ready for you.
$.each(data, function(key, val) {
If you just simply lose the $.getJSON request, and use the each function, you will be iterating over the tags that you return from the server. I believe this is the intended functionality you want.
your code is breaking when checkboxes are not posted
$tags = array();
if( array_key_exists('checkboxes', $_POST) && is_array($_POST['checkboxes']) ) {
$tags = array_values($_POST['checkboxes']);
}
$json = array(
array(
"tags" => $tags,
),
);
echo json_encode($json);
You're getting Invalid argument supplied for foreach because it expects a value in $_POST['checkboxes'] which you're not sending in your $.getJSON call.
$.getJSON sends another AJAX call, a GET request to get a JSON file. You already sent a POST request to post.php, you don't need to send another call.
Add dataType: 'json' to your 1st call, and the JSON response will be parsed for you.
$.ajax({
type: "POST",
url: "post.php",
data: $("form#input").serialize(),
dataType: 'json',
success: function (data) {
$.each(data, function (key, val) {
// code here
});
}
});
you don't have to invoke "getJSON" because you already have what you want. Everything you need is in data. So your "success" callback should look something like this:
function(data){
var jsonData = $.parseJSON(data);
$.each(jsonData, function(key, val) {
})
}
Related
I get this from ajax call
{"id":"381120774951940096","time":"Posted 0 minutes and 51 seconds ago.",....
How can I add each of these into variable, id, time etc? data.id won't work, it says undef.
<script>
$(function() {
$.ajax({
type: "POST",
url: "start.php",
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
})
});
</script>
This is what I return from start.php
$return = array('id' => $info['id_str'] ,'time' => timeDiff(new DateTime($info['created_at'])), 'name' => $info['user']['name'], 'text' => $info['text'], 'image' => $picture, 'url' => "http://twitter.com/{$info['user']['screen_name']}");
print_r(json_encode($return));
EDIT
I had that print_r inside foreach loop and that was the issue. So I added another array and used echo json_decode($array,true) at the end of file.Writing this just in case, might help someone.
Cheers
First, in your PHP, change your line to:
echo json_encode($return, true);
That second parameter ensures that the JSON is interpretable as an associative array. Also, you should use echo instead of print_r when returning JSON; print_r can alter the formatting.
Next, use the following AJAX call:
$.ajax({
type: "POST",
url: "start.php",
dataType: "json", // Add this option.
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
})
The dataType: "json" option ensures that data will be parsed as a JSON object as soon as it's retrieved. So, data.id should be immediately available in your success callback function.
Hope this helps!
Firstly, you should use echo in the server script. print_r is mainly for debugging arrays.
Secondly, you should declare a dataType option for the ajax call:
$.ajax({
dataType: "json", // <-- here
type: "POST",
url: "start.php",
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
});
The way you have it now, I think you are getting a string response as data.
You can verify that with console.log(JSON.stringify(data));
You have to set dataType: 'json' in your ajax. This means that jQuery will parse the result as JSON for you.
Then parse the data,
data = $.parseJSON(data);
Then read var id = data.id;
Also, in your PHP, No need to use print_r(). Just use echo instead print_r().like:
echo json_encode($return);
You'll need to parse the JSON string into an object. You can use JSON.parse to do this.
// Your JSON string
var json_str = "{'id': 'foo', 'time': 'bar'}";
// We need to parse it, converting it into a JS object
var json_obj = JSON.parse(json_str);
// We can now interact with it
console.log(json_obj.id);
console.log(json_obj.time);
Alternatively, you can parse JSON using a built in jQuery function parseJSON().
jQuery also has a built in function for fetching JSON called getJSON(). If memory serves, this is just a shorthand for doing an .ajax() call and specifying a datatype of json. This will handle the above (parsing JSON) for you, and is the recommended solution.
Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}
I'm having trouble getting a response from my php jquery / json / ajax. I keep combining all these different tutorials together but I still can't seem to pull it all together since no one tutorial follow what I'm trying to do.
Right now I'm trying to pass two arrays (since there's no easy way to pass associative arrays) to my jquery ajax function and just alert it out. Here's my code:
PHP
$names = array('john doe', 'jane doe');
$ids = array('123', '223');
$data['names'] = $names;
$data['ids'] = $ids;
echo json_encode($data);
Jquery
function getList(){
$.ajax({
type: "GET",
url: 'test.php',
data: "",
complete: function(data){
var test = jQuery.parseJSON(data);
alert(test.names[0]);
alert("here");
}
},
"json");
}
getList();
In my html file all I'm really calling is my javascript file for debugging purposes. I know i'm returning an object but I'm getting an error with null values in my names section, and i'm not sure why. What am I missing?
My PHP file returns
{"names":["john doe","jane doe"],"ids":["123","223"]}
It seems to be just ending here
Uncaught TypeError: Cannot read property '0' of undefined
so my sub0 is killing me.
You could prob use the $.getJSON facade that jQuery provides, this will setup all the required ajax params for a standard JSON request:
$.getJSON('test.php', function(response) {
alert(response.names[0]); // john doe
});
However i think the route of the issue is that 1) your server may not be returning the correct response codes and/or the correct headers (ie: JSON data) - however the above method at least for the latter should force this conclusion.
See: http://api.jquery.com/jQuery.getJSON
It looks like the problem is that you're using the complete callback instead of the success callback:
function getList(){
$.ajax({
type: "GET",
url: 'test.php',
data: "",
success: function(data) { /* success callback */
var test = jQuery.parseJSON(data);
alert(test.names[0]);
alert("here");
}
},
"json");
}
getList();
From jQuery AJAX Docs:
success(data, textStatus, jqXHR)
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
complete(jqXHR, textStatus)
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
jQuery wants to know what kind of data to expect as a response, otherwise it wont know how to parse it.
So, as has been said before here, you tell jQuery using the dataType = 'json' attribute.
function getList() {
$.ajax({
type: "GET",
url: 'test.php',
data: "",
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
On top of this it is a good idea to have PHP present its content as json rather than html. You use the header for this by setting header('Content-type: application/json'); before any output in your PHP script. So:
$names = array('john doe', 'jane doe');
$ids = array('123', '223');
$data['names'] = $names;
$data['ids'] = $ids;
header('Content-type: application/json');
echo json_encode($data);
You should pass all parameters for ajax() function in single object. So, there should be "dataType" option. Also, if you set data type explicitly, jQuery will parse JSON data for you. Complete callback will receive parsed JavaScript object as parameter.
function getList() {
$.ajax({
type: "GET",
url: 'test.php',
data: "",
dataType: "json",
success: function(test) {
alert(test.names[0]);
alert("here");
}
});
}
I am trying to send simple data to theservre, and I need a "rough and ready" way to do this.
This is what I have so far:
var emails = ['a#123.com', 'b#123.com', 'c#123.com'];
var ruff_json = "{ 'emails': [";
for (i in emails)
ruff_json += ((i == 0) ? '' : ', ') + '\''+emails[i]+'\'';
ruff_json += '] }';
jQuery.ajax({
type: 'POST',
url: '1.php',
data: ruff_json,
dataType: "json",
timeout: 2000,
success: function(result){
//do something
},
error: function (xhr, ajaxOptions, thrownError){
//do something
}
});
Using Firebug, I can see that the data is POSTed to the server - however, at the server, there is no data ($_POST is empty) - what am I doing wrong?
We post all of our data with json.
var myobj = { this: 'that' };
$.ajax({
url: "my.php",
data: JSON.stringify(myobj),
processData: false,
dataType: "json",
success:function(a) { },
error:function() {}
});
then in php we do
<?php
$json = json_decode(file_get_contents("php://input"), true);
// Access your $json['this']
// then when you are done
header("Content-type: application/json");
print json_encode(array(
"passed" => "back"
));
?>
This way we don't even mess with the post variables, and in general, its faster than having jQuery process them.
Your data field should contain an object with key-value pairs, because it gets encoded as POST key-values pairs.
data = {my_json: encoded_string};
Then on the PHP side you can access the data as:
$data = json_decode($_POST['my_json']);
PHP populates $_POST by parsing the data received. However, it only knows form-encoded data, JSON data cannot be parsed automatically. So $_POST will be useless in this case. You need to get the raw post data and parse it with json_decode.
Sorry if this is basic, but I have been dealing with figuring this out all day and have gotten to where I can do everything I need with Jquery and cakephp (not sure if cakephp matters in this or if its same as any PHP), I want to return a variable from a cakephp function to jquery, I had read about how to do it, like here:
the cakephp:
$test[ 'mytest'] = $test;
echo json_encode($test);
and the jquery:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
}
});
I just can't figure out how to get one or more variables back into usable form within jquery, I just want the variable so I can do whatever else with it, I've been looking at what I can find through searching but its not making it fully clear to me.. thanks for any advice.
The JSON variables are in the data variable. In your case, it'll look like this:
var data = {
myTest: "Whatever you wrote here"
};
... so you can read it from data.myTest.
(Not sure whether it's relevant but you can remove the http://localhost/ part from the URL;
AJAX does not allow cross-domain requests anyway.)
Your variables are in data.
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
var values = eval( data ); //if you 100 % trust to your sources.
}
});
Basically data variable contain the json string. To parse it and convert it again to JSON, you have to do following:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
json = $.parseJSON(data);
alert(json.mytest);
}
I haven't test it but it should work this way.
Note that when you specify dataType "json" or use $.getJSON (instead of $.ajax) jQuery will apply $.parseJSON automatically.
So in the "success" callback you do not need to parse the response using parseJSON again:
success: function(data) {
alert(data.mytest);
}
In case of returning a JSON variable back to view files you can use javascript helper:
in your utilities controller:
function ajax_component_call_handler() {
$this->layout = 'ajax';
if( $this->RequestHandler->isAjax()) {
$foobar = array('Foo' => array('Bar'));
$this->set('data', $foobar);
}
}
and in your view/utilities/ajax_component_call_handler.ctp you can use:
if( isset($data) ) {
$javascript->object($data); //converts PHP var to JSON
}
So, when you reach the stage in your function:
success: function(data) {
console.log(data); //it will be a JSON object.
}
In this case you will variable type handling separated from controllers and view logic (what if you'll need something else then JSON)...