This is my code, which sometimes works and sometimes doesn't.
var resolve_ajax_login=function(){
$.ajaxSetup({cache:false });
var loginvar=$("#inputlogin").attr("value");
var senhavar=$("#inputsenha").attr("value");
$.post("../model/php/login_ajax.php",
{login:loginvar, senha:senhavar},
function(responseText){
if (responseText=="ok"){
window.location="areatrab.php";
}else{
$("#inputlogin").attr("value","");
$("#inputsenha").attr("value","");
$("#divmensagem").html("<span style='color:red;font-size:70%;'>"+responseText+"</span>");
}
}
);
return false;
};
Ok. It's in portuguese but I think you get the general picture. Sometimes this works, no problem, but some other times (only in IE, no problem whatsoever in Firefox) it throws a javascript error in my jquery.js file (minified). The error description is as follows:
Object doesn't support this property or method: jquerymin.js line 123 character 183..
which amounts to...
{return new A.XMLHttpRequest}
somewhere in the middle of the jquery.js file. It seems to be very IE-specific, as I had no such problems on Firefox. This guy apparently had the same problem as I did, but got no responses yet.
Has anyone else seen this? Thanks in Advance
P.S.: I run IE 8
Have you tried using a full URL instead of ../model...? For example: http://www.mysite.com/model/login_ajax.php
Also, maybe try modifying the 'xhr' property using jQuery's .ajax method... something like:
var loginvar = $("#inputlogin").val();
var senhavar = $("#inputsenha").val();
var ajax_obj = null;
var resolve_ajax_login = function() {
if(ajax_obj !== null) {
try {
ajax_obj.abort();
} catch(e) {
}
}
ajax_obj = $.ajax({
type: 'POST',
cache: false,
url: '../model/php/login_ajax.php',
data: {login:loginvar, senha:senhavar},
dataType: 'text',
timeout: 7000,
success: function(data)
{
if(response == 'ok') {
alert("right on!");
} else {
alert("not ok");
return;
}
},
error: function(req, reqStatus, reqError)
{
alert("error");
return;
},
'xhr': function() {
if(ajax_obj !== null) {
return ajax_obj;
}
if($.browser.msie && $.browser.version.substr(0,1) <= 7) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
return new XMLHttpRequest();
}
}
});
}
It's something to do with the order in which you try all the different types of browsers in order to create the right kind of XMLHTTP REQUEST object.. I'll explain it in more detail in the following page:
AJAX inconsistency in IE 8?
Related
This question already has answers here:
What does "async: false" do in jQuery.ajax()?
(7 answers)
Closed 3 years ago.
I have an ajax function and thought it would be nice to include a little ajax-spinner to tell the enduser something is actually happening. This is my current jQuery function:
$('#contact-form').submit(function(e)
{
e.preventDefault();
let overlay = $('#overlay'),
loader = $('#loader-popup');
console.log(overlay);
console.log(loader);
console.log('===================');
//show overlay
overlay.removeClass('hidden');
loader.removeClass('hidden');
console.log(overlay);
console.log(loader);
let formData = new FormData($(this)[0]),
params = [];
$.ajax({
data: formData,
type: 'post',
url: '/pages/contact-us/action/send.php',
cache: false,
contentType: false,
processData: false,
success: function(res)
{
if (res == 1) {
params['type'] = 1;
params['msg'] = 'We will be with you as soon as we can!'
} else {
try {
res = $.parseJSON(res);
let data = [];
$.each(res, function(key, value) {data.push(value)});
params['type'] = 2;
params['msg'] = data.join('<br />')
} catch(e) {
console.log(e);
alert('Huh. that\'s weird, something went wrong! Please try again');
//cause syntax error to stop script working
die()
}
}
validator.displayAlert(params['type'], params['msg'])
},
error: function(res)
{
console.log(res);
alert('Don\'t worry.. it\'s not you, it\'s us.')
}
});
//hide overlay
overlay.addClass('hidden');
loader.addClass('hidden');
});
But weirdly the overlay doesn't show, nor does the loader. What makes this hard to kinda debug and fathom is the console.log output.
first console.log(overlay)
Object [ div#overlay.hidden ]
second console.log(loader)
Object [ div#loader-popup.hidden ]
third console.log(overlay)
Object [ div#overlay ]
fourth console.log(loader)
Object [ div#loader-popup ]
So I can see that my .removeClass() function is working, however, inspecting my page once the form is being submitted shows the elements with the hidden class. If I manually remove that hidden class in the inspector tab then everything shows, so I know it's not a CSS issue.
You can see this happen on a much simpler scale here
I've also tried with .toggle() with no avail.
How do I even begin to debug something that seems to work behind-the-scenes but, not on screen?
You should call hide the overlay in your callback, because it'll be executing asynchronously.
Something like
try {
res = $.parseJSON(res);
let data = [];
$.each(res, function(key, value) {
data.push(value)
});
params['type'] = 2;
params['msg'] = data.join('<br />')
} catch (e) {
console.log(e);
alert('Huh. that\'s weird, something went wrong! Please try again');
//cause syntax error to stop script working
die()
} finally {
//hide overlay
overlay.addClass('hidden');
loader.addClass('hidden');
}
The logic within the $.ajax() call is asynchronous. As such you remove the class then immediately add it back in as the AJAX request is in progress.
To fix this, change the addClass() calls to be made after the AJAX request completes. In your case the best place to do this would be in the complete callback as it will fire whether the AJAX request completed successfully or with an error:
$('#contact-form').submit(function(e) {
e.preventDefault();
let $overlays = $('#overlay, #loader-popup').removeClass('hidden');
let formData = new FormData(this),
params = [];
$.ajax({
// ajax settings...
complete: function() {
$overlays.addClass('hidden');
}
});
});
I have created a web page that displays data retrieved from a database via a jQuery $.ajax call. The web page is part of a digital signage system that will be displayed continuously.
The $.ajax response is formatted HTML generated server side. This HTML is then inserted into a div element after removing any existing HTML from the div.
I then attach a jQuery marquee plugin (http://aamirafridi.com/jquery/jquery-marquee-plugin) to some of the newly created div elements with the .marquee class.
var marqueeCounter = 0;
var appBusy = false;
function update() {
if (appBusy == false) {
$.ajax({
url: '/get/html/from/server',
cache: false,
success: function (response) {
$('#div-container').empty();
$('#div-container').html('');
$('#div-container').html(response);
$('.marquee').each(function () {
$(this).width($(this).parent().width());
});
$('.marquee').bind('beforeStarting',function () {
appBusy = true;
marqueeCounter++;
}).bind('finished', function () {
$(this).marquee('pause');
marqueeCounter--;
if (marqueeCounter < 1) {
appBusy = false;
}
}).marquee({
duration: 3500,
allowCss3Support: true,
duplicated: false
});
}
});
}
setTimeout(update, 5000);
}
The problem I am facing is that after hours of running this app, the marquees gradually slow down and eventually the browser (firefox) crashes.
Looking at the memory usage in firefox and chrome, the elements that are replaced with each $.ajax call don't seem to be freed from memory and the eventually choke the browser.
The DOM element count goes up and up as does memory usage.
I'm probably doing something fundamentally wrong here but cannot figure out how to free these resources up.
Thanks.
EDIT 1:
I have tried using the plugins destroy method as per the example on the developers page but it didn't help.
I have removed references to the plugin which results in the following code:
function update() {
if (appBusy == false) {
$.ajax({
url: '/get/html/from/server',
cache: false,
success: function (response) {
$('#div-container').empty();
$('#div-container').html(response);
}
});
}
setTimeout(update, 5000);
}
The number of nodes continues to grow and never decreases.
EDIT 2:
I have re-written this function in native javascript and the problem seems to have gone away.
function update()
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("div-container").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/get/html/from/server", true);
xmlhttp.send();
setTimeout(update, 5000);
}
Why would jQuery be returning different results?
I am trying to check for the internet connection by sending a GET request to the server. I am a beginner in jquery and javascript. I am not using navigator.onLine for my code as it works differently in different browsers. This is my code so far:
var check_connectivity={
is_internet_connected : function(){
var dfd = new $.Deferred();
$.get("/app/check_connectivity/")
.done(function(resp){
return dfd.resolve();
})
.fail(function(resp){
return dfd.reject(resp);
})
return dfd.promise();
},
}
I call this code in different file as:
if(!this.internet_connected())
{
console.log("internet not connected");
//Perform actions
}
internet_connected : function(){
return check_connectivity.is_internet_connected();
},
The is_internet_connected() function returns a deferred object whereas I just need an answer in true/false. Can anybody tell me about how to achieve this?
$.get() returns a jqXHR object, which is promise compatible - therefore no need to create your own $.Deferred.
var check_connectivity = {
...
is_internet_connected: function() {
return $.get({
url: "/app/check_connectivity/",
dataType: 'text',
cache: false
});
},
...
};
Then :
check_connectivity.is_internet_connected().done(function() {
//The resource is accessible - you are **probably** online.
}).fail(function(jqXHR, textStatus, errorThrown) {
//Something went wrong. Test textStatus/errorThrown to find out what. You may be offline.
});
As you can see, it's not possible to be definitive about whether you are online or offline. All javascript/jQuery knows is whether a resource was successfully accessed or not.
In general, it is more useful to know whether a resource was successfully accessed (and that the response was cool) than to know about your online status per se. Every ajax call can (and should) have its own .done() and .fail() branches, allowing appropriate action to be taken whatever the outcome of the request.
Do you mean to check the internet connection if it's connected?
If so, try this:
$.ajax({
url: "url.php",
timeout: 10000,
error: function(jqXHR) {
if(jqXHR.status==0) {
alert(" fail to connect, please check your connection settings");
}
},
success: function() {
alert(" your connection is alright!");
}
});
100% Working:
function checkconnection() {
var status = navigator.onLine;
if (status) {
alert('Internet connected !!');
} else {
alert('No internet Connection !!');
}
}
This piece of code will continue monitoring internet connection
click bellow "Run code snippet" button and see it in action.
function checkInternetConnection(){
var status = navigator.onLine;
if (status) {
console.log('Internet Available !!');
} else {
console.log('No internet Available !!');
}
setTimeout(function() {
checkInternetConnection();
}, 1000);
}
//calling above function
checkInternetConnection();
try this
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
if (! window.jQuery) {
alert('No internet Connection !!');
}
else {
// internet connected
}
Jquery Plugin for Detecting Internet Connection
you cannot get simple true or false in return, give them a callback handler
function is_internet_connected(callbackhandler)
{
$.get({
url: "/app/check_connectivity/",
success: function(){
callbackhandler(true);
},
error: function(){
callbackhandler(false);
},
dataType: 'text'
});
}
I just use the navigator onLine property, according to W3C http://www.w3schools.com/jsref/prop_nav_online.asp
BUT navigator only tells us if the browser has internet capability (connected to router, 3G or such).
So if this returns false you are probably offline but if it returns true you can still be offline if the network is down or really slow.
This is the time to check for an XHR request.
setInterval(setOnlineStatus(navigator.onLine), 10000);
function setOnlineStatus(online)
{
if (online) {
//Check host reachable only if connected to Router/Wifi/3G...etc
if (hostReachable())
$('#onlineStatus').html('ONLINE').removeAttr('class').addClass('online');
else
$('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
} else {
$('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
}
}
function hostReachable()
{
// Handle IE and more capable browsers
var xhr = new (window.ActiveXObject || XMLHttpRequest)("Microsoft.XMLHTTP");
var status;
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open("HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
// Issue request and handle response
try {
xhr.send();
return (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304));
} catch (error) {
return false;
}
}
EDIT: Use port number if it is different than 80, otherwise it fails.
xhr.open("HEAD", "//" + window.location.hostname + ":" + window.location.port + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
It's working fine for me.
<div id="status"></div>
<script>
window.addEventListener("offline", (event) => {
const statusDisplay = document.getElementById("status");
statusDisplay.textContent = "OFFline";
});
window.addEventListener("online", (event) => {
const statusDisplay = document.getElementById("status");
statusDisplay.textContent = "Online";
});
</script>
I'm getting 'Unexpected call to method or property access' in IE7 and my script won't work in IE8 and I can't for the life of me figure out why.
I've been using developer tools in IE (woohooo!) but it isn't much help. The error I am getting is in Jquery:
SCRIPT65535: Unexpected call to method or property access.
jquery.js?ver=1.7.1, line 3 character 31871
It works perfectly fine in IE9, Safari, FF and chrome.
On the Html page, I click the following link which passes the vale of the data-tax attribute to the script. Do you think perhaps it has to do anything with html5? Any pointers will be much appreciated.
For example, if you click Brad Pitt, it should display movies Brad Pitt is in:
<li class="ajaxFilterItem brad-pitt af-actor-6 filter-selected" data-tax="actor=6"><span class="checkbox"></span>Brad Pitt (1)</li>
I pass the following value to
filterAjaxify("actor=6")
And this is the offending code:
(function($){
var isRunning = false;
// Return an array of selected navigation classes.
function loopSelected(_node) {
var _arr = [];
_node.each(function(){
var _class = $(this).attr('data-tax');
_arr.push(_class);
});
return _arr;
};
// Animate the progress bar based on Ajax step completion.
function increaseProgressBar(percent){
$('div#progbar').animate({
width: percent + '%'
},30);
};
// Join the array with an & so we can break it later.
function returnSelected(){
var selected = loopSelected($('li.filter-selected'));
return selected.join('&');
};
// When the navigation is clicked run the ajax function.
$('a.ajax-filter-label, a.paginationNav, a.pagelink').live('click', function(e) {
if(isRunning == false){
isRunning = true;
e.preventDefault();
var relation = $(this).attr('rel');
if($(this).parent('li').length > 0) {
$(this).parent('li').toggleClass('filter-selected');
thisPage = 1;
}
if(relation === 'next'){
thisPage++;
} else if(relation === 'prev') {
thisPage--;
} else if($(this).hasClass('pagelink')){
thisPage = relation;
}
filterAjaxify(returnSelected());
}
});
// Do all the ajax functions.
function filterAjaxify(selected){
$.ajax({
url: ajaxurl,
type: 'post',
data: {
"action":"affilterposts",
"filters": selected,
"posttypes": posttypes,
"qo": qo,
"paged": thisPage,
"_ajax_nonce": nonce
},
beforeSend: function(){
$('div#ajax-loader').fadeIn();
$('section#ajax-filtered-section').fadeTo('slow',0.4);
increaseProgressBar(33);
},
success: function(html){
increaseProgressBar(80);
$('section#ajax-filtered-section').html(html);
},
complete: function(){
$('section#ajax-filtered-section').fadeTo('slow',1);
increaseProgressBar(100);
$('div#ajax-loader').fadeOut();
isRunning = false;
},
error: function(){}
});
};
})(jQuery);
The <section> is new in HTML5, older IE doesn't know how to digest that, and has some DOM issues when you try and append things to such elements.
E.g. http://jsfiddle.net/EKU7R/
So far I've been making an AJAX call to replace the content of a div with another page, using the following code:
<script>
function fetchContainerContent(url, containerid) {
var req = false
if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
req = new XMLHttpRequest()
} else {
return false
}
req.onreadystatechange = function() {
requestContainerContent(req, containerid)
}
req.open('GET', url, true)
req.send(null)
}
function requestContainerContent(req, containerid) {
if (req.readyState == 4 && (req.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML = req.responseText
}
</script>
I have tried transforming the above code to work with jQuery as below but it doesn't work. In other words, I am trying to mimic the end result of the above behaviour but it is nowhere near the same. In fact, nothing happens on screen, nothing changes. I should mention that I don't really need the Loading... but since the examples I've seen use it and since I'm not sure how to correctly syntax jQuery, I've left it in.
<script>
function fetchContainerContent(url, containerid) {
jQuery.ajaxSetup ({
cache: false
});
var ajax_load = "loading...' />";
jQuery("#load_basic").click(function() {
jQuery("#"+containerid).html(ajax_load).load(url);
});
}
</script>
Thanks in advance. I'm really new to jQuery so I may have done something really stupid.
After all the comments received (thanks guys!) I have left only the following:
function fetchContainerContent(url, containerid){
var ajax_load = "loading...";
$("#load_basic").click(function(){$("#"+containerid).html(ajax_load).load(url);});
}
but I'm still having problems as it does not update the page. No js error, nothing happens.
Try this:
jQuery("#load_basic").click(function() {
jQuery("#result").html(ajax_load).load(url);
return false;
});
Note the return false statement at the end of the click handler. This will prevent from propagating the click event in case load_basic is a button or an anchor element.
The only fundamental differences I see are:
You're using a hacky-looking loading string "loading...' />". This doesn't smell good.
You're hardcoding the containerid with "#result" instead of using "#" + containerid.
You're defining the click event in JS code rather than (apparently) inline in the element. How did it originally look like?
For the remnant the code looks fine.
Is the issue that it isn't calling your callback method? You have to had the callback to the .load method.
<script>
function fetchContainerContent(url, containerid) {
jQuery.ajaxSetup ({
cache: false
});
var ajax_load = "loading...' />";
jQuery("#load_basic").click(function() {
jQuery("#result").html(ajax_load).load(url, null, requestContainerContent);
return false;
});
}
function requestContainerContent(responseText, textStatus, XMLHttpRequest) {
// do replacement in here
}
</script>
You'll have to adjust the code a bit in your requestContainerContent to do what you need it to do with the arguments provided.
OK, I seem to have gotten it working, even if I'm not too sure about the quality of the code.
var ajax_load = "loading...";
$("#"+containerid).html(ajax_load).load(url);