I would like to send array to the server.
This is how i try to send the array:
jQuery(document).ready(function($){
$.ajax({
type: "POST",
url: "file.php",
datatype : "json",
data : JSON.stringify({ name: "Daniel", phone: "01234123456" }),
success: function(msg){
alert('Success!');
}
});
});
This is how i try to get the array in file.php
print_r($_POST);
print_r($_GET);
print_r(json_decode($_POST);
Of course in the firebug console i see the array but not on the page.
You are currently sending the data - what you refer to as the 'array' in the format of JSON - java script object notation.
It is not possible to send data across (at least in jQuery ajax) in JSON. You must stringify it before you send it, and then decode it in the php end (like you already do - got that part right). You would have to do something like:
data: JSON.stringify({ name: "Daniel", phone: "01234123456" }),
Hope this helps!
Related
This is a weird one, although it should be very simple.
The code:
var recipients = [];
recipients.push(uuid1);
recipients.push(uuid2);
$.ajax({
url: '/api-url/',
type: 'POST',
data: {'recipient': recipients, 'message': message, 'subject': subject},
dataType: 'json'
}) ...
This is caught in the Chrome Network inspector:
recipient[]:8b99fa41-0f8f-4882-b14f-dc258a765b15
recipient[]:add61999-9baa-4096-a92f-fbb144a4a981
subject:test
message:testtest
This arrives to the server:
{u'recipient[]': [u'8b99fa41-0f8f-4882-b14f-dc258a765b15', u'add61999-9baa-4096-a92f-fbb144a4a981'], u'message': [u'testtest'], u'subject': [u'test']}
As you can see, we have a 'recipient' in the ajax call, two instances of 'recipient[]' in network inspector and one 'recipient[]' on the server with correct data, but wrong param name.
Any ideas how is that '[]' in 'recipient[]' getting there?
This is what JQuery does to your data object:
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
To send it as JSON you need to convert it to JSON string:
...
type: 'POST',
data: JSON.stringify({'recipient': recipients, 'message': message, 'subject': subject}),
I try to send list of object like [{"name":"Vasya"},{"name":"Lila"}]
It's my code:
$.ajax({
url: url
, type: 'POST'
, contentType: 'application/json'
, data: data
, success: function(response) {
showPopup(response.successMessage);
}
});
Where alert(JSON.stringify(data)); shows: [{"name":"Vasya"},{"name":"Lila"}]
But when I am checking my request in chrome debug mode the request contains undefined= instead correct data.
What I do wrong? Is this syntax incorrect according to JSON?
You need to stringify the object when sending it so that you send JSON.
, data: JSON.stringify(data)
Solved. The solution is to set contentType to 'application/json' and use the JSON.stringify(obj) instead of obj, but you may then have to change how you get the data on your server, depending on the language or framework. Original question below...
Here's what I'm trying
var obj = {
'firstName': 'bill',
'lastName': 'johnson',
'hobbies': ['apples', 'dogs']
});
$.ajax({
type: 'POST',
url: '/myurl'
data: obj,
success: function(data){alert(data);}
});
If I alert/log a JSON.stringify(obj), I get the correct result, i.e.:
{'firstName': 'bill', 'lastName': 'johnson', 'hobbies': ['apples', 'dogs']}
However, when I do the above ajax call, my server gets the following:
{'firstName': 'bill', 'lastName': 'johnson', 'hobbies[]': 'apples'}
Which clearly is not proper json. I've tried adding various contentType arguments but then my server actually gets nothing (an empty post request).
I also tried setting the data argument to a pre-stringified string of JSON (which is correct), but then jquery escapes it and my server gets this:
{"{\"firstName\":\"bill\",\"lastName\":\"johnson\",\"hobbies\":[\"apples\",\"dogs\"]}": ""}
I tried setting processData to false and that changes nothing.
I've researched this for hours and haven't gotten it to work. Surely there's a way to send json with lists to the server...
any tips?
From your post that looks correct to me, I am somewhat new to JSON myself but it looks like its treating the last key-value pair as an array, to access the individual elements you would have to use the correct index to access the value. from json.org JSON is built on two structures:
•A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
•An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
you could check it on jsonlint.com if you still think something is wrong.
Try this
$.ajax({
url: url,
type: 'POST',
datatype: "json",
traditional: true,
data: {
menuItems: JSON.stringify(myArray),
},
success: function () { window.alert('success'); },
error: function (event, request, settings) {
window.alert('error'); },
timeout: 20000
});
Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.
I have a mobile application and I have a lot of data that I am putting in to a JSON object to store in localStorage. I need to get this data to PHP to process it. I have chosen to use jQuery.ajax to send the data as a JSON object to PHP. However, when I run the function, it gives a success message, but does not go to the url specified. I have a lot of PHP experience but this is my first JS intensive project.
Here is my JS code:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
ATRdataJSON is a JSON object that has several JSON objects nested inside.
The URL may not be pointing where you think it's pointing. Try:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "/email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
i'm afraid you cannot send the json object without stringifying it, it may be sent but as a string [object] try to check it first then you may make sure of the url is absolute to make sure it goes to the right controller.