I'm trying to send the selected rows into a controller when I click on the button with id="send". The issue is that when I tried to send other values( in this case a number and a string) with the selected rows values, the selected rows values is sending null to the controller but the number and the string aren't null in the controller parameters.
This is my javascript code that works fine if only i send the selected rows values:
$('#send').click(function () {
var items = {};
var grid = $('#grid').data('kendoGrid');
var selectedElements = grid.select();
for (var j = 0; j < selectedElements.length; j++) {
var item = grid.dataItem(selectedElements[j]);
items['grid[' + j + '].ParecidoCodigo'] = item.ParecidoCodigo;
}
$.ajax({
url: '#Url.Action("Index", "Busqueda")',
type: "POST",
async: false,
data: items,
success: function (result) {
console.log(result);
}
})
})
and this is my controller method action:
public ActionResult Index(MarcaParecido[] grid)
{ ... }
Everything works fine until now.But when I tried to send another values like this:
$('#send').click(function () {
var items = {};
var grid = $('#grid').data('kendoGrid');
var selectedElements = grid.select();
var enviarDest = $('#destinatario').val();
var marca = $('#numMarca').val();
for (var j = 0; j < selectedElements.length; j++) {
var item = grid.dataItem(selectedElements[j]);
items['grid[' + j + '].ParecidoCodigo'] = item.ParecidoCodigo;
}
$.ajax({
url: '#Url.Action("Index", "Busqueda")',
type: "POST",
async: false,
data: { items, marcas: marca, destinatario: enviarDest },
success: function (result) {
console.log(result);
}
})
})
The selected rows values is sending me null, but the others values aren't null
This is my controller now:
public ActionResult Index(MarcaParecido[] grid, string marcas, string destinatario)
{...}
I tried with JSON.stringify too but it doesn't work.
If items is a collection of the key/value pairs that you are sending to the server, add the two additional parameters to that, and then continue to send item the items object. MVC should read the "grid." items as the list of items in the collection (as you have working now), and see the other two parameters in the variables you have specified:
items["marcas"] = marca;
items["destinatario"] = enviarDest;
$.ajax({
.
.
data: items
Related
I debugged the JS and Ajax code with console.log. I can see that what I entered into the textbox, is displayed in the console. However, when these values are supposed to send to the controller, they are empty or null when I hover over the tbl_stuff List. Not sure where I am making a mistake.
Here is the JS:
$("body").on("click", "#btnSave", function () {
var table = $("table tbody");
var array= new Array();
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
Amount = $(this).find('.val').val();
valuestoupdate = { Amount: amount };
array.push(valuestoupdate);
});
$.ajax({
type: "POST",
url: "#Url.Action("StuffAction","Home")",
data: JSON.stringify(array),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) saved.");
}
});
Here is the controller action:
public JsonResult StuffAction(List<tbl_Stuff> stuffs)
{
int getID = (int)TempData["id"];
TempData.Keep();
var GetData = _context.tbl_Detail.Where(x => x.detId == getID).FirstOrDefault();
if (GetData != null)
{
foreach (tbl_Stuff moreThings in stuffs)
{
tbl_Stuff stuff = new tbl_Stuff();
stuff.Amount = moreThings.Amount;
_context.tbl_Stuff.Add(stuff);
}
}
int insertedRecords = _context.SaveChanges();
return Json(insertedRecords);
}
I get an error saying that moreThings.Amount is empty. But during debugging, the JS code gets the value entered into the textbox.
The .Net routing can't match the request
change the action signature to public JsonResult StuffAction(List< string > stuffs)
or in your ajax call change the array to an array of objects matching the properties of tbl_Stuff
I have to pass List<List<string>> to my controller and read data from it but I am unable to do it. I think that i am sending data wrongly or readuíng it badly but I was unable to find out where is problem.
My code in controller:
public async Task<ActionResult> GetFindResults(string TableName, List<List<string>> AllData)
{
Console.WriteLine(AllData[0][1]); //error: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
//doing long code, problem is not in return
return Json(new { pocetfound = found.Count(), listfound = found });
}
My code in View(Ajax):
var EndSender = []; //Always is like [["one", "two", "three", "four"], ["One2", "Two2", "Three2", "Four2"]] after for loops
var TableFilter = document.getElementById("TableNN111");
for (var i = 1, row; row = TableFilter.rows[i]; i++) { //i = 1, because I dont want to read header of my table
var tempArr = [];
for (var j = 0, col; col = row.cells[j]; j++) {
tempArr.push(col.innerHTML);
}
EndSender.push(tempArr);
}
alert(EndSender[0][1]); //return right value
var link = '#Url.Action("GetFindResults", "MyController")';
var args = {
TableName: '#ViewBag.TableName',
AllData: EndSender
};
$.ajax({
type: "GET",
url: link,
data: args,
dataType: "json",
success: function (data) {
alert(data.pocetfound);
$("#HidenLink").val(data.pocetfound);
},
error: function () { //after error in controller it throws this
alert("Error. Kontaktujte správce.");
return;
}
});
So basically I am trying to send EndSender that is List<List<string>> and then I want to read from it but I am for some reason unable to, am I sending data wrongly? Am I rerading it wrongly?
Thanks for any help!
EDIT:
I am testing it and it seems like it recognizes that I have sent List<List<string>> but is unble to read from List<List<string>(<-- this List that holds string is unable toread but knows that there is List<string>)>
for (int i = 0; i < AllData.Count(); i++)
{
Console.WriteLine(AllData.ElementAt(i)); //return that there are List<string>
for (int i2 = 0; i2 < AllData.ElementAt(i).Count(); i2++) //is unable to execute
{
Console.WriteLine(AllData.ElementAt(i).ElementAt(i2));
}
Console.WriteLine("\n");
}
EDIT2: My Json looks like this: [["2010","Vše","","false"],["2001","CV","aaa","false"]]
I'm trying to fetch designations from database using ajax and php and store those values in a javascript variable designations.
I'm trying to set the availabletags option of tagit() from this designation variable.
var tagThis = $(".tagit");
tagThis.tagit({
tagSource: function(search, showChoices) {
$.ajax({
type : 'POST',
url: "/tags/search",
data: { queryString: inputString },
dataType: "json",
success: function(data) {
var assigned = tagThis.tagit("assignedTags");
var filtered = [];
for (var i = 0; i < data.length; i++) {
if ($.inArray(data[i], assigned) == -1) {
filtered.push(data[i]);
}
}
showChoices(filtered);
}
});
}
});
The drop down isn't getting produced when I change the type to POST.
I have data in a table coming from multiple json api links.
my code currently is
<script src="js/1.js"></script>
<script src="js/2.js"></script>
Above this is a table code. Allowing the table to be sorted. It only has <th> and <thead> tags.
The issue as it stands looks like this:
I'm wanting ideally the price field to be sorted. below is the inside of the JS files
1.js
$.ajax({
type : 'GET',
crossDomain : true,
dataType : 'json',
url : 'api link here',
success : function (json) {
//var json = $.parseJSON(data);
for(var i=0; i<json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid").append("<tbody><tr><td>"+section+"</td><td>"+no+"</td><td>"+price+"</td><td>"+button+"</td></tr></tbody>");
$("#tableid").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
}
},
error : function(error){
console.log(error);
}
});
and here is the 2nd js file
$.ajax({
type : 'GET',
crossDomain : true,
dataType : 'json',
url : '2nd api',
success : function (json) {
//var json = $.parseJSON(data);
for(var i=0; i<json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid").append("<tbody><tr><td>"+section+"</td><td>"+no+"</td><td>"+price+"</td><td>"+button+"</td></tr></tbody>");
$("#tableid").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
}
},
error : function(error){
console.log(error);
}
});
Now here is what i believe is the code to sort the js files in the table, Issue is I have no idea where to put it.
var sortTable = function(){
$("#tableid tbody tr").detach().sort(function(a,b){
//substring was added to omit currency sign, you can remove it if data-price attribute does not contain it.
return parseFloat($(a).data('price').substring(1))- parseFloat($(b).data('price').substring(1));
})
.appendTo('#tableid tbody');
};
And
for(var i=0; i<json.results.length; i++) {
....
}
sortTable();
I would use a tablesorter jquery plugin but i would rather not.
Since you're pulling data from two ajax requests, perhaps it will be better to store both results in one global array that you can sort and loop through to build your table in price order.
var resultsArray = new Array();
for (var i = 0; i < json.results.length; i++) {
resultsArray.push(json.results[i]);
}
resultsArray.sort(function(a,b) {
return a.price - b.price;
});
for (var i = 0; i < json.results.length; i++) {
//print your table here
var price = resultsArray[i].price;
//etc...
}
I fully demonstrated this in a fiddle
is it possible for you to take both of the json reponses, sort them in order by price, and then add them to the dom? This way you don't have to access the dom so much just to sort your data?
This would go something like this, if you're using jQuery. Basically once both of your ajax requests resolve you can do whatever with the data you have. Fromt here you can merge them, sort them, and then run your piece to populate the table.
var urlDatas = [];
$.when(
$.getJSON(someUrl, function(data) {
urlDatas.push(data);
}),
$.getJSON(someOtherUrl, function(data) {
urlDatas.push(data);
})
).then(function() {
//not completely sure if extend returns a value or just mutates, target.
finalData = $.extend(true, {}, urlDatas[0], urlDatas[1]);
//run a sort on that data
sortData(finalData);
//add it to your dom
insertData(finalData);
});
I have seen many of these questions on here but none seem to solve my problem. I have a multidimensional (nested) array which I am populating through query. I wish to send the final array over AJAX jQuery:
(function() {
var orderDetails = [];
orderDetails['retailer'] = [];
orderDetails['order'] = [];
db.transaction(function(qry){
qry.executeSql("SELECT * FROM retailers WHERE pending = '1' ", [], function(tx, results){
len = results.rows.length; //if rows.length, means retailer is pending so add details to array. If no length, means retailer exists
for (var i=0; i<len; i++){
console.log('start '+i+' loop in retailers qry');
orderDetails['retailer'][i] = [];
orderDetails['retailer'][i]['localID'] = results.rows.item(i).ID;
orderDetails['retailer'][i]['retailerName'] = results.rows.item(i).retailerName;
orderDetails['retailer'][i]['address'] = results.rows.item(i).address;
orderDetails['retailer'][i]['postcode'] = results.rows.item(i).postcode;
console.log('finish '+i+' loop in retailers qry');
}
}, function(err){console.log(err)})
}
This is how I am populating the array, and here is the AJAX request:
function(){
console.log('start orders qry success callback');
//alert(orderDetails['retailer'][0]['localID']);
var st = JSON.stringify(orderDetails['retailer']);
console.log(st);
$.ajax({//send retailer to server, bring back the ID of the retailer as it is on the server so we can insert it into the order
type: "POST",
cache: false,
//async: false,
url: "https://www.......processOrder.php",
data: { orderType: 'saved', orderDetails: st},
dataType: "json",
success: function(result){
}
})
});
When I log the above just before the ajax request, it returns [[],[],[],[],[],[],[],[],[],[],[]] so I know something is working, I just thought the whole contents of the object would be visible on the server side.
Also I have wrapped the whole thing in an anonymous function because I think this helps the array variable scope.
Change this orderDetails['retailer'][i] = []; to this orderDetails['retailer'][i] = {};
And if your item is not a function you want to call with parameter i, access it like this: results.rows.item[i].ID