jQuery AJAX request data field - javascript

I'm using this piece of code to make an ajax call:
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('caricamento...'); // changing the button label
},
success:function(data){
filter.find('button').text('Filtra'); // changing the button label back
$('.load').html(data); // insert data
$('.grve-iso-spinner').hide();
}
});
return false;
});
I need to add more variables to the 'data' attribute, something like:
data : {
var1: 'value1',
var2 : 'value2'
}
How can I merge the two data elements?
Thanks in advance

You can try this:
data: filter.serialize() + '&key=' + value,
It will add key: value pair to form serialize data. As serialize data is in the form of key: value pair, you can add additional values by following the same pattern

As jQuery serialize() function produces a text string in standard URL-encoded notation, you only have to concatenate the new values you want to add:
var data = filter.serialize();
data += "&var1=" + value1 + "&var2=" + value2;

Take a look at this answer:
jQuery post() with serialize and extra data
It uses serializeArray and pushes the extra data to the array instead, you can then pass this array to the ajax call.
var data = $('#filter').serializeArray();
data.push({name: 'wordlist', value: wordlist});

try this
var data = $('#filter').serializeArray();
data.push({name: 'var1', value: value1});
data.push({name: 'var2', value: value2});
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:{ data : data }, // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('caricamento...'); // changing the button label
},
success:function(data){
filter.find('button').text('Filtra'); // changing the button label back
$('.load').html(data); // insert data
$('.grve-iso-spinner').hide();
}
});
return false;
});

Related

How to send multiple javascript values to a C# action method?

Suppose I have some javascript like in the image. In the array
I put the (multiple) values in the variable array and send this
array to an action method in a controller. However, in the action method I will get this as an 'object'. How do I get the values out of this 'object'? I prefer to not use an ajax post. Is this possible? If yes, how do I 'catch' the values in the action method?
You should use the data property to send the array of integers
var array = [1, 2, 4];
$.ajax({
url: '/Home/Items',
type: 'POST',
data: { items: array },
success: function(data) {
console.log(data);
}
});
Assuming your have an action method like this to receive it
[HttpPost]
public ActionResult Items(int[] items)
{
// to do : do something with items
return Json(items);
}
Now i see you read the value of an input field and use that as the value of your array variable. I am not sure what format of value you have in your input field. If it is comma seperated list of int (Ex : "1,3,5"), you may use the split function to get an array from that.
var v = "2,5,78,8";
var array = v.split(',');
In Ajax call:
var items = ['USA', 'UK', 'Canada'];
$.ajax(
{
type: "POST",
url: "/Test/Details",
contentType: 'application/json',
data: JSON.stringify({ function_param: items })
});
In Controller:
public ActionResult Details(string[] function_param)
If you don't want to use Ajax call, then create an input type hidden control in html and put the javascript array to the hidden field and submit the form and get value in controller by using request.form["hiddencontrol"]
In JS:
$("#hiddenControl").val(JSON.stringify(items));

dynamically build data string for ajax call that contains html

For a long time I have been using the below code to dynamically build a string representing key value pairs to be used in an ajax call.
This has been working quite well for my originally simple needs.
// make an array of strings representing key value pairs
var feedback = ['var1=val1', 'var2=val2', 'var3=val3' ];
// join each pair with "&" seperating them
var dataString = feedback.join('&');
// make an ajax call
$.ajax({
type: "POST",
url: "_php/feedback.php",
data: dataString, //pass in the built vars
success: function() {
// do stuff...
}
});
I now have the need to send html as values in the data string. First thing I notice is that html containing '&' is going to be an issue so I made a simple test using var2=<span> val2<span>:
// make any array of strings representing key value pairs
var feedback = ['var1=val1', 'var2=<span> val2<span>', 'var3=val3' ];
// join each pair with "&" seperating them
var dataString = feedback.join('&');
// amke an ajax call
$.ajax({
type: "POST",
url: "feedback.php",
data: dataString, //pass in the built vars
success: function(info) {
$('#result').html(info);
}
});
Then in my php page:
<?php
$var1=$_POST['var1'];
$var2=$_POST['var2'];
$var3=$_POST['var3'];
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>';
?>
I want the script to return:
val1<br><span> val2<span><br>val3<br>
But, just as I suspected, the return output was:
val1<br><span><br>val3<br>
A quick look in the inspector shows:
How can I dynamically create a string to use with data: dataString, in an ajax call that may contain html?
I tried searching for this but all I can find is "how to send post data with an html form" which clearly doesnt help.
// make an array of strings representing key value pairs
var feedback = ['var1=val1', 'var2=val2', 'var3=val3' ];
// to apply encodeURIComponent function for each cell
feedback = feedback.map(function (cell)
{
var res = cell.split('=');
return res[0] + '=' + encodeURIComponent (res[1]);
}) ;
// join each pair with "&" seperating them
var dataString = feedback.join('&');
$.ajax({
type : "POST",
url : "feedback.php",
data : dataString,
success: function(info) {
$('#result').html(info);
}
});

Splitting a string into words has resulted in splitting into letters

I'm new to Javascript. I need to split a string of this format:
["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
and create as options for select tag. I tried the below code
$.each(data, function (index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
But I get strings split as letters.
What can I do to split the string to get options as
<option>Man1</option>
<option>SKC2</option>
Note : Some times this string may contain spaces as well.
If data is your string, then parse it from JSON to a JavaScript array of strings, then iterate over that:
var yourArray = JSON.parse(data);
$.each(yourArray, function(index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
Try to pass the array first and then pass the translated array as the html string,
$('#bu_group').html($.map(JSON.parse(data),function(val,i){
return "<option value="+ val +">" + val + "</option>";
}));
DEMO
As data is actually coming from your server via ajax you can simply specify correct dataType.
Either
$.ajax({dataType: 'json', ...}).done(function(data){
//data will be parsed
});
Or
$.getJSON(url).done(function(data){
//data will be parsed
});
Or configure your server to return correct mime type (application/json)
if your data is
["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
then there is no problem, so I think you have your data as :
'["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]'
which you must 'parse' it.
as you are using jQuery, one option is to parseJSON like this:
var parsed_array = $.parseJSON('["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]');
after doing that, you can successfully do :
$.each(parsed_array, function (index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
If you have your data as
var data=["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
then you can iterate this var, isn't it?
var data=["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"];
for(i=0;i<data.length;i++) {
$('#bu_group').append($('<option/>', {
value: data[i],
text : data[i]
}));
};
JSFiddle here

Backbone js - Clean up data using regex on collection(models) before passing to view

I'm using backbone to populate a dropdown list. Changes to the API have resulted in the data (option labels) coming back with unwanted data e.g "Option Foo - 00011222" instead of "Option Foo"
I'm planning to use regex so that i can only show the first characters before the '-'
What is the best approach to sanitizing data on a collection before rendering to a view.
Should this be done on the view or on the collection
If the additional data can be safely discarded, you can use Model.parse to modify the data you receive:
parse model.parse(response, options)
parse is called whenever a model's data is returned by the server, in fetch, and save. The
function is passed the raw response object, and should return the
attributes hash to be set on the model.
For example, if you want to replace a label field:
var data = [
{label: 'Option Foo - 00011222'},
{label: 'Option Foo2 - 00011222'}
];
var M = Backbone.Model.extend({
parse: function(data) {
data.label = data.label.replace(M.regexp, '');
return data;
}
}, {
regexp: /\s*-.*$/
});
var C = Backbone.Collection.extend({
model: M
});
var c = new C(data, {parse: true});
console.log(c.pluck('label'));
And a demo http://jsfiddle.net/nikoshr/xPJDr/

How to Access Array response of AJAX

This is my AJAX call response which is in array format
[1,2,3,4,5,6]
success: function(outputfromserver) {
$.each(outputfromserver, function(index, el)
{
});
How can we access outputfromserver all values ??
Means outputfromserver Zeroth value is 1 , 2nd element is 2 , -----so on
It would help to know what your AJAX request looks like. I recommend using $.ajax() and specifying the dataType as JSON, or using $.getJSON().
Here is an example that demonstrates $.ajax() and shows you how to access the returned values in an array.
$.ajax({
url: 'test.json', // returns "[1,2,3,4,5,6]"
dataType: 'json', // jQuery will parse the response as JSON
success: function (outputfromserver) {
// outputfromserver is an array in this case
// just access it like one
alert(outputfromserver[0]); // alert the 0th value
// let's iterate through the returned values
// for loops are good for that, $.each() is fine too
// but unnecessary here
for (var i = 0; i < outputfromserver.length; i++) {
// outputfromserver[i] can be used to get each value
}
}
});
Now, if you insist on using $.each, the following will work for the success option.
success: function (outputfromserver) {
$.each(outputfromserver, function(index, el) {
// index is your 0-based array index
// el is your value
// for example
alert("element at " + index + ": " + el); // will alert each value
});
}
Feel free to ask any questions!
The array is a valid JSON string, you need to parse it using JSON parser.
success: function(outputfromserver) {
var data = JSON.parse(outputfromserver);
$.each(data, function(index, el) {
// Do your stuff
});
},
...
You can use JS objects like arrays
For example this way:
// Loop through all values in outputfromserver
for (var index in outputfromserver) {
// Show value in alert dialog:
alert( outputfromserver[index] );
}
This way you can get values at first dimension of array,
above for..loop will get values like this:
// Sample values in array, case: Indexed array
outputfromserver[0];
outputfromserver[1];
outputfromserver[2];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
However, when implemented this way, by using for ( index in array ) we not only grab indexed 1,2,3,4,... keys but also values associated with named index:
// Sample values in array, case: accosiated/mixed array
outputfromserver["name"];
outputfromserver["phone"];
outputfromserver[37];
outputfromserver[37];
outputfromserver["myindex"];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
In short, array can contain indexed values and/or name associated values, that does not matter, every value in array is still processed.
If you are using multidimensional stuff
then you can add nested for (...) loops or make recursive function to loop through all and every value.
Multidimensional will be something like this:
// Sample values in array, case: indexed multidimensional array
outputfromserver[0][0];
outputfromserver[0][1];
outputfromserver[1][0];
outputfromserver[1][...];
outputfromserver[...][...];
Update, JSON object:
If you server returns JSON encoded string you can convert it to javascript object this way:
try {
// Try to convert JSON string with jQuery:
serveroutputobject = $.parseJSON(outputfromserver);
} catch (e) {
// Conversion failed, result is not JSON encoded string
serveroutputobject = null;
}
// Check if object converted successfully:
if ( serveroutputobject !== null ) {
// Loop through all values in outputfromserver
for (var index in serveroutputobject) {
// Append value inside <div id="results">:
$('#results').append( serveroutputobject[index] + "<br/>" );
}
}
// In my own projects I also use this part if server can return normal text too:
// This way if server returned array we parse it and if server returns text we display it.
else {
$('#results').html( outputfromserver );
}
More information here
$.ajax({
type : "POST",
dataType: "json",
url : url,
data:dataString,
success: function(return_data,textStatus) {
temperature.innerText=return_data.temp;
// OR
**temperature.innerText=return_data['temp'];**
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error while accessing api [ "+url+"<br>"+textStatus+","+errorThrown+" ]"); return false;
}
});

Categories

Resources