I have spent the last couple of hours battling to write some javascript and jquery.
Basically I am trying to loop through a table checking if an attribute exists within a TD if it does add its info into an array and post it back to the server
My code (I am sure it could be better)
$("#save-changes").click(function () {
var param = [];
var table = $("#products-grid > .t-grid-content > table tbody tr").each(function (i) {
//find checkboxes using class
var td = ($(this).find("td:nth-child(2)").find(".cb"));
var attr = $(td).attr('data-item');
if (typeof attr !== 'undefined' && attr !== false) {
console.log(td);
param.push({ "itemId": attr, "productId": td.val() });
}
});
console.log(param);
$.ajax({
url: '#Url.Action("ApplyProduct")',
data: param,
type: 'POST',
success: function (e) {
I am now stuck on trying to pass the array back to the server. What do I need to do to send the data back to the server as a parameter the server can understand?
Any help would be great!
add two parameters
dataType: "json",
data: JSON.stringify(param)
to your .ajax call.
Crate an object server side which has two int properties int called itemId and productId and then create a JsonResult route that takes an array of your object that you post too (this would be ApplyProduct in your case).
you cannot send arrays to a server , they have to be strings.
you could join the array together like this
param.join(";");
that would create a string with each value seperated by a ;
also you need to specify the data option as a key-value json
$.ajax({
url: '#Url.Action("ApplyProduct")',
data: {
param : param
},
type: 'POST',
then on the serverside you can split the string back into an array
$param = explode(";",$_POST['param']);
Related
I have an MVC PagedList which works just fine. I am filtering that list and the filter predicate is sent to the client during roundtrips. I use unobtusive ajax replacing. My pager code looks as:
#Html.PagedListPager((IPagedList)Model.Items,
page => Url.Action("Filter",
new ClientSearch
{
Page = page,
PageSize = Model.PageSize,
Predicate = Model.Predicate
}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "clients-list",
}))
The problem is, that the Predicate parameter is too long. And it should be. I get the following exception:
"The request filtering module is configured to deny a request where the query string is too long."
I do not want to alter the web.config in order to allow long parameters. I would like to pass the model in a POST header instead of query string parameter. Is it possible with PagedList?
Thanks in advance.
I still couldn't figure out whether PagedList supported posting large data, however I ended up with the following workaround.
I have a post method which posts the model to the controller function and replaces the partial view content with the results.
function postToPage(url, size, predicate, replace) {
var data = {
size: size,
predicate: predicate
};
$.ajax({
url: url,
data: data,
type: 'POST',
success: function (result) {
$('#' + replace).html(result);
}
});
}
I also have another function to replace the URLs in the pagination-container div and wire up the click event to call the post method. The click event stops event propagation, so the URL in the href attribute won't be used.
function replaceHrefs() {
$('div[class = pagination-container').find('a').each(function (index, value) {
var url = value.href.toString();
value.addEventListener('click', function (event) {
event.stopPropagation();
post(url);
});
value.href = '#';
});
I created a custom version of post method in order to generate the pagesize and predicate from the model.
function post(url) {
postToPage(url, #Model.PageSize, '#Model.Predicate', 'clients-list');
}
I had to wire up the URL replacing procedure to two places: when the document becomes ready and when the ajax call completes. These covered all the cases I needed.
$( document ).ajaxComplete(function() {
replaceHrefs();
});
$( document ).ready(function() {
replaceHrefs();
});
I hope it helps someone.
I'm using select2 and I want to set a custom field for the text property of the rendered items without
replacing standard behavior (marking and such)
pushin all my array into a new one with the text field on it
ps: i just want to a render many select2 items that doesn't have a text field
Basically if you see this jsbin you will see something like this
$("#e10_3").select2({
data:{ results: data, text: function(item) { return item.tag; } },
formatSelection: format,
formatResult: format
});
But if I delete the custom formatSelection and formatResult parameters of select2 I loose my hability to use a different field for text.
I suggest this approach
$("#e10_3").select2({
data:{
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.tag,
id: item.id
...
}
})
};
}
},
formatSelection: format,
formatResult: format
});
As previous answer this solution DOES create a new array, but it seems to be a better approach considering readability. Before passing data you should modify it. You can see this in official docs
var data = $.map(yourArrayData, function (obj) {
obj.text = obj.text || obj.name; // desired field
return obj;
});
The only other option is to prepare data with text property matched to desired property from the very beginning.
UPDATE (added an example)
$('your-select2-el').select2
data: $.map(yourArrayData, (obj) ->
obj.text = obj.your_custom_field_name # obj.title or obj.name etc.
obj
)
See docs in the link I provided before and this one
In my web app , I am showing rates of stocks.I am using jquery autocomplete to show options while entring stocks name. But I have built local copy of javascript array. I want to show the options from this local array , If search term is not found in local array then ajax call must be made to get the list from server side.
Thanks !!!
//Local array
var local_array=["option1","option2"];
//jqueryUI call of autocomplete function
$('#search_stock').autocomplete({
source:function(){
if(search term is found in local array)
{
show suggestion from local array.
}
else
{
make ajax call to show suggestions of stock names.
}
}
});
UPDATE
Here's the actual code
$(function() {
var cache = {'option1':'option1','option2':'option2'}, lastXhr;
$( "#stock_rates" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "stock_rates.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) { response( data ); }
});
}
});
});
The example pages for jQuery UI autocomplete have an example of exactly this issue.
http://jqueryui.com/demos/autocomplete/#remote-with-cache. Click the 'View Source' link on that page to see the code for the example.
The key part is that 'source' takes arguments.
source: function(request, response){
You need to read request, either fetch the value from your cache, or do a request, and then call the response function and pass it the matched values.
Update
Your problem now is that the format that you are storing in your cache is wrong. The cache just stores data as it would be returned from your getJSON call, indexed by the search term. It is up to you do to do the prefix checking and such.
To continue the way you are trying now, you'll either need to populate the cache properly.
var cache = {
"o": ['option1', 'option2'],
"op": ['option1', 'option2'],
// ....
"option1": ['option1'],
"option2": ['option2']
};
Otherwise, you could store the data differently and put more logic in your 'source' function to do the prefix checking on a static array or something. That all really depends on the data you are caching though.
Use search event of autocomplete and check your condition in that event and based on that return true or false if you want to make a ajax call respectively.
Below is the sample code.
$('#search_stock').autocomplete({
search:function(event,ui){
if(search term is found in local array)
{
return false;
}
else
{
return true;
}
}
});
I have problem with autocomplete. The code below is returnig me
["foo#foo.com","bar#bar.com"]
$('.autocomplete').keyup(function() {
tid = $(this).attr('id')
$(this).autocomplete({
source: function (req, resp){
$.ajax(
{
url: "autocompl.asp",
data:$("#msgForm").serialize() + "&field="+tid ,
success : function( resp ) {
return resp
}
})
}
});
});
But the suggestions don't appear. It worked for me when I have called autocomplete without any extra parameters.
Any clue?
Thanks in advance
Magda
Note that one of your parameters for the source function is resp, and you're using another resp afterwards. I think you need to use the first resp to send the response object back.
I'm using this as well and this works for me (Instead of sending an array of values, I'm sending an array of objects with two attributes, but I don't think it's mandatory).
id
label
so the code inside the ajax success should look something like this (my data variable is your second resp variable, a different name to avoid mixup):
success: function(data) {
for (i in data) {
a = {}
a.id = data[i]
a.label = data[i]
options.push(a)
}
resp(options)
}
I am having problems with Jquery parsing the JSON I am sending back... however, this is very odd because I am using MVC's JSON method.
Here's my setup. I have a very simple function:
$.ajax({
url: URLd,
dataType: 'json',
data: { Year: $('#VehicleYear').val(), Value: request.term },
success: function (data, textStatus, jqXHR) { alert("Success!"); },
error: function(XMLHttpRequest, textStatus) {
alert(textStatus + ": " + XMLHttpRequest.responseText);
}
});
It always runs the error function which shows:
parsererror: [{"Value":"Toyota","ID":160}]
I cannot figure out why in the world it is doing this... it was working with an older version of JQuery - and I read that the JQuery JSON parser is quite a bit more strict now- but I can't figure out what's wrong with my JSON.
Even if it is wrong, that's very frustrating because I'm using MVC's Json function to generate this:
public ActionResult GetVehicleModels(int Year, int MakeID, string Value = null)
{
var modlMatchs = (from VMYX in ent.VehicleMakeYearXREFs
join VM in ent.VehicleModels
on VMYX.VehicleModelID equals VM.VehicleModelID
join VMa in ent.VehicleMakes
on VM.VehicleMakeID equals VMa.VehicleMakeID
where VMYX.ModelYear == Year && VMa.VehicleMakeID == MakeID && VM.VehicleModelName.StartsWith(Value)
orderby VMa.VehicleMakeName
select new { Value = VM.VehicleModelName, ID = VM.VehicleModelID }).Distinct().Take(10).ToList();
return this.Json(modlMatchs, "application/json", JsonRequestBehavior.AllowGet);
}
I must be missing something glaringly obvious... still getting the hang of JQuery/MVC but these things are really slowing my progress.
Sure enough, the JQuery result looks as follows (according to Chrome's developer toolbar)
[{"Value":"Toyota","ID":160}]
Change your dataType in the jQuery AJAX call to "text json". I suspect there may be a problem with the response content-type header, or something else that's causing jQuery not to acknowledge the dataType as json. Using "text json" will cause jQuery to accept it as plaintext before converting it to a js object.
var parsed = jQuery.parseJSON('[{"Value":"Toyota","ID":160}]');
I've just tried the above and it parses it fine, however remember it has returned it as a single record in an array (due to returning an IEnumerable from the C#).