jquery mobile 1.4 not updating content on page transition - jquery-mobile

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

Related

Multiple AJAX in one window.onload

I'm sure this question must have been asked before but I'm really struggling
to find the answer anywhere so have finally given up and will consult
the stackoverflow community - hopefully there's someone out there who's seen
it all before and can help me out!
I have a webpage which needs to make some function calls as the page loads. It is an ajax method which calls the Json method from the controller which supplies the data that will be used to draw the chart.
I've successfully displayed one chart on my page but still need to display two more charts. Is it possible to have multiple ajax methods on window.onload function?
Here is my code so far.
window.onload = function () {
$.ajax(
{
datatype: "json",
type: "POST",
url: "/CRM/GetIndustryTypeData",
data: JSON,
success: function (data) {
IndTypePieChart(data);
},
error: function () { alert("Error"); }
});
}
Stephen Muecke's answer will work 100%. Get rid of window.onload = function(){ and have any number of $.ajax() calls - positioned at the bottom of the page or wrapped in $(document).ready(){
}).

Preload page into turbolinks transition cache

I'm using turbolinks to simulate a "single-page" app. The app is acceptably quick once pages are cached, however the first clicks are too slow. Is there a way to pre-fill the transition cache by loading some pages in the background?
I'm going to be looking into hacking into the page cache, but wondering if anyone has done this before.
(If this seems unusual, well, just trust that I'm doing this for good reason. Turbolinks gets nearly the performance of a far more complex implementation and overall I'm quite happy with it.)
UPDATE: So it seems like this SHOULD be relatively easy by simply adding entries to the pageCache of Turbolinks, something like:
$.ajax({
url: url,
dataType: 'html',
success: function(data) {
var dom = $(data);
Turbolinks.pageCache[url] = {
...
}
}
});
however it doesn't seem possible to construct a body element in javascript, which is required. Without out that, it doesn't seem like I can't construct the object that is stored in the cache without the browser first rendering it.
Any ideas beyond hacking more into Turbolinks?
UPDATE 2: There was the further problem that pageCache is hidden by a closure, so hacking Turbolinks is necessary. I have a solution that I'm testing that leverages iFrames - seems to be working.
First Hack Turbolinks to allow access to pageCache, the end of your turbolinks.js.coffee should look like this.
#Turbolinks = {
visit,
pagesCached,
pageCache,
enableTransitionCache,
enableProgressBar,
allowLinkExtensions: Link.allowExtensions,
supported: browserSupportsTurbolinks,
EVENTS: clone(EVENTS)
}
Then implement a fetch function. This is what you were thinking about, we can use DOMParser to convert string into DOM object.
function preFetch(url) {
$.ajax({
url: url,
dataType: 'html'
}).done(function(data) {
var key = App.Helper.getCurrentDomain() + url;
var parser = new DOMParser();
var doc = parser.parseFromString(data, "text/html");
Turbolinks.pageCache[key] = {
url: url,
body: doc.body,
title: doc.title,
positionY: window.pageYOffset,
positionX: window.pageXOffset,
cachedAt: new Date().getTime(),
transitionCacheDisabled: doc.querySelector('[data-no-transition-cache]') != null
};
});
};
Usage:
$(function() {
preFetch('/link1'); // fetch link1 into transition cache
preFetch('/link2'); // fetch link2 into transition cache
});

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/

Ajax call on ruby on rails

I have a ajax call using ruby on rails. I'm getting a success but I don't know how to use the data result of the ajax call.
$.ajax({
url: "/search/get_listing?listing_id" + id,
dataType: 'JSON',
success: function(data) {
var listing = JSON.parse(data);
$("#modalPrice").html(data.city);
}
});
Controller:
#listings_data = Listings.find_by(id: params[:id])
render :json => #listings_data.to_json
Using data.city won't work. I'm expecting to get the values retrieve from the model by simply putting . on the variable
var listing = JSON.parse(data);
Still no luck. Help guys. Thanks!
JSON.parse is Ruby code, API of JSON gem. How can you guys use that in Javascript :)
jQuery can process JSON object data directly. Just use:
success: function(data) {
$("#modalPrice").html(data.city);
}
For example, you can render in the controller:
render :json => { :city => #listings_data }
On the JS:
success: function(data) {
var listing = data.city;
}
I'm having similar problems everytime I use AJAX in rails since the response seems to differ depending on how you return the value or how you are handling the success in JS. Try this:
success: function(data, status, xhr) {
var listing = JSON.parse(xhr.responseText);
$("#modalPrice").html(data.city);
}
I usually use Firebug (Firefox Plugin) to set a breakpoint in my success handlers to check the arguments where exactly the response is in. Sometimes it's in the first value, sometimes in some other and then it may be xhr.response or even xhr.responseText. It's confusing me every time.
To use Firebug for this, press F12 on your page, select the 'Script' pane and find the code you want to check. Click next to the row number of your code where you want your breakpoint. In this case, you could've chosen the var listing line. When the code is executed (after your click), the browser will stop there and you can check the passed arguments on the right side.

autocomplete showing self.element.propAttr error

I am using Jquery ui Autocomplete.But it show error autocomplete showing self.element.propAttr error.
this is my ajax code
$.ajax({
url: "persons.xml",
dataType: "xml",
success: function( xmlResponse ) {
var data = $( "person", xmlResponse ).map(function() {
return {
value: $( "name", this ).text()
};
}).get();
$( "#birds" ).autocomplete({
source: data,
minLength: 0
});
}
});
I am using xml for response but that doesnot seem to be the problem it seems some function in javascript is deprecated.
Can anyone give me any solutions for this?
Add this lines in front of your statement:
jQuery.fn.extend({
propAttr: $.fn.prop || $.fn.attr
});
I was facing this problem when refactoring my javascript and found that the problem was I removed jquery.ui.core.js, and instead was using only jquery-ui-1.9.1.custom.min.js.
I created this file using the Download Builder at the Jquery UI website with everything checked. Correct me If I am wrong but jquery-ui-1.9.1.custom.min.js should have contained all the javascript necessary to run all the jquery ui addins (in this case autocomplete was failing).
Adding the reference back to jquery.ui.core.js fixed the bug.

Resources