Jquery script not working with IE - javascript

I written this script, to add JavaScript functionality to my online shop, the script works fine with Firefox and Chrome, but will not run on ie, and i am not sure why?
i am using jQuery(function( $ ){ instead of .ready due to script conflicts, i have tested the script using .ready and it still does not work with ie.
if anyone has an ideas they would be much appreciated.
jQuery(function( $ ){
setInterval(function(){ updatecart(); },8000);
$('.addtobag').on('click', function(){
event.preventDefault();
var postdata = new Object();
var action = $(this).closest('form').attr('action');
$(':input',$(this).closest('form')).each(function(evt){
var L = $(this).attr('name')
postdata[L] = $(this).val();
});
$.post(action, postdata);
generate('success'); //display banner
updatecart(); //update cart
});
var postdata = new Object();
postdata['basket'] = phpbasket;
function updatecart() {
$.post("/get_cart_details.php", postdata, function (data) {
var obj = $.parseJSON(data);
$('#qty_js').text(obj.items_qty);
$('#amt_js').text(obj.items_value);
});
}
function generate(type) {
var n = noty({
text: 'The item(s) have been added to your basket.',
type: type,
dismissQueue: true,
layout: 'topCenter',
theme: 'defaultTheme'
});
console.log('html: '+n.options.id);
setTimeout(function() {
$.noty.closeAll();
}, 5000);
}
});

Get rid of the console.log() statement. IE < 9 chokes on it and 9 only works if the console is open.

Try adding an event parameter in your click callback
$('.addtobag').on('click', function(event){

A couple things that might be tolerated in some browsers and not IE are that line 12 is missing a semicolon at the end, and the variable phpbasket is not defined (although if you defined it outside of the closure with 'var phpbasket' then you should be ok. If you debug it in IE 9 or higher, you should be able to see line numbers of errors in the console.

Not a complete answer, but it may point you in the right direction. I was actually about to ask a similar question - I found how to get IE 11 to load the jquery, but it required the user to hit "f12" and then "run activex" because apparently IE considered my code potentially unsafe. But when the user tells the activex to run, it works fine.
I am trying to learn how to use jquery to make touchscreen-friendly dropdown menus, so my code was basic - no css, no doctype, just basic html and js. If anyone else could shed some light on this it would be great.

Related

Ajax method does not fire on initial page load

Note: Please see edit at the bottom after reading this question.
This issue is only happening in IE 11, and only started occurring after a recent Windows update. There were 5 updates, one of which was specific to IE, so I uninstalled that one. However, the issue still exists. Before I consider rolling back the remaining updates, is there something inherently wrong in my code? The following is inside the document ready function:
$('#leftmenu>li').click(function () {
var clickedId = this.id;
$.ajax({
url: "Session/Index/",
cache: false,
success: function (result) {
if (result.length > 0)
{
performListItemAction(clickedId);
}
else
{
window.location.href = 'Home/Index/'
}
}
});
});
And the following is the performListItemAction method (a separate function not in document.ready):
function performListItemAction(item)
{
alert("clicked");
$(".tabui").each(function ()
{
$(this).hide();
});
$(".listitem").each(function ()
{
$(this).css("background", "transparent");
});
$(document.getElementById(item)).css("background-color", "#C8C8C8");
var targetId = $(document.getElementById(item)).data('target');
var target = $(document.getElementById(targetId));
target.show();
}
The alert clicked never appears when this problem happens, and that is how I concluded the ajax call is not working.
A few other notes:
This issue isn't happening on Firefox.
This only happens if I directly login to the page with a direct URL. If I log in via the application's home screen, and then go to the page that uses the above javascript, the issue doesn't occur.
Thank you.
EDIT: I just now see that the same issue is now occurring in Firefox as well. It's just much less frequent.
After trial and error, I think I fixed the issue by adding a forward slash to the beginning of each of the URLs, and added the type: "POST", to the ajax call. I don't know why it was working fine before, but now this works in all my attempts.

Internet Explorer issues running code if debugger closed

Yesterday I encountered an interesting issue with Internet Explorer. A script runs perfectly on Chrome, Firefox, Safari, but with Internet Explorer 11 it doesn't do anything. If I open the debugger it runs smoothly and everything is as it should, but the moment I close the debugger it stops working and I have no idea why is this. My first thought was the IE extensions, but I disabled them to no veil. I tried running in safe-mode, with admin rights, but nothing seems to work.
To summarize everything: IE - script runs ONLY while the debugger is On. No error is produced, it just doesn't work.
I would be really glad for any ideas what can I do regarding this. Thank you in advance.
--------------EDIT---------------
Here is the script that doesn't run.
for (var i = 0; i < AllStrategyGrids.length; i++) {
try {
isChange = true;
var data = $("#objectives").data("kendoGrid").select().data();
if (AllStrategyGrids[i].ID == data.uid) {
var jsonData = new Object();
jsonData.StrategicID = "1";
jsonData.ObjectiveID = $("#ObjectiveID").val();
jsonData.HeaderID = "00000000-0000-0000-0000-000000000000";
jsonData.PeriodID = "00000000-0000-0000-0000-000000000000";
jsonData.Strategic = "Please enter strategic";
jsonData.TaskStatus = "";
jsonData.TaskStatusID = "1";
jsonData.Position = "";
jsonData.Sorted = "1";
jsonData.SessionID = "00000000-0000-0000-0000-000000000000";
tmpGrid = AllStrategyGrids[i].Grid.data("kendoGrid");
var dataRows = tmpGrid.items();
var rowIndex = dataRows.index(tmpGrid.select());
$.ajax({
url: "CreateStrategy",
type: 'POST',
data:
{
strategics: jsonData,
VersionID: $("#VersionUID").val(),
index: rowIndex
},
success: function () {
tmpGrid.dataSource.read();
}
});
}
} catch (e) { }
}
Just a guess, this is likely because you have a console.log in that script and in IE the console object doesn't exist if your debugger is closed... we've all be there :)
An easy fix is the just add small shim as early on in your site as you can.. it won't do a thing on any browsers except IE and will just stop the execution error that probably blocking your other JS code from running...
<script>
if(!console)console={log:function(){}};
</script>
a more robust solution here :
'console' is undefined error for Internet Explorer
---- EDIT
Okay one thing i can see from your code is that you're going to fail silently because you've used a try catch but do nothing with it. This is going to catch any exception you are having (blocking it from reaching your window thus making it seem like you have no errors). I would perhaps alert the error message at the very least while testing (so you don't need to open Debugger) and see if anything is thrown...
I'd be suspecting your ajax request myself.. that or an undefined in IE8.. so add some logging alerts (brute force i know) to test your assumptions at certain points e.g.
alert("Reach here and data="+data);
Alternatively, i can also see that your ajax request has no callbacks for unsuccessful which might be good idea to add to your call. It might be that the success isn't calling for some reason...
$.ajax({
url: "CreateStrategy",
type: 'POST',
data:
{
strategics: jsonData,
VersionID: $("#VersionUID").val(),
index: rowIndex
},
success: function () {
tmpGrid.dataSource.read();
}
})
.fail(function() {
alert( "error" );
//handle a failed load gracefully here
})
.always(function() {
alert( "complete" );
//useful for any clean up code here
});
Final food for thought.
Since you're checking the DOM for an item, and i have no idea when this code is called but just in case its called directly AFTER a page reload..and lets assume something in IE isn't ready at 'that' point, it might be the DOM isn't ready to be queried yet? Try executing this code when the DOM is ready.. lots of ways to achieve this $.ready , setTimeout(f(){},1) or vanilla... but you get the idea..
Note: Debugging Script with the Developer Tools: MSDN
To enable script debugging for all instances of Internet Explorer, on
the Internet Options menu, click the Advanced tab. Then, under the
Browsing category, uncheck the Disable script debugging (Internet
Explorer) option, and then click OK. For the changes to take effect,
close all instances of Internet Explorer then reopen them again.

jQuery.when.done() seems to not work in IE9. No console error either

I have written a jquery addon, with a little help from the internet, which retrieves data from Facebook and does as intended on all browsers tested so far apart from IE9.
I work for local government and unfortunately we still use IE9 in our builds (It was still IE8 a few weeks back!! So could have been a lot worse I expect :).
Anyways, I digress, I have added the section of code below which never completes in IE9, but does in IE10, and other browsers...
Can anyone explain/help me adapt or fix this snippet so that I can get it working in IE9?? And not break it in any other browsers in the process :)??
$.when($.getJSON(ogUSER), $.getJSON(ogPOSTS)).done(function (user, posts) {
// user[0] contains information about the user (name and picture);
// posts[0].data is an array with wall posts;
var fb = {
user: user[0],
posts: []
};
var idxLimit = 0;
$.each(posts[0].data, function () {
// We only show links and statuses from the posts feed:
if (this.type != 'link' && this.type != 'status') {
return true;
}
// Copying the user avatar to each post, so it is
// easier to generate the templates:
this.from.picture = fb.user.picture.data.url;
// Converting the created_time (a UNIX timestamp) to
// a relative time offset (e.g. 5 minutes ago):
this.created_time = relativeTime(this.created_time * 1000);
// Converting URL strings to actual hyperlinks:
this.message = urlHyperlinks(this.message);
//remove all anchors
//var content = $('<div>' + this.message + '</div>');
//content.find('a').remove();
//this.message = content.html();
fb.posts.push(this);
idxLimit++;
if (idxLimit === 2) {
return false;
}
});
In all browsers, not including IE9, if I insert a breakpoints anywhere within the .done() callback it stops execution and I can debug. With IE9 the breakpoint is not reached leading me to believe there is an issue with IE9 script engine and jQuery.when() API call, or the .done() callback method...
But, I'm just guessing at the mo... I've been searching the web for the last few hours to see if anyone else has happened upon a similar issue but to no avail. I hope some of the more experienced coders here can help... would be very much appreciated. Until then the search goes on :)
Thanks for your time folks ;)
PS. I don't receive any console errors what so ever in IE9 running the script...
TartanBono

$(this).dialog is not a function

...or Why $(this).dialog() fails in Firefox when using dynamic HTML?
I have a a click event that opens a jQuery modal dialog box on a web page, and it is working fine in Chrome and IE, but not in Firefox.
Here is the pertinent code:
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
var dialogDiv = $(document.createElement('div')).attr("id", dialogId);
dialogDiv.load(this.href, function () {
var dialog = $(this).dialog({ autoOpen: false });
...
});
In Firefox 11, $(this).dialog({ autoOpen: false }) fails with the following error message:
$(this).dialog is not a function
But in IE 9 an Chrome 17 everything is working fine. Any clue why that is?
UPDATE:
Here is my document.ready function where the code above was. I removed it to simplify things. ALERT A is occuring before ALERT B. ALERT A says [object Object]. ALERT B occurs when I click on a link and it says 'undefined'.
$(function () {
alert($.ui); // ALERT A
// Wire up the click event of any dialog links
$('.dialogLink').live('click', function () {
alert($.ui); // ALERT B
return false;
});
});
UPDATE 2:
Now that I pin pointed where the problem was coming from I rephrased my question and posted the minimal code to reproduce the original problem here: Why is FF on OS X losing jQuery-UI in click event handler?
You've got a bit of a syntax/chaining issue if I'm not mistaken:
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
//var dialogDiv = $(document.createElement('div')).attr("id", dialogId);
//dialogDiv equals the attribute 'id'
//try and console.log(dialogDiv) right here. what I think you want is:
var dialogDiv = $("<div />");
dialogDiv.attr("id", dialogId).load(this.href, function () {
var dialog = $(this).dialog({ autoOpen: false });
...
});
I also don't think this is the correct way to initialize what you're trying to do... can you describe what's going on, on your page?
you may think about doing something like this:
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000);
//Build some HTML here in the dialog div, or in a string.
theHTML = $('#'+dialogId).html() || "<p>This is a string of HTML</p>";
$('body').on('click', ".button" function () {
console.log($.ui);
$.dialog({autoOpen:true, html: theHTML})
});
The problem was with a Firefox Add-On. I started Firefox in safe mode, and now everything is working fine. I tried to identify which Add-On caused the problem, and I restarted Firefox with various Add-Ons turned on or off, but I can't seem to be able to reproduce the problem now.

Javascript in Safari not always running

Am having an issue with Safari. I have a basic script using jQuery that makes some changes to a form field and adds some behaviours to it. When I run this script on using the document ready method it's fine in Firefox but in Safari it doesn't always run the initial changes. I can hit refresh and get it running fine 4/5 times, but sometimes it just doesn't initialise like it should.
This is running on a local server so the refresh is pretty quick, I'm wondering if the javascript is executing before the page has finished loading. I've tried calling the script in the foot of the page rather then the header but that hasn't helped. I remember hearing about different browsers firing document ready at different times and thought this would help remedy it but it hasn't and I can't find any further information on that topic.
Anything I'm missing that could be the issue or a workaround? The script itself doesn't seem to be at fault. Am using the jQuery colours plugin, apart from that it's only jQuery and my script.
Help is always appreciated, thanks people!
Here is the code. initSearchBox() is run using the line below in the header.
$(document).ready(function() { initSearchBox() ; });
function randomFieldValue(){
var options = new Array(
'Lorem',
'Ipsum',
'Dolor',
'Sit',
'Amet'
)
t = Math.floor(Math.random()*(options.length - 1));
return options[t] ;
}
function initSearchBox(){
instanceDefText = randomFieldValue() ;
$('#search-form-field')
.attr('value',instanceDefText)
.css('color','#fff')
.animate({color:'#999'},1500)
.focus(function(){
if($(this).attr('value') == instanceDefText){
$(this).attr('value','')
.css('color','#000')
}
})
.blur(function(){
if($(this).attr('value') == ''){
instanceDefText = randomFieldValue() ;
$(this).attr('value',instanceDefText)
.css('color','#fff')
.animate({color:'#999'},1500)
}
});
}

Categories

Resources