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!
Related
i am calling an ajax function every second to make an online class link live, if the class link is finished i need to display the last class until the current time matches with the scheduled class time which needs to be enabled live. so i called ajax function using set interval method, and it works fine but i am getting an error like 504 Gateway time out error and the whole site is not working. so can any one give me good suggestion please ?
Below is my ajax code
$(function() {
setInterval(updateLstream, 1000);
});
updateLstream();
function updateLstream() {
$.ajax({
type: 'POST',
async: true,
url: "../users/zbbtns_live.php",
data: {
cid: ""
},
success: function(data) {
if (data.status == 1) {
$(".setMainLiveBtn").html(data.Hdata);
} else {
//alert("No Live Streams");
console.log("ss");
}
}
});
}
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 am new to working with AJAX and have some experience with Java/Jquery. I have been looking around for an solution to my problem but i cant seem to find any.
I am trying to build a function in a webshop where the product will appear in a popup window instead of loading a new page.
I got it working by using this code:
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
$("#product-overlay-inner").load(myUrl, function() {
});
$("#product-overlay").fadeIn();
return false;
});
product-slot a = Link to the product in the category page.
product-content = the div i want to insert in the popup from the product page.
product-overlay-inner = The popup window.
product-overlay = The popup wrapper.
The problem that i now have is that my Javascript/Jquery isnt working in the productpopup. For example the lightbox for the product image or the button to add product to shoppingcart doesnt work. Is there anyway to make the javascript work inside the loaded content or to load javascript into the popup?
I hope you can understand what my problem is!
Thank you in advance!
EDIT: The platform im using has jquery-ui-1.7.2
I know this is an old thread but I've been working on a similar process with the same script loading problem and thought I'd share my version as another option.
I have a basic route handler for when a user clicks an anchor/button etc that I use to swap out the main content area of the site, in this example it's the ".page" class.
I then use a function to make an ajax call to get the html content as a partial, at the moment they are php files and they do some preliminary rendering server side to build the html but this isn't necessary.
The callback handles placing the new html and as I know what script I need I just append it to the bottom in a script tag created on the fly. If I have an error at the server I pass this back as content which may be just a key word that I can use to trigger a custom js method to print something more meaningful to the page.
here's a basic implementation based on the register route handler:
var register = function(){
$(".page").html("");
// use the getText ajax function to get the page content:
getText('partials/register.php', function(content) {
$(".page").html(content);
var script = document.createElement('script');
script.src = "js/register.js";
$(".page").append(script);
});
};
/******************************************
* Ajax helpers
******************************************/
// Issue a Http GET request for the contents of the specified Url.
// when the response arrives successfully, verify it's plain text
// and if so, pass it to the specified callback function
function getText(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url);
request.onreadystatechange = function() {
// if the request is complete and was successful -
if (request.readyState === 4 && request.status === 200) {
// check the content type:
var type = request.getResponseHeader("Content-Type");
if (type.match(/^text/)) {
callback(request.responseText);
}
}
};
// send it:
request.send(null); // nothing to send on GET requests.
}
I find this a good way to 'module-ize' my code into partial views and separated JavaScript files that can be swapped in/out of the page easily.
I will be working on a way to make this more dynamic and even cache these 'modules' for repeated use in an SPA scenario.
I'm relatively new to web dev so if you can see any problems with this or a safer/better way to do it I'm all ears :)
Yes you can load Javascript from a dynamic page, but not with load() as load strips any Javascript and inserts the raw HTML.
Solution: pull down raw page with a get and reattach any Javascript blocks.
Apologies that this is in Typescript, but you should get the idea (if anything, strongly-typed TypeScript is easier to read than plain Javascript):
_loadIntoPanel(panel: JQuery, url: string, callback?: { (): void; })
{
// Regular expression to match <script>...</script> block
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts: string = "";
var match;
// Do an async AJAX get
$.ajax({
url: url,
type: "get",
success: function (data: string, status: string, xhr)
{
while (match = re.exec(data))
{
if (match[1] != "")
{
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
// Replace the contents of the panel
//panel.html(data);
// If you only want part of the loaded view (assuming it is not a partial view)
// using something like
panel.html($(data).find('#product-content'));
// Add the scripts - will evaluate immediately - beware of any onload code
panel.append(scripts);
if (callback) { callback(); }
},
error: function (xhr, status, error)
{
alert(error);
}
});
}
Plain JQuery/Javascript version with hooks:
It will go something like:
var _loadFormIntoPanel = function (panel, url, callback) {
var that = this;
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts = "";
var match;
$.ajax({
url: url,
type: "get",
success: function (data, status, xhr) {
while(match = re.exec(data)) {
if(match[1] != "") {
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
panel.html(data);
panel.append(scripts);
if(callback) {
callback();
}
},
error: function (xhr, status, error) {
alert(error);
}
});
};
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
_loadFormIntoPanel($("#product-overlay-inner"), myUrl, function() {
// Now do extra stuff to loaded panel here
});
$("#product-overlay").fadeIn();
return false;
});
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.
I have an AJAX function to check for new messages and then prepend the new messages to the #message. But, my problem is that this function triggers every 20 seconds, but whenever you click the Refresh button that instantly triggers the function, it messes up. Here is my functions for the AJAX:
function ajaxMail() {
var message_id = $('.line:first').attr('id');
jQuery.ajax({ //new mail
type: 'get',
dataType: 'text',
url: "/employee/message/check_mail.php",
data: {
latest_id: message_id,
t: Math.random()
},
success: function(data, textStatus) {
$('#messages_inner').prepend(data);
}
});
}
function updateTitles() {
//if(titleChange !== false) {
$.get('update.php?type=title', function(data) {
document.title = data;
});
//}
$.get('update.php?type=header', function(data) {
$('#heading').html(data);
});
$.get('update.php?type=total', function(data) {
$('#total').html('Total messages: ' + data);
});
setTimeout("updateTitles();ajaxMail();", 20000);
}
updateTitles();
And for the Refresh button this is what I use:
$(document).ready(function() {
$('#refresh').click(function() {
ajaxMail();
updateTitles();
});
});
Sometimes, the same exact message gets prepended to the message div because of the button or something. (but when I refresh of course there aren't 2 of the same message anymore) This is one time when the same message was prepended multiple times:
First, I pressed the Refresh button and it prepended the new message. But then about 5 seconds later the funciton triggered again and for some reason prepended the same message again. Also as you can see the Inbox count says 2 because really there is only 2 ("Test" and "Test12345"), but for some reason the "Test12345" got prepended 2 times.
Does anyone know why it is doing this? I can also provide the code for check_mail.php if you need to see it.
I'd recommend trying cache:false too, I've had browsers caching an ajax request even through I was sending a random string along.
Also, consider clearing the timeout before you set it again, as each time the refresh button is pressed it starts another timeout.