I am using chrome.
I have an iframe in which i require to hit a url that supports jsonp.
so i used this code :
$.ajax({
dataType: 'jsonp',
url: my_url.endpoint + '/login/v1/token' ,
data: form_to_object("#signin_form"),
context: window,
// All Ajax calls to ABC are json
// Response statuses other than 200 are caught in a timeout
timeout: 10000, //10s
// Handler for successful calls to ABC: calls that return with statusCode 200
success: function(data, textStatus, jqXHR) {
// console.log(data);
alert("in access_token success");
if (data.hasOwnProperty('error_flag')) {
// Errors associated with this action are caught here:
// invalid_credentials, account_lockout, etc.
if (data.hasOwnProperty("jump")) {
ABC_show_frame(data.jump);
} else {
ABC_error_handler(data);
}
return;
}
// Auth succeeded, we can log in the user
GetUserProfile(data);
// ABC_success_handler(data);
},
error: function(data, textStatus, jqXHR) {
alert("In access_token error");
if (data.hasOwnProperty("jump")) {
ABC_show_frame(data.jump);
} else {
ABC_error_handler(data);
}
}
});
Now this code does not attach a callback=some_random_function_name in the url that it generates after attaching the parameters of data.
like https://abc/login/v1/token?username=ashish?password=abc but no callback.
When i debug it line by line, it do call the url with callback=something, and it seems to work. (seems because may be sometime it does not attach even in debugging line by line.)
But when i just run it, it does not.
I think that may be the problem is a bug in jquery where it also has to attach data that it got from form_to_object() and may be that overrides the callback parameter. But that is just a guess.
What should i do ?
I had a form and i was writing my own custom function that would be called when submit button of the form was clicked. In that function i was not stopping the event from propagating further. This lead to this weird errors.
$("form.ims.ajax").submit(function(event) {
event.preventDefault();
// do your stuff
});
This solved the problem.
Related
Hello I have this script that moves from one page through a href without page load.
It works perfectly, but I want to redirect to the requested page if Ajax takes longer than 5 seconds to respond, usually caused by probably slow internet connection.
In this case: Stop the script and load the page normally.
Firstly the href:
new
New 1
This is the script:
<script>
$(function(){
$("a[rel='tab']").click(function(e){
pageurl = $(this).attr('href'); //get the href clicked
$.ajax({url:pageurl+'?rel=tab',
success: function(data){
$('#mole').html(data);
}
});
if(pageurl!=window.location){
window.history.pushState({
path:pageurl
},'',pageurl);
}
return false;
});
});
$(window).bind('popstate', function(){
$.ajax({
url:location.pathname+'?rel=tab',
success: function(data){
// here how do I detect if the success takes longer than 5 seconds
// stop the script and load the page normally which is the URL parameter in ajax
$('#mole').html(data);
}
});
});
</script>
First, we need to add a timeout to the ajax handler so it will cancel the request after 5 seconds (here we use 5000 for milliseconds). Then, based on the docs, head to error and you can see the second param is textStatus. If it was a timeout, this will be equal to "timeout". This is probably your easiest path to what you need to do. Update the error handler as needed for your functionality.
$(window).bind('popstate', function() {
var url = location.pathname + '?rel=tab';
$.ajax({
timeout: 5000,
url: url,
success: function(data) {
$('#mole').html(data);
},
error: function(jqXHR, textStatus) {
if (textStatus === 'timeout') {
// we know the ajax failed due to a timeout,
// do what you need here, below is an example.
window.location = url;
}
}
});
});
In order to prevent getting an error twice I use beforeSend.
hasSent = false
function submit() {
if (!hasSent)
$.ajax({
url: "${createLink(controller:'userInvitation', action:'ajaxUpdate')}",
type: "POST",
data: $("#invitationForm").serialize(),
success: function(data, textStatus, jqXHR) {
$('#invitationForm')[0].reset();
$('.thank-you-modal').modal('show');
hasSent = true;
console.log(hasSent)
},
complete: function() {
hasSent = false;
console.log(hasSent)
}
});
}
As you can see the ajax should happen only if hasSent=false.
For some reason the ajax happens also if the user clicks multiple time (very quick) on the submit button
To prevent this kind of issue disable the button before sending the ajax and then anable inside the success function
$(mybutton).prop("disabled",true);
// ajax call here
then
success: function(data, textStatus, jqXHR) {
$(mybutton).prop("disabled",false);
// code here
}
You can create another flag such as isSending
function submit() {
if(isSending)
return;
isSending = true
$.ajax({
// ...
complete: function() {
isSending = false;
}
});
}
there are two ways you can do this.
1) create a flag and check if the button is pressed. If pressed then do not execute the ajax code
change the flag back once the request is successful, like this
success:function(...)
{
flag=false;
}
Or you can disable the button at the button click so the request will be carried out and double click situation won't arise. Enable the button on complete like this
complete:function(..){ $("yourbutton").attr("disabled",false)}
I have a website where users can work on projects and their work gets automatically saved to my database. Every couple seconds on my site an ajax (post) call occurs (usually in jquery) to check permissions and what not.
With one section of code is there any way so check if any of the ajax calls on your page fail. I don't want to have to go to every individual call and add a block of code to the end.
Basically this is so I can alert the user if they have lost connection or if something is going wrong.
You can use the jQuery event ajaxError. It will be triggered whenever an Ajax request completes with an error:
$(document).ajaxError(function() {
console.error('Error');
});
Check out the documentation.
$(document).ready(function(){
//ajax setup settings
$.ajaxSetup ({
cache: false,
async: false,
statusCode: {
404: function() {
alert('Page not found!');
},
500: function(jqXHR, textStatus) {
alert('Server side: ' + textStatus);
}
}
});
});
I hope this may help you
I would suggest you to override the original jquery ajax function.
var $_ajax = $.ajax; // reference to original ajax
$.ajax = function(options) {
if (options.error) {
// reference to original error callback
var originalErrorHandler = options.error;
var errorHandlerContext = options.context ? options.context : $;
var customErrorHandler = function(xhr, status, error) {
// notify error to your user here
};
// override error callback with custom implementation
options.error = customErrorHandler;
};
return $_ajax.apply($, arguments);
}
I got this piece of cake function:
$.ajax({
url: 'Example.html',
DataType: 'text',
cache: false,
success: function (){
alert ('Yes');
},
error: function (){
alert ('No');
}
});
This function, works just fine, BUT ONLY FOR THE VERY FIRST TIME), from the second time on, the function sends the following error to Chrome:
GET http://MyServer.com/Example.html?_=1406469092100 net::ERR_FAILED
The same situation happens equally with this second JS option:
function doesConnectionExist() {
var xhr = new XMLHttpRequest();
var file = "http://www.example.com/Example.html";
var randomNum = Math.round(Math.random() * 10000);
xhr.open('HEAD', file + "?rand=" + randomNum, false);
try {
xhr.send();
if (xhr.status >= 200 && xhr.status < 304) {
alert ('Yes');
} else {
alert ('No');
}
} catch (e) {
alert ('No');
}
}
1) In the Ajax scenario I just indicate cache: "false"!
2) In the JavaScript scenario I am using random arguments to avoid cache!
Is there anything I am missing? in the Server side??
Please help...
It may be a server problem? I have created a jsFiddle and it seems to work like it should. I wrapped your $.ajax method in a ping function and run it 3 times fetching a jsfiddle resource.
function ping(i) {
$.ajax({
url: '/img/logo.png',
success: function () {
screen.log({text: 'attempt #'+(i+1)+ ' Yes', timed: +i, clear: 'no'});
},
error: function (d){
screen.log({text: 'attempt #'+(i+1)+ ' Nope', timed: +i, clear: 'no'});
}
});
}
See the already mentioned jsFiddle for output
Note: in your second code snippet your supply false as the third paramater to the open method, which means asynchronous = false, so the XHR there is synchronous. The cache: false parameter in the first snippet appends a random reuqeststring to the request. This prevents the browser from caching the fetched resource. I suppose it's not really necessary here.
After hours and hours of try an error I found the Answer....dedicated for those guys who are facing the same problem I did:
In my case this was not a common Web Page, it was an "Offline Web Page" with a Manifest File in it.
Simply in the section "NETWORK" of the manifest file included the file "Example.html" and that's it.
That's all folks!
We are putting together an FSSO API that requires a popup window for the user to log in. In the popup, we perform two tasks:
Calling a service to populate a profile values, then setting a page
to redirect the user to based on the event type (login or registration).
Redirecting the user to the redirect page in the parent window and closing the FSSO popup.
Code:
$(document).ready(function() {
var nextPage = "index.html",
storage = window.opener.sessionStorage;
function setStorage(callback){
$.ajax({
type: "GET",
cache: false,
dataType: "json",
url: "https://someserviceURL/service/profile",
success: function(objJSON){
//storage.op is set on the parent page when login or reg link is clicked
if (storage.op == "login") {
storage.firstname = objJSON.firstName;
storage.lastname = objJSON.lastName;
storage.setItem('loggedIn',JSON.stringify(true)); //Some browsers don't support booleans in sessionStorage
nextPage = "dashboard.html";
}
else if (storage.op == "register") {
storage.firstname = objJSON.firstName;
storage.lastname = objJSON.lastName;
storage.setItem('loggedIn',JSON.stringify(true));
nextPage = "options.html";
}
},
error: function( jqXHR, textStatus, errorThrown){
//display error message
}
});
callback();
}
setStorage(function(){
if (typeof window.opener != "undefined" && window.opener != null){
setTimeout(function(){
window.opener.location.href = nextPage;
window.close();
},3000);
}
});
});
Problem:
The window seems to be closing before I'm able to set the sessionStorage values if I set the timeout to anything less than 3000. I just want to close the window in response to those values being set, not some arbitrary amount of time passing. I tried the trick of setting the timeout to 0 but no luck, and I tried just the callback with no timeout.
Looking for best practices here on handling timing issues like these, what I have now feels hacky. :)
The call to $.ajax() is asynchronous, which means that the rest of the script will continue to execute immediately after the call is made, without waiting for the call to complete and trigger the success or error handlers.
This means that your function called callback is being executed before your success handler. It may usually work as intended with a 3000ms timeout as your web service often takes less time than this to complete, so your callbacks are executed first in these cases. As you mentioned, this is not a reliable way to control the order of events.
One solution would be to execute your callback as part of the complete handler, as follows:
$(document).ready(function() {
var nextPage = "index.html",
storage = window.opener.sessionStorage;
function setStorage(callback){
$.ajax({
type: "GET",
cache: false,
dataType: "json",
url: "https://someserviceURL/service/profile",
success: function(objJSON){
//storage.op is set on the parent page when login or reg link is clicked
if (storage.op == "login") {
storage.firstname = objJSON.firstName;
storage.lastname = objJSON.lastName;
storage.setItem('loggedIn',JSON.stringify(true)); //Some browsers don't support booleans in sessionStorage
nextPage = "dashboard.html";
}
else if (storage.op == "register") {
storage.firstname = objJSON.firstName;
storage.lastname = objJSON.lastName;
storage.setItem('loggedIn',JSON.stringify(true));
nextPage = "options.html";
}
},
error: function( jqXHR, textStatus, errorThrown){
//display error message
},
complete: function( jqXHR, textStatus){
callback();
}
});
}
setStorage(function(){
if (typeof window.opener != "undefined" && window.opener != null){
window.opener.location.href = nextPage;
window.close();
}
});
});
Or if you don't care about the returned arguments you could pass callback directly to complete. Note that complete will be executed in both success and error conditions, so you might want to call callback only in your success handler and do something else with any errors.
You should call your callback as the last action of your success function:
.
.
.
else if (storage.op == "register") {
storage.firstname = objJSON.firstName;
storage.lastname = objJSON.lastName;
storage.setItem('loggedIn',JSON.stringify(true));
nextPage = "options.html";
}
callback(); // execute your callback to the window closer here.
},
error: function( jqXHR, textStatus, errorThrown){
//display error message
}
});
}