jQuery post() with serialize and extra data - javascript

I'm trying to find out if it's possible to post serialize() and other data that's outside the form.
Here's what I thought would work, but it only sends 'wordlist' and not the form data.
$.post("page.php",( $('#myForm').serialize(), { 'wordlist': wordlist }));
Does anyone have any ideas?

You can use serializeArray [docs] and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});
$.post("page.php", data);

Try $.param
$.post("page.php",( $('#myForm').serialize()+'&'+$.param({ 'wordlist': wordlist })));

An alternative solution, in case you are needing to do this on an ajax file upload:
var data = new FormData( $('#form')[0] ).append( 'name' , value );
OR even simpler.
$('form').on('submit',function(e){
e.preventDefault();
var data = new FormData( this ).append('name', value );
// ... your ajax code here ...
return false;
});

When you want to add a javascript object to the form data, you can use the following code
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
if (data.hasOwnProperty(key)) {
postData.push({name:key, value:data[key]});
}
}
$.post(url, postData, function(){});
Or if you add the method serializeObject(), you can do the following
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});

In new version of jquery, could done it via following steps:
get param array via serializeArray()
call push() or similar methods to add additional params to the array,
call $.param(arr) to get serialized string, which could be used as jquery ajax's data param.
Example code:
var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
// ...
}

$.ajax({
type: 'POST',
url: 'test.php',
data:$("#Test-form").serialize(),
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&moreinfo=MoreData';
},
success:function(data){
// json response
},
error: function(data) {
// if error occured
}
});

You can use this
var data = $("#myForm").serialize();
data += '&moreinfo='+JSON.stringify(wordlist);

You could have the form contain the additional data as hidden fields which you would set right before sending the AJAX request to the corresponding values.
Another possibility consists into using this little gem to serialize your form into a javascript object (instead of string) and add the missing data:
var data = $('#myForm').serializeObject();
// now add some additional stuff
data['wordlist'] = wordlist;
$.post('/page.php', data);

I like to keep objects as objects and not do any crazy type-shifting. Here's my way
var post_vars = $('#my-form').serializeArray();
$.ajax({
url: '//site.com/script.php',
method: 'POST',
data: post_vars,
complete: function() {
$.ajax({
url: '//site.com/script2.php',
method: 'POST',
data: post_vars.concat({
name: 'EXTRA_VAR',
value: 'WOW THIS WORKS!'
})
});
}
});
if you can't see from above I used the .concat function and passed in an object with the post variable as 'name' and the value as 'value'!
Hope this helps.

Related

Converting serialized form data into json object using Jquery?

I am trying to get data from my form and then send it to a servlet. But then I notice that the json object that I am getting after serializing my form is not a valid json object. What could I be doing wrong? This is what I tried so far.
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var data = $("#register").serialize().split("&");
var obj={};
for(var key in data)
{
console.log(data[key]);
obj[data[key].split("=")[0]] = data[key].split("=")[1];
}
console.log(obj);
// store json string
$.ajax({
type: "POST",
url: "HomeServlet",
dataType: "text",
contentType: "application/json",
data:{"res":obj},
success: function(data){
console.log(data);
},
error:function(){
console.log("error");
},
});
});
</script>
The json object that i am getting from the form is -
{
apiname: "jdjdj",
apiendpoint: "sdjsdj",
apiversion: "djdjd",
source: "internet"
}
This is what I want -
{
"apiname": "jdjdj",
"apiendpoint": "sdjsdj",
"apiversion": "djdjd",
"source": "internet"
}
There is nothing wrong with the json you Got .
Just stringify it to get the desired object
var myJSON1 = JSON.stringify(data);
this will work
YOu may try it
JSON.stringify(json_data);
As others have noted, your passing a raw javascript object.
What you must do is convert this object prior to sending it over the wire.
JSON.stringify(json_data);
Instead of this foreach loop only use serializeArray() then json_parse() these two functions will work for you.
var data = $("#register").serializeArray();
var obj= JSON_parse(JSON_stringify(data));
please use JSON.stringify(obj, undefined, 2);

Print JSON string from URL

I'm using ajax to parse JSON data from a URL. I need to capture the parsed array into a variable. How would I go about this? Thanks
function rvOffices() {
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
data: JSON.stringify(data),
dataType: 'text',
success: function( data) {
// get string
}
});
}
rvOffices();
var rvOfficesString = // resultant string
You can use JSON.parse(data) to convert the desired output to JSON, and then access the objects and array indexes from within that with .object and [array_index] respectively:
function rvOffices() {
$.ajax({
url: 'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type: 'GET',
dataType: 'text',
success: function(data) {
var json_result = JSON.parse(data);
//console.log(json_result); // The whole JSON
console.log(json_result.offices[0].name);
}
});
}
rvOffices();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You also don't need to pass any data, as you're performing a GET request.
Hope this helps! :)
So I guess you are not sure about the ajax call, so lets break it..
Ajax call is a simply method to make a request to remote resource (Get/post/put...) the type of request (GET/POST) depends upon your need.
so if you have an endpoint that return simply data as in your case a simple get/post request is sufficient.
You can send addition data with request to get the data from endpoint (say id of resource (say person) whose other fields you want to get like name, age, address).
here is link for ajax request in jQuery
here is jQuery parse json parse json in jQuery
So for example:
// let's say when you call this function it will make post request to fixed end point and return data else null
function rvOffices() {
var res = null; // let be default null
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET', // type of request method
dataType: 'text', // type of data you want to send if any.
success: function( data) {
res = $.parseJSON(data); // will do the parsing of data returned if ajax succeeds (assuming your endpoint will return JSON data.)
}
});
return res;
}
// lets call the function
var rvOfficesString = rvOffices();
// print the value returned
console.log(rvOfficesString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can try something like: -
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
dataType: 'text',
success: function(response) {
// get string
window.temp = JSON.parse(response);
}
});

Empty Array AJAX

So I have searched around a bit in hopes of finding a solution to my problem, but have had no luck.
I am basically trying to pass data into the ajax function, but when it passes it to my php file it only returns an empty array (Yes there are a few topics on this, couldn't find any to fit my needs) , here is the console output: Array ()
Its odd because just before the ajax function I log the data, and it prints out each section with no problems.The posting URL is accurate, works fine straight from my form. I have tried to use response instead of data passed through the function, but no luck their either.
Thanks in advance!
Here is the JS file
$(document).ready(function() {
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = [];
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data); /////THIS LINE HERE ACTUALLY PRINTS DATA
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
return false;
});
});
And here is my PHP
<?php //removed the issets and other checkers for ease of readability
print_r($_POST);
?>
UPDATE: I have tried to add method:"POST" to my ajax function and it still seems to be printing out blank arrays... Maybe I should convert everything to GET?
jQuery ajax() uses GET as default method. You need to mention method: POST for POST requests.
method (default: 'GET')
$.ajax({
url: url,
method: "POST",
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
Or you can also use post().
EUREKA!!! Wow, the mistake was much simpler than I thought, figured it out solo! Thank you everyone for the tips! Finally got it
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {}; // THIS NEEDS TO BE CHANGED TO BRACKETS!!

javascript, array of string as JSON

I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.

How to submit a form and pass some extra parameters to a $.getJSON callback method?

I know how to pass some parameters to a JQuery $.getJSON callback method, thanks to this question:
$.getJSON('/website/json',
{
action: "read",
record: "1"
},
function(data) {
// do something
});
And I can also submit a form to a $.getJSON callback method:
$.getJSON('/website/json', $(formName)
function(data) {
// do something
});
But I want to pass some parameters AND submit some form elements. How can I combine the two things togheter?
I could serialize the form elements and manually add some parameters to the url, and it looks like it works:
$.getJSON('/website/json',
'action=read&record=1&'
+ $(formName).serialize(),
function(data) {
// do something
});
But it doesn't look very elegant. Is this the proper way, or there's a better way to do it?
We could implement the functionality demonstrated in this answer as a custom jQuery instance method which produces an object of key/value pairs from a form and combines it with the properties that aren't derived from the form:
$.fn.formObject = function (obj) {
obj = obj || {};
$.each(this.serializeArray(), function (_, kv) {
obj[kv.name] = kv.value;
});
return obj;
};
$.getJSON('/website/json', $(formName).formObject({
action: "read",
record: "1"
}), function(data) {
// do something
});
Make an Ajax post to send the data to the server. Retrieve the parameter data in the backend code along with the form data.
var formData = {data from form};
formData.action = 'read';
formData.post = '1';
$.ajax({
url: '/website/json',
type: "post",
data: formData
}).done(function (data) {
// remove prior values set upon request response
formData.action = null;
formData.post = null;
});

Categories

Resources