JQuery Mobile Linked Listview not working properly? - jquery-mobile

So, I'm making an mobile e-commerce app using JQuery Mobile and I'm having the following issue.
After logging in, the app takes the user to the store area which consists on a linked listview populated with JSON data. Now when the store page first initialises, the links don't work, but when I refresh the page they work just fine. Does anyone know why I'm getting this behaviour?.
Note: I'm using a multipage template, to navigate from #store page to #product page.
Here the javascript I'm using for this:
$(document).on("pagebeforecreate","#store", function() {
getProducts('',
function(data){
let products = data.products;
storeProducts(products);
$(".product-list").html('');
$.each(products, function(i, item){
$(".product-list").append(`
<li>
<a href="#product" data-index="${item.prod_id}">
<img src="${item.picture}" alt="">
<h2>${item.prod_name}</h2>
<p>${item.prod_desc}</p>
<small>Price: <strong>€${item.unit_price}</strong></small>
</a>
</li>
`).listview("refresh");
});
},
function(e){
console.log(e);
},
function(data){
console.log('always');
});
});
function getProducts(param, success, error, always){
$.ajax({
type:'GET',
url:`./ajax/products-ajax.php?${param}`,
dataType: 'json',
async:true
}).done(function(data){
success(data);
}).fail(function(e){
error(e);
}).always(function(data){
always('always');
});
}
Thanks in advance.
UPDATE:
Hi deblocker,
Thanks again for your answer. There's no errors showing up in the console log. I tried turning off the cache in my browser and still have the same issue. Let me see if I can explain better what I am trying to do.
I am trying to make this app using JQuery Mobile for the frontend and PHP for the backend. I've got an index.php with links to get you either to login or register. Let's say that you select the login option, that's going to take you to login.php where there is a form which when you submit it makes an ajax request to the server to do authentication. Supposing the response is successful, that'll redirect you to store.php which is where the listview lives. As I say before, when you land in store.php after logging in the links in the listview don't work, however if you refresh the page the work as they are supposed to.

Here is what was causing the problem:
When redirecting the user to store.php after authentication, JQuery Mobile's Ajax navigation was grabbing the first page I had in there (store.php is multipage, containing #store and #product) and injecting it on top of what already was in the DOM. Of course when I clicked on my links these didn't work since there was no page containers with id = "product" in the DOM. When I refreshed the page JQuery mobile made a http request to the server, this time getting the full store.php with both pages #store and #product, hence the links would work as they were supposed to.
My solution: have both #store and #product as external pages. By separating them and calling them as external pages I avoid this issue with the Ajax navigation.

Related

JQM submit form with AJAX cause errors with redirect

I'm using prestashop (1.4), I've installed mobile theme module for mobile client that uses jqm (1.3.2) on top of jquery (1.9.1)
Now, in the mobile version, The paypal module fails when clicking on a form that suppose to load the paypal page - it display 'error loading page' on the screen.
I tried to compare the HTTP request headers on the desktop and the mobile and found that there is an extra 'X-Requested-With:XMLHttpRequest' header in the mobile.
Therefore I figured that the jqm grabs all form submit and send them as ajax requests.
I think this cause a problem: the srv code redirect to paypal.com, but since it's an ajax request it cannot load the page...
or am I missing something???
The question is: how to prevent jqm from garbing the form and submitting it with ajax?
any idea, or solution to this issue is more than welcome.
download the file http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.js
set your code to use this file.
in line: 4863, after $.mobile.document.delegate( "form", "submit", function( event ) {
add the following lines:
prventAjax = $(this).attr("prventAjax");
if (prventAjax == 'true') return true;
now in the form orignal html form add attribute: prventAjax='true'
i.e.
<form action="submit.php" method="post" prventAjax='true'>
this solves the problem for me.

jQuery mobile finds elements from first page when on second page

I've got a two page jQuery mobile app, and within the init function, the following code..
Call to the init function
$(document).on('pageinit', function(){
MyPages.init();
});
init: function() {
$('td[id$="drops"]').each(function() {
console.log("Element: " + $(this).attr('id'));
}),
};
I have elements in page one that match the above, such as '#early_drops', '#late_drops', etc. These elements do not exist on page 2, but when page 2 loads, the elements are displayed in the console just like when page 1 is loaded. What am I missing here?
Thanks very much,
-Adam vonNieda
By default jQuery loads pages using AJAX into the existing page in order to allow the animated transitions. If you don't want this you just need to 'turn off' the AJAX loading.
See description here: http://view.jquerymobile.com/1.3.2/dist/demos/widgets/links/
Links that point to other domains or that have rel="external", data-ajax="false" or target attributes will not be loaded with AJAX. Instead, these links will cause a full page refresh with no animated transition. Both attributes (rel="external" and data-ajax="false") have the same effect, but a different semantic meaning: rel="external" should be used when linking to another site or domain, while data-ajax="false" is useful for simply opting a page within your domain from being loaded via AJAX.
You can also disable AJAX across the entire app by default using global configuration: http://api.jquerymobile.com/global-config/

Passing data between pages with jQuery Mobile?

So I've just started learning jQuery Mobile, and I've learned how it loads all links via ajax without actually loading the next page. Several of my pages use forms and GET to pass data on to the next page-- How can I do this while using jQuery Mobile?
One thing that I think is cool about JQM is that you don't have to use parameters to pass data between pages. Since you're in the same DOM as the first page, you can access data using plain old variables, i.e.
field1 = $('[name=field1]').val();
field2 = $('[name=field2]').val();
And so long as you're using the ajax feature of JQM you could do the following in the next page:
$('.title').text(field1);
I made a jsfiddle example for you.
Other ways would be to use the localStorage or sessionStorage api or there are also some plugins mentioned in the docs.
page params
JQM router plugin
Commonly, there 2 method for transfer parameter between jQuery Mobile page.
Modify Ajax address at first page, and parse the ajax to get parameter in next page.
Using HTML5 sessionStorage, a kind of WebStorage, to transfer parameter.
This is the method use ajax address to transfer parameter.
How to pass and get Parameters between two Pages in Jquery Mobile?
Using sessionStorage/localStorage to transfer parameter, you can add this code at first page,
<a href="#page_Parameter1" onclick="sessionStorage.ParameterID=123">
Before go to next page, parameter id is storaged into sessionStorage.
</a>
In next page, you can use this method to take parameter content,
$('#page_Parameter1').live('pageshow', function(event, ui) {
alert('Parameter ID: ' + sessionStorage.ParameterID);
});

jQuery Mobile Page refresh mechanism

I'm having a lot of pain understanding how jQuery Mobile handles pages refresh after an ajax update.
I'm having a two pages - unique file site: a search engine.
First page is a search field. Submit triggers a JSON call and parser which updates the second page: results.
for now i'm using: $.mobile.changePage( $('#result') ); which does the job great from search field to result page.
However:
If I reuse it from result page for next/prev pages ( new json call, new parse, new added nodes in the DOM );
Jquery Mobile just don't "paint" the newly added nodes.
can anyone explain, please the use and distinction of
1- $.mobile.page()
2- $.mobile.changePage()
3- $.mobile.refresh()
or give me a hint on how I should handle page changes.
thanks!
function refreshPage()
{
jQuery.mobile.changePage(window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
});
}
Taken from here http://scottwb.com/blog/2012/06/29/reload-the-same-page-without-blinking-on-jquery-mobile/ also tested on jQuery Mobile 1.2.0
Please take a good look here: http://jquerymobile.com/test/docs/api/methods.html
$.mobile.changePage() is to change from one page to another, and the parameter can be a url or a page object. ( only #result will also work )
$.mobile.page() isn't recommended anymore, please use .trigger( "create"), see also: JQuery Mobile .page() function causes infinite loop?
Important:
Create vs. refresh: An important distinction
Note that there is an important difference between the create event and refresh method that some widgets have. The create event is suited for enhancing raw markup that contains one or more widgets. The refresh method that some widgets have should be used on existing (already enhanced) widgets that have been manipulated programmatically and need the UI be updated to match.
For example, if you had a page where you dynamically appended a new unordered list with data-role=listview attribute after page creation, triggering create on a parent element of that list would transform it into a listview styled widget. If more list items were then programmatically added, calling the listview’s refresh method would update just those new list items to the enhanced state and leave the existing list items untouched.
$.mobile.refresh() doesn't exist i guess
So what are you using for your results? A listview? Then you can update it by doing:
$('ul').listview('refresh');
Example:
http://operationmobile.com/dont-forget-to-call-refresh-when-adding-items-to-your-jquery-mobile-list/
Otherwise you can do:
$('#result').live("pageinit", function(){ // or pageshow
// your dom manipulations here
});
I posted that in jQuery forums (I hope it can help):
Diving into the jQM code i've found this solution. I hope it can help other people:
To refresh a dynamically modified page:
function refreshPage(page){
// Page refresh
page.trigger('pagecreate');
page.listview('refresh');
}
It works even if you create new headers, navbars or footers. I've tested it with jQM 1.0.1.
I found this thread looking to create an ajax page refresh button with jQuery Mobile.
#sgissinger had the closest answer to what I was looking for, but it was outdated.
I updated for jQuery Mobile 1.4
function refreshPage() {
jQuery.mobile.pageContainer.pagecontainer('change', window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
// 'reload' parameter not working yet: //github.com/jquery/jquery-mobile/issues/7406
});
}
// Run it with .on
$(document).on( "click", '#refresh', function() {
refreshPage();
});
I solved this problem by using the the data-cache="false" attribute in the page div on the pages I wanted refreshed.
<div data-role="page" data-cache="false">
/*content goes here*/
</div>
In my case it was my shopping cart. If a customer added an item to their cart and then continued shopping and then added another item to their cart the cart page would not show the new item. Unless they refreshed the page. Setting data-cache to false instructs JQM not to cache that page as far as I understand.
Hope this helps others in the future.
This answer did the trick for me http://view.jquerymobile.com/master/demos/faq/injected-content-is-not-enhanced.php.
In the context of a multi-pages template, I modify the content of a <div id="foo">...</div> in a Javascript 'pagebeforeshow' handler and trigger a refresh at the end of the script:
$(document).bind("pagebeforeshow", function(event,pdata) {
var parsedUrl = $.mobile.path.parseUrl( location.href );
switch ( parsedUrl.hash ) {
case "#p_02":
... some modifications of the content of the <div> here ...
$("#foo").trigger("create");
break;
}
});

jQueryMobile page events not firing when navigating to a different html page

I'm trying to navigate to a different .html page using
$.mobile.changePage( "PlayGame.html", { transition: "slideup"}, true, true)
PlayGame.html is being transitioned to, however, none of the following are firing:
$(document).bind("mobileinit", function()
{
alert(1);
});
$('#gamePage').live('pageinit',function(event, ui)
{
alert('pageinit');
});
$('#gamePage').live('pagebeforeshow',function(event, ui)
{
alert('booooo');
});
However, if I do window.location.href = "PlayGame.html" then everything fires accordingly.
What am I missing?
Thanks
Tom
If the code in your example is in the <head> of the PlayGame.html document then it will not be included when the jQuery Mobile framework grabs the page via AJAX. That is why your custom code runs when you load the whole page but not when clicking on a link from another page.
You will want to either put your custom JavaScript in a single file and include it on every page (so it will be available no matter what page the user enters your site from) or you will want to move the custom JavaScript for each page into the <div data-role="page"> element for each page (so it will be included when the page is pulled into the DOM).
The reason is that when you click on a link to an external file, jQuery Mobile uses AJAX to pull out the first instance of a <div data-role="page"> element and places that element in the current DOM, everything else in the document is discarded.
Here is some suggested reading about how jQuery Mobile navigation works: http://jquerymobile.com/demos/1.0rc2/docs/pages/page-navmodel.html

Resources