jQuery: I'm trying to send data via AJAX for jQuery.ui.sortable but it doesn't send everything - jquery-ui

I'm trying to build an array structured like
[
[num,
[num, num num]],
[num,
[num, num]],
]
but I get [num,num,num,num,num,num,num] =(
code here: http://jsfiddle.net/WRppV/4/
the problem is that I'm trying to send the var 'x' as data in an AJAX update function that jQueryUI uses for sortable. And it needs to be the array structure above. =\
I'm using the http://jqueryui.com/demos/sortable/#connect-lists kind of sorting.
So, normally I would just to $j(list selector).sortable('serialize')
but because I have two lists I tried this $j(selector1,selector2).sortable('serialize') which is what you do for sorting two lists as in the example. But when the ajax request is made, it only sends the updated list. Which would be fine if I had tons of processing power. but I need the list, and which list it belongs to.
Whats really interesting is that my server says the war is getting sent as
"content"=>"215,207"
but that doesn't even include the section_id
I should be getting something similar to
["141", ["203", "206", "204", "205"],
"142", ["215", "207"]]
(numbers and structure from chrome when I run the script from the link on my webpage)
my sortable js:
$j("<%= #sortable_contents %>").sortable({
connectWith: '.section-content',
axis: 'y',
zIndex: 1003,
cursor: 'crosshair',
update: function(){
d = $j("#sort_sections > li").map(function(index, element){
return [element.id.replace(/[a-z]+_/,""), [
$j(element).find("li.content").map(function(subindex, subelement){
return subelement.id.replace(/[a-z]+_/,"");
}).get()]];
}).get();
alert(d)
$j.ajax({
type: 'post',
data: {'content': d},//$j("<%= #sortable_contents %>").sortable('serialize'),//
dataType: 'script',
complete: function(request){
$j('#sort_contents').effect('highlight');
},
url: '/contents/sort_contents'})
}
});

This is nested. Don't listen to alert, try console.log instead.
In chrome, this gets logged out as this:

Related

jquery mobile 1.4 not updating content on page transition

From the index page, a user clicks a navigation link, the data attribute is passed via ajax, the data is retrieved from the server but the content is not being updated on the new page.
Been stuck for hours, really appreciate any help!
js
$('a.navLink').on('click', function() {
var cat = $(this).data("cat");
console.log(cat);
$.ajax({
url: 'scripts/categoryGet.php',
type: 'POST',
dataType: "json",
data: {'cat': cat},
success: function(data) {
var title = data[0][0],
description = data[0][1];
console.log(title);
$('#categoryTitle').html(title);
$('#categoryTitle').trigger("refresh");
$('#categoryDescription').html(description);
$('#categoryDescription').trigger("refresh");
}
});
});
Im getting the correct responses back on both console logs, so I know the works, but neither divs categoryTitle or categoryDescription are being updated. I've tried .trigger('refresh'), .trigger('updatelayout') but no luck!
This was not intended to be an answer (but I can't comment yet.. (weird SO rules)
You should specify in the question description that the above code IS working, that your problem occurs WHEN your playing back and forth on that page/code aka, using the JQM ajax navigation.
From what I understood in the above comment, you're probably "stacking" the ajax function every time you return to the page, thus getting weird results, if nothing at all.
Is your example code wrapped into something ? If not, (assuming you use JQM v1.4) you should consider wrapping it into $( 'body' ).on( 'pagecontainercreate', function( event, ui ) {... which I'm trying to figure out myself how to best play with..
Simple solution to prevent stacking the ajax definition would be to create/use a control var, here is a way to do so:
var navLinkCatchClick = {
loaded: false,
launchAjax: function(){
if ( !this.loaded ){
this.ajaxCall();
}
},
ajaxCall: function(){
// paste you example code here..
this.loaded = true;
}
}
navLinkCatchClick.launchAjax();

Retrieve passed data between pages with JQuery Mobile

I'm generating some list items with JQuery Mobile. These list items have an id on the anchor. All anchors needs to load the page event.html. I need to retrieve the id when event.html is loaded.
On my index page I have the following code, which should pass the id from my anchor and refer me to event.html.
$(document).on('pageinit', '#index', function() {
$(document).on('click', '#overview a', function(e) {
e.preventDefault();
$.mobile.changePage('event.html', {
transition: 'slide',
data: {
'id': 'this.id'
}
});
});
});
On the page event.html I want to retrieve the data id.
$(document).on('pageinit', '#event', function() {
//output data id
});
How do I do this?
I've seen some examples where people have tried to do this by using global variables and submitting through get request. I have not been able to successfully reproduce their solutions and I would prefer if the data could be passed directly from the pages. Is this possible?
i think get method is the best , however I sometimes use the method data() , but you have to create a dummy element that is common among pages to keep you data , you can check this page though :
http://api.jquery.com/data/

Assigning JSon data in JqGrid using WebApi

I am building an application using MVC & Web Api. On a View I am using JqGrid. Previously we used to assign local data to JqGrid which was working fine. Now due to some changes in logic, we are using WebApi to bring data from Server, this is a Json data, we store it in variable then we assign this data object to JqGrid but data does not get displayed.
When instead of data option i give "url" of web api then everything works fine, but as soon we use "data" option then jqgrid does not work.What could be the possible reason? Reason for doing this is that I want to add, edit, update data locally and then when final save button is pressed, data goes back to Server.
$().ready(function () {
//{"total":1,"page":1,"records":3,"rows":[{"id":"1","cell":["1","Tomato
//Soup","db#db.com","db#db.com","Groceries"]},{"id":"2","cell":["2","Yo-
//yo","db#db.com","db#db.com","Toys"]},{"id":"3","cell":
//["3","Hammer","db#db.com","db#db.com","Hardware"]}]}
//
$.getJSON("api/userwebapi/",
function (data) {
//userDataFromApi = jQuery.parseJSON(data);
userDataFromApi =data;
//alert(userDataFromApi[0].ID);
ConfigureUserGrid(userDataFromApi);
});
});
function ConfigureUserGrid(userDataFromApi) {
var grdUsers = $("#grdUsers");
var lastsel = 0;
$("#grdUsers").jqGrid({
datatype: "json"
, data: userDataFromApi
//, url: "api/userwebapi"
,colNames: ['ID', 'Name', 'User Role', 'Email', 'Address']
,colModel: [
{ name: 'ID', index: 'ID', width: 80, hidden: true }
, { name: 'Name', index: 'Name', width: 150 }
, { name: 'UserRole', index: 'UserRole', width: 150 }
, { name: 'Email', index: 'Email', width: 200, sortable: true }
, { name: 'Address', index: 'Address', width: 200, sortable: true }]
, viewrecords: true
, pager: '#pager1'
, mtype: 'GET'
,rowNum:true
,caption: 'My first grid'
}); //close of jQuery("#grdUsers").jqGrid({
$("#grdUsers").jqGrid('navGrid', '#pager1',
{ add: false, del: false, edit: false, search: false, refresh: false });
}
The reason of the problem is wrong usage of jqGrid parameters (options). To be exactly you use wrong combination of jqGrid options. Tony Tomov (the developer of jqGrid) added many features in jqGrid during every new version. He wanted to hold backwards compatibility if it's possible. As the result there are a lot of options without clear name conversion. Many options work only if some other options are set. Exactly like in case of jQuery or jQuery UI there are no validation of input parameters. It makes many problems who people who starts to use jqGrid.
The problem in your case is the usage of data parameter together with datatype: "json". It's wrong combination of parameters. The problem is that jqGrid supports two remote datatypes and some local datatypes.
If you use datatype: "json" or datatype: "xml" then jqGrid get for you AJAX request for initial filling of grid and on every sorting, paging and (optionally) filtering. In any way the request to the url will be send. One uses HTTP command specified by mtype parameter. The paging and sorting of data have to be implemented on the server side. The request contain the requested page number, the length of the page, the index of the column used for the sorting and the direction of sorting. The data returned from the server should in the format described here. If you have non-standard data format you can use jsonReader options of jqGrid and jsonmap (xmlmap) in colModel to specify how the server response should be used to fill the grid.
If you don't want to implement server side paging, sorting and filtering of data you can use loadonce: true option. In the case the server should return all data at once. The data should be sorted once based on the initial sorting column (based of sortname and sortorder which you use). jqGrid will change datatype automatically to "local" after the first loading of data.
All other datatypes will be interpreted as local datatypes. The data parameter will be used only in case of datatype: "local". One should use another format of data in the case. One can use localReader (see here) to change the way how the data should be read from data parameter.
There are special case datatype: "jsonstring" where you can fill the grid in the way close with datatype: "json", but to use an object or JSON string as the input. In the case one should use datastr (not data !!!) as the input of data. After the first filling the datatype will be changed by jqGrid from datatype: "jsonstring" to datatype: "local".
So you have some options to fix the problem:
to use url and loadonce: true options if you don't want to implement paging of data.
to use datatype: "jsonstring" and datastr instead of data.
to use datatype: "local" and data filled as array of named items (properties of items should be the same as the value of name property of the columns).

Jquery UI Autocomplete: is "value" required?

I am using jQuery UI's autocomplete with a remote data file. It works but it's slow. My JSONP is over a meg of 'value' junk characters and I'd like to minimize that. Here is the format:
[{"value": "Aaronsburg, PA"},
{"value": "Abanda, AL"},
{"value": "Abbeville, AL"}]
How do I get jQuery UI's Autocomplete to accept a remote data file of the form:
{["Aaronsburg, PA", "Abanda, AL", "Abbeville, AL"]}
or
["Aaronsburg, PA", "Abanda, AL", "Abbeville, AL"]
?
jQuery UI Autocomplete can take any format of data. You have complete control the rendering of the list but in this case I think it might just work.
This demo (albeit with a local source) seems to work as expected.
If you need more control you can tailor the renderItem function to suit any data format:
var searches = [{
label:'first',
desc:'foo foo',
},
{
label:'second',
desc:'bar bar',
},
{
label:'third',
desc:'baz baz',
}];
$(function() {
$('input').autocomplete({
dataType: 'json',
source: searches
})
.data('autocomplete')._renderItem = function(ul, item) {
return $('<li></li>')
.data('item.autocomplete', item)
.append(item.desc)
.appendTo(ul);
};
});
Or there is an example on the jQuery site using remote JSONP as a source and customizes the label and value needed to populate the list.
Well, the only way I can think of to do this is by using php with fopen and fread, then format the data.

JQuery UI Autocomplete Syntax

Can someone help me understand the following code? I found it here.
It takes advantage of the JQuery UI Autocomplete with a remote source. I've commented the code as best I can and a more precise question follows it.
$( "#city" ).autocomplete({
source: function( request, response ) {
//request is an objet which contains the user input so far
// response is a callback expecting an argument with the values to autocomplete with
$.ajax({
url: "http://ws.geonames.org/searchJSON", //where is script located
dataType: "jsonp", //type of data we send the script
data: { //what data do we send the script
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) { //CONFUSED!
response(
$.map(
data.geonames, function( item ) {
return {
label: item.name+(item.adminName1 ? ","+item.adminName1:"")+","+item.countryName,
value: item.name
}
}
)
);
}
});
}
});
As you can see, I don't understand the use of the success function and the response callback.
I know the success function literal is an AJAX option which is called when the AJAX query returns. In this case, it seems to encapsulate a call to the response callback? Which is defined where? I thought by definition of a callback, it should be called on its own?
Thanks!
The response object as defined by the documentation ("Overview" page):
A response callback, which expects a
single argument to contain the data to
suggest to the user. This data should
be filtered based on the provided
term, and can be in any of the formats
described above for simple local data
(String-Array or Object-Array with
label/value/both properties). It's
important when providing a custom
source callback to handle errors
during the request. You must always
call the response callback even if you
encounter an error. This ensures that
the widget always has the correct
state.
so, the 'response' argument is actually a callback, which must be called upon success of the ajax retrieval of autocomplete items.
Since your data will come back via AJAX, your code must update the widget manually. jQueryUI provides an argument as a function so that your code can do that update by calling the function.
You can see the response object defined in the declaration of the function used for the source option:
source: function( request, response )
You could even take the AJAX call out of the equation and do something like this:
source: function(request, response) {
response([{label:'foo', value: 'foo'},{label:'bar', value:'bar'}]);
}
Would immediately call the response callback with an array of label/value pairs for the widget.

Resources