I am trying to submit some JSON to my web app and I want the JSON to be like this:
{
"thing1" :
{
"something" : "hello"
},
"list_of_things" :
[
{
"item1" : "hello"
},
{
"item2" : "hello"
}
]
}
Here I have one JSON object and a JSON array that holds JSON objects. When I create the data to submit in Javascript I do:
form = {
"thing1" : {
"something" : somethingVariable
},
"list_of_things" : listArray
}
Here 'listArray' is a Javascript Array object of Javascript hash objects. I submit this using jQuery's ajax method but instead of javascript array displaying as the JSON array desired it converts it to a series of JSON objects like this:
{ "1" : { "thing1" : "something" }, "2" : { "thing2" : "something" }...
How can I get the array to be submitted as an array rather than be converted into a series of JSON objects with the array indexes as keys?
EDIT#1: 'listArray' is a simple Javascript array that is defined like so:
var listArray = new Array();
listArray.push({ "thing1" : "something" });
listArray.push({ "thing2" : "something" });
EDIT#2: 'form' is sent to the server with the following call:
$.ajax({
type: 'POST',
url: '/url',
dataType: "json",
data: form,
success: function(data) {
/* success code here */
}
});
Have a look here. If you are truly trying to post JSON you will need to send the string, not an object literal. You could use JSON.stringify (or a more supported JSON solution) on form.
$.ajax({
url: "/url",,
dataType: "json",
type: "POST",
processData: false,
contentType: "application/json",
data: JSON.stringify(form)
});
Related
I am trying to show my JSON data in the table by using Data table. However, data table keep stuck in the processing like this and I don't know why.
https://jsfiddle.net/Lvmertbp/
JSON format
console.log(data)
Java controller code
#GetMapping(value="/projects")
public #ResponseBody List<Project> getProjects() {
return projectService.findAllProjects2();
}
I know this is the old question, but I have tried everything I can but it just don't work.
Try removing the success function, that seemed to work for me:
success:function(data){
console.log(data);
},
You should also check that your array is in the "data" object, if it's just a flat array you should pass an empty string to dataSrc. Working example: http://jsfiddle.net/5snrvL4m
Your server response is returning an array of result , not an object with data key array ,
So you data table will search in the result for a data array key , but not found , in your case you should specify the param dataSrc as empty , so it'll take it as ana array ,
Check here the doc
$(document).ready(function () {
$('#tableProject').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "/projects",
type: "GET",
contentType: "application/json",
dataSrc: '', // <------------------------ here set empty string
data: function () {
},
success:function(data){
console.log(data);
},
},
paging:true,
columns: [
{data: "projectNumber"},
{data: "name"},
{data: "status"},
{data: "customerName"},
{data: "startDate"},
]
});
});
I'm trying to parse a JSON response with JQuery:
<script>
$(document).ready(function() {
$("button").click(function() {
$.ajax({
url : 'test.php',
type : 'GET',
data : {
name : "Peter",
},
dataType : 'json',
success : function(response) {
console.log(response);
alert(response.name)
},
error : function() {
console.log("error")
}
});
});
});
</script>
I want to get the name into the alert box, but everything I get is an undefined.
This is the result in the console:
Object {results: Array[1]}
results: Array[1]
0: Object
id: "4"
name: "Peter"
When I do alert(JSON.stringify(response)); I get {"results":[{"id":"4","name":"Peter"}]}, so there is definitely valid JSON.
In response there is not property name. name there is in in first element in results array, so to get name you need do
console.log(response.results[0].name)
response is an object which contains an array in results, you need to iterate over ressponse.results or if you're sure it well have only one element, use response.results[0].name
The JSON data contains an array, so you need use an index:
var data = {"results":[{"id":"4","name":"Peter"}]}
document.write(data.results[0].name)
I have a list of variables available to me and I want to send it via $.ajax post. What format would I have to keep these in to use the function .serialize? I keep getting this error:
Object 'blank' has no method 'serialize'
I've tried to make them an array and I've tried jQuery.param(). I have a feeling this is simple but I can't seem to get it. Thanks!
var $data = jQuery.makeArray(attachmentId = attachmentID, action = 'rename', oldName = filename, newName, bucketName, oldFolderName, newFolderName, projectId = PID, businessId = BID);
var serializedData = $data.serializeArray();
//alert(theurl);
$.ajax({ type: "post", url: theurl, data: serializedData, dataType: 'json', success: reCreateTree });
.serialize is for form elements:
Encode a set of form elements as a string for submission.
The $.ajax documentation says for the data option:
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).
So all you need to do is passing an object. For example:
$.ajax({
type: "post",
url: theurl,
data: { // <-- just pass an object
attachmentId: attachmentID,
action: 'rename',
// ...
},
dataType: 'json',
success: reCreateTree
});
It seems you're used to the PHP style of array's (associated arrays). In Javascript, objects are basically the same thing (though can be MUCH more complicated).
So if you are trying to create an array like this in php it would be
$array = array(
"foo" => "bar",
"bar" => "foo",
);
in Javascript using an object instead of an array it would be
var arr = {
foo: "bar",
bar: "foo"
}
I want to send data to a java servlet for processing. The data will have a variable length and be in key/value pairs:
{ A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
The data doesn't need to be formated this way, it is just how I have it now.
var saveData = $.ajax({
type: "POST",
url: "someaction.do?action=saveData",
data: myDataVar.toString(),
dataType: "text",
success: function(resultData){
alert("Save Complete");
}
});
saveData.error(function() { alert("Something went wrong"); });
The $.ajax() function works fine as I do get an alert for "Save Complete". My dilemna is on the servlet. How do I retrieve the data? I tried to use a HashMap like this...
HashMap hm = new HashMap();
hm.putAll(request.getParameterMap());
...but hm turns out to be null which I am guessing means the .getParameterMap() isn't finding the key/value pairs. Where am I going wrong or what am I missing?
You don't want a string, you really want a JS map of key value pairs. E.g., change:
data: myDataVar.toString(),
with:
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: myKeyVals,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.
UPDATE: Code fixed.
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:abc#invalid.ts
you can use ajax post as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:
&A2168=1&A1837=5&A8472=1&A1987=2
On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:
Enumeration keys = request.getParameterNames();
HashMap map = new HashMap();
String key = null;
while(keys.hasMoreElements()){
key = keys.nextElement().toString();
map.put(key, request.getParameter(key));
}
To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.
When I try passing array of array to server it gives(on server log)
1 => [object, object], 2=> [object, object]
using ajax data: data
data on console.log shows:
[Object {name="abc", place="us"}, Object {name="pqr", place="jp"}]
actual array is as follow:
data.push({name: "abc", place: "us"})
data.push({name: "pqr", place: "jp"})
I would like output as (on server):
Person1 = {name="abc", place="us"}
Person2 = {name="pqr", place="jp"}
I tried jQuery.Serialize it does not work and trying to convert it JSON but failed on client side.(giving output [ ])
I am not sure, where I am going wrong. Can I directly send data array to server?
Thanks
Viral
JavaScript arrays and objects are not the same thing. Arrays have elements with numeric indexes, while objects have properties with string key names.
You probably want something like this:
var data = {
Person1 : {name:"abc", place:"us"},
Person2 : {name:"pqr", place:"jp"}
};
This creates an object (data) which has properties "Person1" and "Person2" that are themselves references to objects with "name" and "place" properties.
Or, the equivalent of the array push method to add your properties to the object is to do this:
// create an empty object
var data = {};
// set properties
data["Person1"] = {name:"abc", place:"us"};
data["Person2"] = {name:"pqr", place:"jp"};
// or use dot notation:
data.Person3 = {name:"xyz", place:"au"};
here is an ajax if you like to try, serializing and passing data object as JSON to the server side.
var data = {
Person1 : { name:'abc', place:'us'},
Person2 : { name:'pqr', place:'jp'}
}
$.ajax({
type: 'POST',
url: 'url',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
//success
}
});