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"
}
Related
I am completely lost to get some ajax form to work my case scenario I want to use a form to collect its data and post it to MongoDB using an Express App, for some reason I am trying to pass an array of sites to the DB but for some reason it's coming as a string with quotes but it won't accept an array of objects.
My Code:
$("#createClients").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var siteArr = [];
$(".site").each(function(){
var siteUrl = $(this).val();
var siteObj = {
"site": siteUrl
};
siteArr.push(siteObj);// if I use stringify it returns 2 strings with 2 objects
});//building array of sites from inputs
console.log("Sites Array", siteArr);//Here the array looks right and returns all objects from the inteneration
formData.append('sites', siteArr);
// here I am appending it to the response but it returns like ["{"site":"site.com"},{"site":"site.com"}"]
// for some reason its generating quotes for the objects just like a string !!?!?!?
$.ajax({
url: "/clients/create",
type: "POST",
connection: "keep-alive",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function (data) {
console.log(data);
},
error: function (err) {
console.log(err);
}
});
});// posts new Clients
My Mongoose model:
...
sites: [],
...
My problems:
The siteObj is returned from the formData() with quotes if I JSON.stringify the object sites:["{"site":"http://www.site1.com"},{"site":"http://www.site2.co.uk"}"].
If I pass the siteObj as a data type it returns sites:["[object Object],[object Object]"] as string.
What am I doing wrong here?... Thanks for your response in advance!
After doing some deeper research and another 3 days hammering my own head over this nonsense issue I came to a solution:
1. Mongoose validation can be done in 2 ways...
...
sites: [{site: {type: String}}], ... or using a new mongoose Schema
const SiteUrls = mongoose.Schema({
site: {type: String}
});
**then...**
sites: [SiteUrls]
...
2. The Ajax method to transfer FormData with appended Array should look like the example below or you will face a validation error from Mongoose "Cast to Array failed for value"...
$("#createClients").submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
var siteArr = [];
$(".site").each(function() {
var siteUrl = $(this).val();
siteArr.push({'site':siteUrl});
}); //building array of sites from inputs
console.log("Sites Array", JSON.stringify(siteArr));
formData.append('sites', JSON.stringify(siteArr));// SEND the array as string otherwise it will send [object object] as the string... this should build a response like [{"url":"site.com"},{"url":"site2.co.uk"}]... follow clients.js file use JSON.parse(req.body.sites); to turn it into a parsed object like so [{url:"site.com"},{url:"site2.co.uk"}]
$.ajax({
url: "/clients/create",
type: "POST",
connection: "keep-alive",
contentType: false,
cache: false,
processData: false,
data: formData,
success: function (data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
});
}); // posts new Clients
THEN!!!
3. Clients.js Router
...
sites: JSON.parse(req.body.sites), // turn it into a parsable array so data is validated by mongoose and sent to DB
...
🎉🎉
i've this piece of code that performs an AJAX call
$.ajax({
url : 'inviaCommento.php',
type : 'POST',
data : {page: page, category: category}
dataType : 'json',
success : function (msg)
//...and so on
The problem is that i want to check if a search parameter is set, if yes i've to add the word to the data parameters.
The question is: can i costruct the data parameters before the call appendig values to it?
Something like this:
if $('#searchBtn').val()!=''
{
data.append(search: $('#searchBtn').val())
}
Yeah, just create an array.
var data = {something: [], page: page, category: category, somekey: "default"};
data.something.push("a");
data.something.push("b");
if (...) {
data.somekey = "new value";
}
$.ajax({
...
data: data
});
Yup, but data isn't a list, it's an object, so you just assign to the appropriate key.
var data = {page:page}; // ... current value of data: param in the $.ajax call
if($('#searchBtn').val()!=='')
{
data.search= $('#searchBtn').val();
}
You'd put this above the $.ajax() call.
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
}
});
I've 1 object:
var myobject = {first: 1, second: {test: 90}, third: [10, 20]};
and I want to send it as JSON string via jQuery ajax.
How can I do it? (i test JSON.stringify(), but it doesn't work in IE)
Thanks.
If you specify your myobject as the data parameter to the jQuery .ajax() method, it will automatically convert it to a query string, which I believe is what you want.
e.g.
$.ajax({
url: /* ... */,
data: myobject,
/* other settings/callbacks */
})
From the docs:
data
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.
You should be able to pass your object to the 'data' parameter of the ajax function -
$.ajax({
type: "POST",
url: "some.php",
data: myobject ,
success: function(msg){
alert( "Data Saved: " + msg );
}
});