JQM submit form with AJAX cause errors with redirect - jquery-mobile

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.

Related

JQuery Mobile Linked Listview not working properly?

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.

Facebook and Twitter widgets disappear on navigation (Rails)

I have a fb-like-box and a twitter-timeline, the official facebook page and twitter widgets. However, on actual navigation (the links in the sidebar do an ajax load), for example on clicking the logo, these two widgets vanish into thin air.
On refreshing the page, the widgets once again appear as expected.
<div id="social_bar">
<div id="facebook_like_box">
<div class="fb-like-box" data-href="https://www.facebook.com/Gx.Edg" data-width="234" data-height="500" data-colorscheme="light" data-show-faces="true" data-header="true" data-stream="false" data-show-border="true"></div>
</div>
<a class="twitter-timeline" href="https://twitter.com/gxEDGE" data-widget-id="308092518074040321"></a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</div>
The root cause is how Turbolinks interacts with header scripts. #peteykun offers the correct solution in his answer, though it is out of date and lacks an elaborate explanation. At the time of this writing, Rails 5 uses Turbolinks 5.
When you visit a page on your Rails site for the first time (or refresh the page), the page is fetched normally without interference from Turbolinks. The expected browser events fire, the JavaScript executes, and everything renders properly. The trouble starts when you navigate from that page to another page on the same domain (i.e. clicking a link). When that happens, Turbolinks intercepts the new page request and makes a slightly different request that is faster. Glossing over the details, the end result is that expected browser events do not fire as they normally would. No events, no JavaScript. No JavaScript, no rendering. Per the Turbolinks GitHub:
You may be used to installing JavaScript behavior in response to the
window.onload, DOMContentLoaded, or jQuery ready events. With
Turbolinks, these events will fire only in response to the initial
page load—not after any subsequent page changes.
The best and simplest solution is to listen for Turbolink's events instead of the standard browser events.
Fortunately, there's a website authored by user #reed of GitHub which is dedicated to rewriting a wide variety of commonly-used JavaScripts to be compatible with Turbolinks. Unfortunately, the solutions currently on the site were written for an earlier version of Turbolinks and will not work out-of-the-box. Assuming they haven't updated the site yet, you'll need to make some changes.
First, change all event bindings of the form page:* to turbolinks:*. The event namespaces were changed in Turbolinks 5. This is the only change required to get #reed's Twitter coffeescript (Solution #2) to work. As for the Facebook coffeescript, there's no such thing as a turbolinks:fetch or turbolinks:change event, but that's okay. Read on for a more elegant solution.
Reed's Facebook coffeescript uses Javascript to transfer the #fb-root element from the body of the old page to the new one. As I understand it, this is done to preserve the Facebook functionality. Turbolinks 5 has a new feature that allows you to mark a page element as permanent. User #pomartel mentioned this here, and I believe this is a much more elegant solution. Simply add the data-turbolinks-permanent attribute to the #fb-root div, and we remove the need for the saveFacebookRoot and restoreFacebookRoot functions.
The complete Facebook solution is below. In the <body>:
<body>
<div id="fb-root" data-turbolinks-permanent></div>
In the <head>:
<%= javascript_include_tag 'facebook_sdk', 'data-turbolinks-track': 'reload' %>
And the facebook_sdk.coffee file, which belongs in ./app/assets/javascripts:
$ ->
loadFacebookSDK()
bindFacebookEvents() unless window.fbEventsBound
bindFacebookEvents = ->
$(document)
.on('turbolinks:load', ->
FB?.XFBML.parse()
)
#fbEventsBound = true
loadFacebookSDK = ->
window.fbAsyncInit = initializeFacebookSDK
$.getScript("//connect.facebook.net/en_US/sdk.js")
initializeFacebookSDK = ->
FB.init
appId : 'YOUR-APP-ID-HERE'
status : true
cookie : true
xfbml : true
autoLogAppEvents : true
version: 'v2.11'
Don't forget to add the Facebook and Twitter coffeescripts to the precompiled asset pipeline!
The problem was a ruby gem that is bundled by default, called Turbolinks.
The solution is found in the Turbolinks Compatibility Project:
Facebook Like Box
Twitter Widget

Sending form contents as both html and ajax?

I have an admin form that updates a model via a html submit. I'd like to be able to send the form's contents to an Ajax modal dialog for a 'preview' via a link or button in the admin form.
Is there a way to send the form's contents to the modal dialog via Ajax without breaking the html submit? So far all I can do is get the data into the modal as html which breaks the js rendering. All the Ajax submit examples I find attach to the form which will break the html submit.
Suggestions and/or pointers are appreciated.
We are using Rails 3.2.12 for what it's worth.
I suppose it depends on how you are rendering your modal. If you're doing it server side and just need to get the form values to your ajax controller action you could do something like this with jquery"
$.post(ajaxUrl + "?" + $("#myform").serialize())
to generate a query string of your form values that you could sent to you ajax model.
Or if you're building the modal client side try
$("#myform").serializeArray()
to get an array of name, value pairs
This is what it took to get this to work under Rails 3.2.12
View:
<%= link_to 'Preview Promotion UI', admin_preview_promotion_url, id: :promotion_preview %>
The above link is inside the form do/end.
Javascript in application.js
$("#promotion_preview").live('click', (function (event) {
event.preventDefault();
$.post("/store/admin/promotions/preview",
$(event.currentTarget.parentElement).serialize().replace('=put&', '=post&'),
{},
"script"
);
}));
Rails.js injects some hidden code in the page that sets the type of response to PUT and then gets in the way of the routing. At least in this case simply replacing PUT with POST fixes things.
With this bit of code I can post my form updates as usual and activate a modal dialog "preview" using the form data.

Anchor link to open jquery mobile popups just redirects

I previously used javascript dialogs for confirmation on a mobile web app, but am now trying to switch over to using the new popups feature in JQM 1.2. My initial test doesn't work - no popup appears and I'm simply redirected to the anchor I'm trying to call.
My test code is simple, albeit a bit obfuscated because I'm using haml:
%a{:href => "#popupBasic", :"data-rel" => "popup"} Show popup
%div{:id => "popupBasic", :"data-role" => "popup"} Basic popup div
That said, I don't believe the haml is causing the issue based on reading the final HTML output. Both elements are at equal depth and contained within the element.
In addition, the div does "popup" without issue when I use the following at the console:
$( "#popupBasic" ).popup( "open" )
That makes me believe that the issue lies somewhere in the link or the URL handling. When I do click the link, it instead takes me straight to
http://localhost:3000/#popupBasic
Any ideas on how I should be handling the URL differently so that it shows the popup as intended?
After realizing the problem was probably some part of my Javascript, I went through and tried turning off each bit of javascript individually, until I figured out that the problem was with this in my application.js file:
$(document).bind("mobileinit", function(){
$.mobile.linkBindingEnabled = false;
});
which prevents all anchor click handling. Obviously now that I've removed this code the anchor links are working properly. Of course, that means I'm now left with trying to figure out why I added that in the first place and what I just broke by removing it...

How do I submit a form with a link in ASP.Net MVC?

I have a HTML form, and I have a Controller Action that accepts the POST request. Everything works with a regular submit button, but I would like to submit the form with a link (<a>-tag) instead, to be able to further control the formatting. Is there any way of doing this nicely built into the ASP.NET MVC Framework, or should I write my own extension method? Is it even possible to do this without javascript (I will use AJAX in the future, but it has to work without).
Here is a complete example. Note that this particular example does something fairly important: it has a fallback for browsers with JavaScript disabled.
If javascript and jQuery is enabled this effectively replaces all submit-buttons with links:
$("input:submit").hide().each(function (index, Element) {
var elm = $(Element);
elm.after($("<a href=#>" + elm.val() + "</a>")
.click(function () { elm.click(); })
);
});
Based on post linked to in the accepted answer.
I'm not aware of a helper and as far as I know it is impossible to submit a form using an anchor tag without using javascript.
You cannot 'submit a form' using a link (<a> tag) without Javascript. The javascript is going to generate a standard POST request (same as clicking a submit form button) behind the scenes.
There are other workarounds for those with JS disabled, look at what #Craig Stuntz submitted.

Resources