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

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));

Related

jQuery AJAX request data field

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;
});

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);
}
});

how to append multiple string to an HTML element in jquery?

Here, using ajax call I am getting the data as json object. For example, in userid, it returns some value. But in address value, it returns like addr1, addr2, addr3 (3 values). So how can I append these 3 values in html element and also it should be in String format tostring()
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "Controller?token=123",
dataType: 'json',
success: function(data){
$('#userid').html(data.userid.toString());
$('#addr').html(data.addr1.append(addr2));
},
error:function(){
alert("Sorry!");
}
});
});
</script>
Example strings:
addr1: 124, WELINGTONE STREET
addr2: NEWYORK
addr3: OH 12454-8787
These values are get from json object with the key names as addr1, addr2 and addr3
I need to append the key not values.
Something like this?
$('#addr').html([data.addr1,data.addr2,data.addr3].join("<br>"));

assign object to array in javascript multidimensional array

Below i have given my code which is a javascript function which calls a php file and gets json data .... all things are perfect yet but i am getting problem when i want to adda data to a multidimensional array .. sorry for this noob question.. i don't know it can be done or not.
what i want to do
i want to retrieve data on ajax call and save this data to array
so i dont need to call again if i need data again
so i want to store data in multidimensional array which will have two keys
first key will be length iof array
and second will be dataType of my data which can be "name", "id", "description"
is this right way to do this
if it is not then what should i try ...? HELP ME...!!!
or can i assign full jsondata object data got from ajax call success to an array
Newly added requirements of my question
Its associative array like my php array of data is like
$data[0]["id"] = 1;
$data[0]["name"] = "spomething";
$data[0]["descriptoon"] = "spomething";
$data[0]["image"] = "spomething";
//for second item
$data[1]["id"] = 1;
$data[1]["name"] = "spomething";
$data[1]["descriptoon"] = "spomething";
$data[1]["image"] = "spomething";
so i want to create same array for javascript... for every item i fetch... from ajax../ and include into javascript array...
$('.searchButton').bind("mouseover", function() {
var data = $(this).parents('.item').attr('id');
var type = $(this).parents('.tab-pane').attr('id');
// dataArray will be global javascript variable because of its needdss... it will be outside the function
var dataArray = new Array();
$.ajax({
type: 'GET',
url: '<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success: function(data){
var dataArrayLength = dataArray.length;
dataArray.push({dataArrayLength:data});
console.log(dataArray[0]);
}
});
});
now i change my code on thebasis of your suggestion i can push data object in array via push fn ... now how do i call inside data from that object ....!
Object {dataArrayLength: Object}
dataArrayLength: Object
description: "World famous roasted Chicken, avacado, fresh mushrooms, red onions. Mozzarella cheese and our secret sauce."
id: "11"
images: "/htdocs/kiosk/images/dining/items/pizzas/11.jpg"
name: "Bella Notte Signature Pizza"
price: "4.50"
raters: "10"
ratings: "1"
__proto__: Object
__proto__: Object
this is the output of console.log(dataArray[0]) ... so now i want to get "id" , "name", "description" from it how can i do this...????/
MY SOLUTION TO PROBLEM
success:function(data){
var dataArrayLength = dataArray.length;
dataArray.push(data);
dataArray.forEach(function(object,index){
console.log(object.id);
console.log(object.name);
console.log(object.description);
console.log(object.image);
console.log(object.ratings);
});
and this is what i want to do ...
Try this:
$.ajax({
type:'GET',
url:'<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success:function(data){
dataArray = []; // empty it before pushing data into it...
dataArray.push(data);
}
});
I believe you can directly push the data object into the dataArray.
and while you access this simple access it like dataArray[i].id, dataArray[i].name and so on for all the keys of data.
I'm not quite sure i understand, but cant you simply do:
$.ajax({
type:'GET',
url:'<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success:function(data){
var dataArrayLength = dataArray.length;
dataArray.push({'id':data.id,'name':data.name,'image':data.image,'description':data.description});
}
});
});
Or even:
dataArray.push(data);
I havent tested this so consider it pseudo code but i belive that the push method is what you are looking for?

Unable to post Javascript array via jQuery ajax

I am extremely reluctant to ask this question as I know it is something really stupid I am missing, but I simply cannot get this to work. Code below:
<script>
var formArray = new Array();
formArray['start'] = "one";
formArray['stopat'] = "two";
formArray['stop_at'] = "three";
$('#my_button').click(function() {
$.ajax({
type: "POST",
url: "scheduler.php",
data: formArray,
success: function(response){
console.log(response);
}
});
});
</script>
Server side PHP Script scheduler.php
<?php
print_r($_POST);
?>
All I get back logged to the console is an empty array:
Array
(
)
If I console.log formArray within the click function it shows the complete array just fine. So why is it not posting it to my PHP file?
Thanks in advance
Changing Array() to Object() would work as well.
You would get:
Array
(
[start] => one
[stopat] => two
[stop_at] => three
)
You are adding string properties to an array, which is for storing numeric indices.
Use an object instead:
var formArray = {};
formArray['start'] = "one";
formArray['stopat'] = "two";
formArray['stop_at'] = "three";
jQuery will iterate over the indices in an array, using a for (var i = 0; i < formArray.length; ++i) loop, which will completely miss any properties you've added to the array.
Also, new Array should have been [] (as {} should be preferred over new Object). Don't use the new X method of initialization for built-in types. (Crockford, The Good Parts)
JavaScript Arrays are designed to hold an ordered sequence of items with integer keys. When jQuery converts a data structure into Form URL Encoded data and encounters an array, it will iterate over those integer keys and not over named keys.
Use an Object if you want to have named keys.
Change new Array() to newObject()
Edit your Ajax like this and see if it works: data: {data: formArray}, dataType: 'JSON'
$.ajax({
type: "POST",
url: "scheduler.php",
data: {data : formArray},
dataType: 'JSON'
success: function(response){
console.log(response);
}
});
PHP:
print_r($_POST['data']);

Categories

Resources