Very new to code in general so apologies in advance if i dont explain myself properly,
But I have a form, that actions a piece of JavaScript on submit.
If the form validates successfully then it calls a php file for server side processing.
Once the server side processing is complete the php file returns some data (a url) which the user is then redirected to (client side)
This all works fine on desktop (chrome, IE, FF) and via modern mobile devices, however the redirect is not working on some devices (blackberry for one), and a i assume other older devices. Instead of the redirect URL going straight into the address bar, it is being placed after the url of the original page - as such causing the user to be redirected to a page that of course doesnt exist.
Below is the script that is called on submit. Again apologies if none of the above makes sense...I am very new to all this:
$(function () {
$('#wait').hide();
$('form#leads_form').on('submit', function (e) {
if (validateFrm()) {
$(":submit", this).attr("disabled", true);
$('#wait').show();
var jqxhr = $.ajax({
type: 'post',
timeout: 300000,
url: 'sell-save-leads.php',
cache: false,
data: $('form').serialize(),
success: function (data) {
//alert("Submit success: " + data);
window.top.location.href = data;
}
});
} else {
//alert("validation errors");
$('#wait').hide();
}
e.preventDefault();
});
});
If anyone is able to help or offer some advice that would be great.
As your form is located in an iFrame I suggest you to use this jQuery plugin to send messages from an iframe to its parent:
http://benalman.com/projects/jquery-postmessage-plugin/
With this you could send a message from inside your success function, containing the new url, and catch it in the parent window.
You can also use
window.top.location.assign(data);
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window.location
Related
I've encountered an issue where a jquery ajax post method works on chrome but does not work on safari or firefox. I've looked through all the other similar posts and they don't solve the problem. Whenever I run the ajax code, it just returns the entire HTML of the page the form is found on.
Here's my javascript:
$("#piece-form").submit(function(e)
{
e.preventDefault();
// gets which submit button was clicked
var selectedButton = $(this).find("input[type=submit]:focus");
var url = selectedButton.attr("name");
var formData = new FormData(this);
$.ajax
(
{
type: "POST",
url: url,
data: formData,
cache: false,
processData: false,
success: function(data)
{
if(data == "Success!")
{
$("#error-box").css("display", "none");
$("#success-box").html("Success! Publishing...");
$("#success-box").css("display", "block");
}
else
{
$("#success-box").css("display", "none");
$("#error-box").html(data);
$("#error-box").css("display", "block");
}
}
}
)
});
No matter the content of the PHP file the function points to, it doesn't work as planned. I've tried making a PHP file with a single echo line and I still run into the same problem. I've implemented an error block in the ajax as well and it returns nothing. I also don't receive an error in the console other than: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/" in Firefox
Edit: I've added contentType:false and it still isn't functioning properly on Firefox and Safari
Have you tried wrap your code in document ready?
Also as much as i know now it is correct to use on():
$( document ).ready(function() {
$("#piece-form").on('submit', function(e){
//your main code here
});
});
For now it does not looks like there would be any issue. ..
I finally found the answer.
The error is in the following line of code:
var selectedButton = $(this).find("input[type=submit]:focus");
var url = selectedButton.attr("name");
For some reason, Firefox and Safari don't properly get the value of "selectedButton" (although Chrome does) resulting in the url variable being incorrectly set. In order to circumvent this, I did the following:
$(".piece-button").click(function (){
url = $(this).attr("name");
})
I needed the submittedButton method because I had two submit buttons for the form and was trying to find which one was clicked. This alternate method does that and is transferrable across all three browsers I have tested. This may not be an optimal solution to the two button submit issue but it worked for me and now the ajax works without a hitch.
Though you have got the solution but from interest I am sharing mine as I have just encountered same problem and got the workaround by adding event.preventDefault(); after success. Example code is given
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data: {
name: $('#nameInput').val(),
email: $('#emailInput').val()
},
type: 'POST',
url: '/post_for_db',
success: function(data) {
console.log(data)
$("body").html(data);
// This will navigate to your preferred location
document.location = '/render_table_from_db';
},
event.preventDefault(); // solution is this for me
});
});
I am working on a web Spring MVC 4 application for my end of studies project, the application should connect web and android clients.
I used #RestController to help android app communicate easily via json. I am trying to catch connection failure ex:404 in both web or mobile app, even in the web application i tried to make almost all communication with the server via Ajax hoping to make user more relaxed (Progress bars, Live info hints...) but, one of the problems in countries that after using event.preventDefault() from jQuery, i can't get over it in next actions and the response pages loaded and kept unseen! for example here is my login page example:
login.js
jQuery(document).ready(function ($) {
$("#login-form").submit(function (event) {
//Do somthing...
// Call login function
logViaAjax(event);
// Prevent the form from submitting via the browser.
return false; //Or using event.preventDefault()
});
});
// logViaAjax function
function logViaAjax(event) {
var logObj = {};
logObj["username"] = $("#username").val();
logObj["password"] = $("#password").val();
//the response
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
url: "/login",
data: logObj,
dataType: 'text',
timeout: 10000,
success: function (data) {
if (data.indexOf("login-box") !== -1) {
showLogFail();
}else{
window.location.reload();
//I dont need to reload the page because this gives me login page again... May be if there is a way to get the URL from data!?
}
},
error: function () {
showWarning();
}
});
I am using Spring Security 4 to handle authentification and we know that it gives url ex:/login?fail for failure and get the requested page if succeed and i recently knew that it redirect even before getting in the loginUrl my ex /login. I tried to test if the user logged in on server side and send json response but this could leads to lose the page before requesting login.
I think i should test in the success: function() if url loaded in the jQuery(but not showed) contains ?fail or not, to inform user to change log or password. Else, if it do not, the page user need is charged in the back and all what i need is to show it.
UPDATE
After those little changes all what I need to make is just to keep the page beyond the login page and reshow it. Take note that this function is automatically offered by Spring Security but it still running on background. Ex in my case when user click /messenger the app redirect him to /login to login, if he fail login it gives /login?fail but this page is unseen due to JQuery, else he login successfully it send him to /messenger again…
Try this
var flag;
jQuery(document).ready(function ($) {
$("#login-form").submit(function (event) {
//Do somthing...
// Call login function
logViaAjax(event);
if(flag.status == 404){
return false;
}
});
});
function logViaAjax(event) {
var logObj = {};
logObj["username"] = $("#username").val();
logObj["password"] = $("#password").val();
//the response
flag = $.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
url: "/login",
data: logObj,
dataType: 'text',
timeout: 10000,
success: function (data) {
//Here to move to the page unseen if success and show error hint if it fail...
},
error: function () {
showWarning(); //Show error alerts, this part is DONE!
}
});
Changes Made
► Assigned the AJAX to a variable and dded a condition in the jQuery(document).ready
AJAX - The onreadystatechange Event
Demo Fiddle to show 404 error
I have a link redirecting to an intranet direction:
Go
Only users in intranet can access, otherwise they get a 404 error. I want to know if the the url is valid before redirecting, this way users out of intranet won't get the 404 error but a message saying 'You don't have access'. How can I do this with jquery or javascript?.
EDIT:
Well, thank you very much, but unfortunately any method does not work for me. Sorry, I didn't mention that website and intranet url are in differente domain.
Finally I had to validate user IP in codebehind and write or not the intranet url.
You could make an ajax request first, something like:
$.ajax({
url: "http://10.2.68/name/",
context: document.body,
success: function(){
window.location = "http://10.2.68/name/";
}
});
That could be run by binding to the click event on the link.
Not sure if it will work due to cross origin stuff, but might be a good place to start.
You can use this jQuery plugin to make a head request to the remote file, if it comes back with something it is good (and you can display it for instance) otherwise don't show it
Plugin:
http://binarykitten.me.uk/dev/jq-plugins/88-jquery-plugin-ajax-head-request.html
Perhaps use an htaccess file to detect the internal network instead?
The best answer would be to disable the link if it's inactive, before the user tries to click it (why make them try?).
jQuery(function($) { // make sure dom is ready
$.ajax( {
url: url,
//dataType: 'JSONP', //might need this?
complete: function(xhr) { // use complete so it fires on error OR success
if( xhr.status == 200 || xhr.status == 304 ) {
$('#link').addClass('valid');
}
else {
$('#link').addClass('invalid').click(function() { return false; });
}
}
});
});
But if you don't want the call because there are going to be thousands of users looking at the page every minute...
jQuery(function($) { // make sure dom is ready
$('#link').click(function() {
$.ajax( {
url: url,
//dataType: 'JSONP', //might need this?
success: function() {
window.location = url;
},
error: function() {
// does this work with JSONP? be sure to check!
window.alert('could not connect');
}
}
});
});
Assuming your anchor has an ID:
<a id="lnkGo" href="http://10.2.68/name/">Go</a>
And your jQuery code might look like this:
$("#lnkGo").bind("click", function() {
var $that = $(this);
$.ajax({
url: $that.attr("href"),
statusCode: {
200: function() {
window.location = $that.attr("href")
},
404: function () {
alert("Sorry, page is unavailable...");
}
}
});
return false;
});
Also, please keep mind that this won't work on cross-domain issue. The url has to be same as the current domain.
I have added the required meta tags to my web app so that it can be launched on an iPhone from the springboard with no safari elements (address bar etc).
However, my login page works via JS, with the response coming back as JSON.
In Safari, when not launched as a web app, the redirect works fine (using window.location).
When launched as a web app, the redirect doesn't seem to work properly. The screen will refresh but be on the same page.
Is this a limitation of a web app or (as I suspect) am I doing it wrong?
This is the code that responds to the ajax post
genericPost: function (f, ajaxLoad) {
if (ajaxLoad == undefined)
ajaxLoad = true;
var form = $(f);
var data = form.serialize();
var action = form.attr("action");
$.ajax({
type: 'POST',
url: action,
data: data,
success: function (response) {
if (response.worked) {
//navigate to the next required page
//Notify.showMessage(response.message);
if (response.redirect) {
if (ajaxLoad) {
Notify.showMessage(response.message, "ok");
var back = response.direction == "back";
$.mobile.changePage(response.redirect, "slide", back, true);
}
else {
window.location = response.redirect;
}
}
else {
Notify.showMessage(response.message, "ok");
}
}
else {
Notify.showMessage(response.message, "error");
}
},
dataType: "json",
error: function () {
Notify.showMessage("Could not submit your form at the time. Please try again. Please try again", "error");
}
});
}
Thanks
Ok, so the window.location was a red herring.
The issue was that ios seems to send a different user agent string when running full screen, one that IIS did not like.
IIS therefore decided that this browser did not support cookies or any of that stuff so the authentication token was failing.
This was fixed by adding a app_devices folder to my project and a .browser file.
I need for a php file to process when the user click a link/go back/exits a page. Its part of a saving user info process. if i do a jquery unload how would I fire the php file to load and process.
jQuery(window).bind("unload", function() {
// what should i add?
});
$(document).ready(function() {
$(':input',document.myForm).bind("change", function() {
setConfirmUnload(true);
}); // Prevent accidental navigation away
});
function setConfirmUnload(on) {
// To avoid IE7 and prior jQuery version issues
// we are directly using window.onbeforeunload event
window.onbeforeunload = (on) ? unloadMessage : null;
}
function unloadMessage() {
if(Confirm('You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost.')) {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
}
Make sure you have upgraded version of jQuery. jQuery version 1.3.2 had a bug:
Ticket #4418: beforeunload doenst work correctly
Or use native function:
window.onbeforeunload = function() {....}
I'm guessing a synchronous AJAX call might work.
$.ajax({
async: true,
url: '/foo/',
success: function(data) {
// Finished.
}
});
Of course, keep in mind there's no guarantee any of this will ever happen. My browser may crash. My computer may even power down. And of course I may disable JavaScript. So you'll definitely need a server-side way of handling this in case the convenient JavaScript technique doesn't actually work.
You should use the beforeunload event. You can fire a synchronised ajax request in there.
$(window).bind('beforeunload', function() {
$.ajax({
url: 'foo',
async: false,
// ...
});
});
Be aware that onbeforeunload is not supported by some older browsers. Even if this technique works, I'm not sure how long you can (should?) block this event. Would be a pretty bad user experience if that request would block a few seconds.
A good trade-off is probably to tell the user that something has changed what was not saved yet. Do this with a few boolean checks and finally return a string value in the onbeforeunload request. The browser will then gracefully ask the user if he really wants to leave your site, also showing the string you provided.