sending a 2d array jquery post to java servlet - javascript

I have some data that I need to send that is in a 2D array. I found that you send an array through post here
here but i need to send a 2D array from my javascript using post to a java servlet. Is there a way to do this?

You can use exactly the same technique as the example you link to. This is because it uses JSON to serialise the data, so it can send entire JS data structures in one go. So, taking the example, but rebuilding it for a 2d array and tweaking it to send actual JSON:
var obj=[ [1.1, 1.2], [2.1, 2.2], [3.1, 3.2] ];
$.ajax({
url:"myUrl",
type:"POST",
dataType:'json',
success:function(data){
// codes....
},
data:JSON.stringify(obj),
contentType: 'application/json'
});
Then this will send a string to your server, like:
"[[1.1,1.2],[2.1,2.2],[3.1,3.2]]"
Your Java servlet will then have to deserialise this and use it however you want. In this example, the JSON will be sent as RAW post data; if you want to get it via the request object, you can do something like:
var obj=[ [1.1, 1.2], [2.1, 2.2], [3.1, 3.2] ];
$.ajax({
url:"myUrl",
type:"POST",
dataType:'json',
success:function(data){
// codes....
},
data: {json: JSON.stringify(obj)}
});
Then you should be able to get the JSON string from:
request.getParameterValues("json");

Related

Pushing JSON Data into an array?

I have a PHP script which returns a JSON response like the below
[{"agencyID":"99999", "name":"john", "surname":"doe", "bookings":[{
"ID":"54321", "transactions":[{"desc":"example text"}],
}]
}]
MUST ADD - I HAVE MADE UP THIS JSON - JUST AN EXAMPLE.
How do i push all this information into a JavaScript array from AJAX success block?
I would like to be able to use the information later for example like this -$('#div').append(array.desc);
Content-Type
application/x-www-form-urlencoded; charset=UTF-8
If you are using the jQuery ajax method, you can push the response from your PHP script into an array and use it later. Here's an example:
JavaScript
$.ajax({
url: 'url/to/php/script.php',
dataType: 'JSON',
success: function (data, textStatus, jqXHR) {
var array = [];
array.push(data);
$('#foo').append(array);
}
});

Send an array from Javascript to php

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!

How can I sent an array with $.ajax - dataType: json?

Im currently trying to sent a javascript array to my .php file handler and save it to my database.
The request is successful however it seems my array doesn't get POSTED / saved correctly.
In my POST request source it just turns up as: round_items%5B%5D=1
What am I missing?
id = 5;
var roundChallenges = new Array("item1", "item2", "etc");
//Save the data
var url = path.php;
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: { uid: id, round_items: roundChallenges },
success: function(data)
{....
round_items%5B%5D=1 is correct. That is what it should be sending. That decodes to round_items[]=1, which is how you make arrays in query strings.
When you pass an object to $.ajax, jQuery converts it to a query string, a standard transport format.
In PHP, you don't need json_decode or anything. It will parse it into $_POST for you. $_POST['round_items'] will be an array, and $_POST['uid'] will be your id.

Posting JSON string to PHP page

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.

jQuery.post is not sending data to the specified URL

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.

Categories