i have been trying to figure this out for the past couple hours and was hoping someone here could help out. I am using JQuery 1.6.4 to make an ajax call when a button is clicked and populate the contents of a table with the results. The code works as it should in all browsers except IE. When i run it in IE, some values are populated and the rest are not, very strange!
When i run the script and use IE's debugging tool i get the following error;
Unexpected call to method or property access (line 3)
Does anyone know what i'm doing wrong? Here is my code that runs the ajax;
$(document).ready(function(){
$("#find").click(function () {
//Set kinase
var kinaseEntry = $("#kinaseEntry").val();
var dataString = "kinaseEntry=" + kinaseEntry;
//Fetch list from database
$.ajax({
type : "GET",
url : "http://www.webaddress/php/post.php",
datatype: "json",
data: dataString,
success : function(datas) {
//SET VARIABLES TO BE USED THROUGHOUT PAGE
var kinaseName = (datas.skuName);
var molecularWeight = (datas.molecularWeight);
var kinaseConc = (datas.kinaseConc);
var anti1Name = (datas.antiName);
var anti2Name = (datas.antiName2);
var antiConc = (datas.antiConc);
var antiConc2 = (datas.antiConc2);
var tracerName = (datas.tracerName);
var tracerConc = (datas.tracerConc);
var tracerStockConc = (datas.tracerStockConc);
var tracerSku = (datas.tracerSku);
var kinaseSku = (datas.kinaseSku);
var antiSku = (datas.antiSku);
var antiSku2 = (datas.antiSku2);
var bufferName = (datas.bufferName);
var bufferSku = (datas.bufferSku);
//REAGENT NAMES
$(".kinaseName").html(kinaseName + " (" + molecularWeight + " kDa)");
$(".anti1Name").html(anti1Name);
$(".anti2Name").html(anti2Name);
$(".tracerName").html(tracerName);
$(".bufferName").html(bufferName);
//DEFAULT VALUES
$(".defaultKinaseConc").html(kinaseConc);
$(".defaultAntiConc").html(antiConc);
$(".defaultAnti2Conc").html(antiConc2);
$(".defaultTracerConc").html(tracerConc);
$("#molecularWeight").val(molecularWeight);
$("#tracerStockConc").val(tracerStockConc);
//INSERT DEFAULTS INTO INPUT
$("#userKinaseConc").val(kinaseConc);
$("#userAntibodyConc1").val(antiConc);
$("#userAntibodyConc2").val(antiConc2);
$("#userTracerConc").val(tracerConc);
},
error : function (XMLHttpRequest, textStatus, errorThrown) {
console.log("error :"+XMLHttpRequest.responseText);
}
});
return false;
}); });
The names populate fine and the first default value gets populated, but the rest breaks. Any help would be greatly appreciated.
Here are the results of my console.log();
antiConc
"2"
antiConc2
"2"
antiName
"Biotin-anti-His"
antiName2
"Eu-Streptavidin"
antiSku
"PV6089"
antiSku2
"PV5899"
bufferName
"Kinase Buffer A"
bufferSku
"PV3189"
cleanSKU
null
kinaseConc
"5"
kinaseSku
"P3049"
molecularWeight
"125.4"
skuName
"ABL1"
tracerConc
"100"
tracerName
"Kinase Tracer 1710"
tracerSku
"PV6088"
tracerStockConc
"25"
Are you sure it's working properly in other browsers, or are they just not breaking as significantly.
I'm guessing you have mixed updates happening here (a distinction presumed from val() and html() use). I notice a pattern whereby elements retrieved by id (e.g., #userKinaseConc) and those retrieved by class (e.g., .kinaseName) are using val() and html() respectively. However, #defAntiCon breaks that pattern. You're using html() for this element. Is this element an input or other form field? Should this be val()?
The experience you describe can be re-created by attempting to apply a value to an input field via html() setter rather than val(), with the exception that it still doesn't work for that specific field in all values... browsers other than IE just fail differently and the error becomes non-breaking. In IE, it will break execution. Is #defAntiCon actually being populated based on data returned in other browsers?
IE8 Is strict about HTML insertion. If your markup is invalid, or either have HTML5 specific tags, it will throw an error.
I have no real solution, but I'd follow this steps to make it works.
Make sure your datas contains valid HTML, make sure you have no extra closing tags or syntax error (you can use a validator if needed)
If you are using HTML5 tags, you could try to use html5shiv to make sure the browser will understand all the tags
Make sur you don't use .val() instead of .html() in some cases
You should replace .html(datas.foo) by .text(datas.foo) since you are passing string to the method.
In case you don't find any solutions, you could add a catch block in jQuery resolveWith method (referring to your comment) by doing the following changes :
replace this :
resolveWith: function ( context, args ) {
if ( !cancelled && !fired && !firing ) {
// make sure args are available (#8421)
args = args || []; firing = 1;
try {
while ( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); }
} finally {
fired = [ context, args ];
firing = 0;
}
}
return this ;
},
with this :
resolveWith: function ( context, args ) {
if ( !cancelled && !fired && !firing ) {
// make sure args are available (#8421)
args = args || []; firing = 1;
try {
while ( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); }
} catch (err) {
} finally {
fired = [ context, args ];
firing = 0;
}
}
return this ;
},
Bug on the try-finally in IE is reported here
Hope this helps.
Edit : As #Josh mentionned in the comment, the bug has been reported and resolved in this commit for jQuery 1.7.x. A simple update of your jQuery should works.
Related
I have an ajax function that posts an image, which works perfectly in Chrome and Firefox. Safari and iOS Safari both balk at it, though.
I'm creating and appending the value like this:
var ajaxImage = new FormData();
ajaxImage.append('file-0', $('.some-file-input')[0].files[0]);
I then call this image later, using ajaxImage.entries() to init the iterator for the FormData object, so that I can perform a validation on it. However, in Safari ajaxImage.entries() throws an entries is not a function TypeError.
I guess I could just do the validation before getting to this point as a workaround, but now it's bugging me so I wanted to see if anyone could shed some light on this.
Thanks!
Unfortunately, Safari doesn't support this part of the specification: https://developer.mozilla.org/en-US/docs/Web/API/FormData#Browser_compatibility, specifically the entries method.
I haven't tried it myself, but perhaps a polyfill like this one: https://github.com/francois2metz/html5-formdata might work?
But yes, you might be right -- doing validation before that point might be worth it.
I solved this by conditionally (if Safari is the browser) iterating through the elements property of the form. For all other browser, my wrapper just iterates through FormData entries(). The end result of my function, in either case, is a simple javascript object (JSON) which amounts to name/value pairs. That object can be passed directly to the data property of the JQuery ajax function (with contentType and processData not specified).
function FormDataNameValuePairs(FormName)
{
var FormDaytaObject={};
var FormElement=$('#'+FormName).get(0);
if (IsSafariBrowser())
{
var FormElementCollection=FormElement.elements;
//console.log('namedItem='+FormElementCollection.namedItem('KEY'));
var JQEle,EleType;
for (ele=0; (ele < FormElementCollection.length); ele++)
{
JQEle=$(FormElementCollection.item(ele));
EleType=JQEle.attr('type');
// https://github.com/jimmywarting/FormData/blob/master/FormData.js
if ((! JQEle.attr('name')) ||
(((EleType == 'checkbox') || (EleType == 'radio')) &&
(! JQEle.prop('checked'))))
continue;
FormDaytaObject[JQEle.attr('name')]=JQEle.val();
}
}
else
{
var FormDayta=new FormData(FormElement);
for (var fld of FormDayta.entries())
FormDaytaObject[fld[0]]=fld[1];
}
return FormDaytaObject;
}
where IsSafariBrowser() is implemented by whatever your favorite method is, but I chose this:
function IsSafariBrowser()
{
var VendorName=window.navigator.vendor;
return ((VendorName.indexOf('Apple') > -1) &&
(window.navigator.userAgent.indexOf('Safari') > -1));
}
Example usage with an ajax call:
var FormDaytaObject=FormDataNameValuePairs('FiltersForm');
$.ajax({url: 'AJAXDoSomethingWithFilters/',
method: 'POST',
data: FormDaytaObject,
dataType: 'text',
success: function(data)
{
console.log('AJAXDoSomethingWithFilters success:'+data);
},
error: function(JQXhr,Status,Err)
{
console.log('AJAXDoSomethingWithFilters error:'+Err);
}
});
basically ive been tasked with fixing an none cross browser application. problem is its over use of the .selectSingleNode function. (which ofc is IE only).
i have a replacement being:
function selectOneNode(key, node) {
try {
Response = node.selectSingleNode(key);
}
catch (err) {
var xpe = new XPathEvaluator();
var nsResolver = xpe.createNSResolver(node.ownerDocument == null ? node.documentElement : node.ownerDocument.documentElement);
var results = xpe.evaluate(key, node, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
//Response.ErrorNumber = results.singleNodeValue.text.toString().ToInt();
Response = results.singleNodeValue;
}
return Response;
}
but this .selectSingleNode function is used well over 2000 times in many files, but have no idea how to override the .selectSingleNode function, so i don't need change every instance.
any help?
If u want to override some function you can just write it once again. I've had similar problem but with alert function. I've just done such thing:
function alert(){
//custom code goes here
}
I'm fighting with IE8 and the flashcanvas.js plugin trying to capture a signature.
The demo works fine on IE8, but since I'm using a bunch of other plugins including requireJS, I'm running into some kind of problem on IE8.
I have nailed it down to this:
function onReadyStateChange() {
if (document.readyState === "complete") {
document.detachEvent(ON_READY_STATE_CHANGE, onReadyStateChange);
var canvases = document.getElementsByTagName(CANVAS);
// => returns 1 in IE8 debugger
console.log( canvases.length )
// => returns objectHTMLCollection
console.log( canvases )
for (var i = 0, n = canvases.length; i < n; ++i) {
console.log(" run "+i)
// => this produces an error...
console.log( canvases[i])
// trigger
FlashCanvas.initElement(canvases[i]);
}
}
}
I don't understand why it's not working, but canvases[i] throws an [object HTMLUnknownElement] error.
Question:
Any idea what might be the cause? As a workaroud, how could I select the first element of my objectHTMLCollection without using [] and staying in Javascript!
I have also tried adding an id to the canvas element or select it by class (using Jquery). Same result, length=1, select=forget it.
Thanks for help!
EDIT:
I'm requesting plugins like this from my main app controller:
$(document).on('pagebeforeshow', '#basket', function(e, data){
// signaturePad
var signIt = $('.signatureWrapper');
if ( signIt.length > 0 && signIt.jqmData('bound') != true ) {
signIt.jqmData('bound', true);
require(['services/signature/app'], function (App) {
App.render({target: signIt, drawOnly: true });
});
};
This calls an app.js file, which defines all dependencies required and once everything has loaded, fire the plugin:
define([ 'services/signature/app'
, 'services/signature/jquery.signaturepad.min'
, 'services/signature/json2.min'
, 'services/signature/flashcanvas'
], function( app, signature, json2, flashcanvas ) {
function render(parameters) {
parameters.target.signaturePad({ drawOnly:parameters.drawOnly });
};
return {
render:render
};
});
So, I'm wasting an http-request for flashcanvas.js when I don't really need it. But all files are loaded allright, I believe...
How are you adding the canvas element to the DOM? Since IE8 doesn't support the canvas element, you need to create it dynamically and append it to the DOM, as shown in the FlashCanvas docs
var canvas = document.createElement("canvas");
document.getElementById("target").appendChild(canvas);
if (typeof FlashCanvas != "undefined") {
FlashCanvas.initElement(canvas);
}
Array document.getElementsByName(String balise)
http://www.toutjavascript.com/reference/reference.php?iref=156
You wrote :
var canvases = document.getElementsByTagName(CANVAS);
Are you sure CANVAS is a String ? Maybe you want to write
var canvases = document.getElementsByTagName("CANVAS");
Try to convert the collection to an array:
var arr = Array.prototype.slice.call( canvases );
I know this question has been asked several times, but I couldn't seem to find a solution that worked for me in any of the previous questions. I have a variable that gets set when my HTML page is done loading, but sometimes when my code tries to access that variable, it says that it is undefined. I'm not sure why, since I believe I am waiting for everything to load properly. This exception seems to happen randomly, as most of the time all the code runs fine. Here's a simplified version of my code:
var globalVar;
function initStuff(filePath) {
// I wait till the HTML page is fully loaded before doing anything
$(document).ready(function(){
var video = document.getElementById("videoElementID");
// My parseFile() function seems to run smoothly
var arrayOfStuff = parseFile(filePath);
if (arrayOfStuff == null) {
console.error("Unable to properly parse the file.");
} else {
setGlobalVariable(arrayOfStuff);
video.addEventListener("play", updateVideoFrame, false);
}
});
}
function setGlobalVariable(arrayOfStuff) {
window.globalVar = arrayOfStuff;
}
function updateVideoFrame() {
// A bunch of other code happens first
// This is the line that fails occasionally, saying
// "window.globalVar[0].aProperty.anArray[0] is undefined"
var test = window.globalVar[0].aProperty.anArray[0].aProperty;
}
The only thing that I can think of that might be causing this problem is some sort of synchronicity issue. I don't see why that would be the case, though. Help please!
Edit:
In case the asynchronicity issue is coming from my parseFile(xmlFile) method, here is what I'm doing there. I thought it couldn't possibly be causing the issue, since I force the method to happen synchronously, but in case I'm wrong, here it is:
function parseKML(xmlFile) {
var arrayOfStuff = new Array();
// Turn the AJAX asynchronicity off for the following GET command
$.ajaxSetup( { async : false } );
// Open the XML file
$.get(xmlFile, {}, function(xml) {
var doc = $("Document", xml);
// Code for parsing the XML file is here
// arrayOfStuff() gets populated here
});
// Once I'm done processing the XML file, I turn asynchronicity back on, since that is AJAX's default state
$.ajaxSetup( { async : true } );
return arrayOfStuff;
}
The first thing you should do in your code is figure out which part of:
window.globalVar[0].aProperty.anArray[0]
is undefined.
Since you have multiple chained property references and array references, it could be many different places in the chain. I'd suggest either set a breakpoint right before your reference it examine what's in it or use several console.log() statement sto output each nested piece of the structure in order to find out where your problem is.
console.log("globalVar = " + globalVar);
console.log("globalVar[0] = " + globalVar[0]);
console.log("globalVar[0].aProperty = " + globalVar[0].aProperty);
console.log("globalVar[0].aProperty.anArray = " + globalVar[0].aProperty.anArray);
console.log("globalVar[0].aProperty.anArray[0] = " + globalVar[0].aProperty.anArray[0]);
If the problem is that globalVar isn't yet set, then you have a timing problem or an initialization problem.
If the problem is that one of the other properties isn't set, then you aren't initializing globalVar with what you think you are.
You may also want to write your code more defensibly so it fails gracefully if some of your data isn't set properly.
You need to use defensive programming.
http://www.javascriptref.com/pdf/ch23_ed2.pdf
Example:
var video = document.getElementById("videoElementID") || 0;
-
if( video && video.addEventListener ){
video.addEventListener("play", updateVideoFrame, false);
}
Here's another version of your code.
window.globalVar = globalVar || [];
function setGlobalVariable(arrayOfStuff) {
window.globalVar = arrayOfStuff;
}
function updateVideoFrame() {
// A bunch of other code happens first
// This is the line that fails occasionally, saying
// "window.globalVar[0].aProperty.anArray[0] is undefined"
if( window.globalVar ){
var g = window.globalVar || [];
var d = (g[0] || {})["aProperty"];
// etc...
}else{
console.error( "test error." );
}
}
function initStuff(filePath) {
// I wait till the HTML page is fully loaded before doing anything
$(document).ready(function () {
var video = $("#videoElementID");
// My parseFile() function seems to run smoothly
var arrayOfStuff = parseFile(filePath) || [];
if (arrayOfStuff == null || video == null ) {
console.error("Unable to properly parse the file.");
} else {
setGlobalVariable(arrayOfStuff);
video.bind("play", updateVideoFrame);
}
});
}
This is driving me nuts!
I'm getting some JSON from my server:
{"id262":{"done":null,"status":null,"verfall":null,"id":262,"bid":20044,"art":"owner","uid":"demo02","aktion":null,"termin_datum":null,"docid":null,"gruppenid":null,"news":"newsstring","datum":"11.06.2010","header":"headerstring","for_uid":"demo01"},
"id263":{"done":null,"status":"pending","verfall":null,"bid":20044,"id":263,"uid":"demo02","art":"foo","aktion":"dosomething","termin_datum":"11.06.2010","docid":null,"gruppenid":null,"datum":"11.06.2010","news":"newsstring","for_uid":"demo01","header":"headerstring"},
"id261":{"done":null,"status":null,"verfall":null,"id":261,"bid":20044,"art":"termin","uid":"demo02","aktion":null,"termin_datum":"25.06.2010","docid":null,"gruppenid":null,"news":"newsstring","datum":"11.06.2010","header":"headerstring","for_uid":null}}
This is how my JS looks like:
var user = 'demo02';
new Ajax.Request('myscript.pl?someparameter=value', { method:'get',
onSuccess: function(transport){
var db_json = transport.responseText.evalJSON(),
propCount = 0,
someArray1 = [],
someArray2 = [],
otherArray = [];
//JSON DEBUG
console.log('validated string:');
console.log(transport.responseText.evalJSON(true));
for(var prop in db_json) {
propCount++;
if ( (db_json[prop].art == 'foo') && (db_json[prop].for_uid == user) ) {
someArray1.push(db_json[prop]);
} else if( (db_json[prop].art == 'foo') && (db_json[prop].uid == user) ) {
someArray2.push(db_json[prop]);
} else if( db_json[prop].art == 'log' ) {
otherArray.push(db_json[prop]);
}
}
if(someArray1.length>0) {
someArray1.map(function(el){
$('someArray1target').innerHTML += el.done;
//do more stuff
});
}
if(someArray2.length>0) {
someArray2.map(function(el){
$('someArray2target').innerHTML += el.done;
//do more stuff
});
}
});
Sometimes, it works perfectly.
Sometimes, i get my JSON String (it appears in Firebug's "answer"-tab), but it won't log the JSON in console-log(). I'm not getting any errors and javascript is still working.
Next time after reloading, it might work, but it might not.
I cannot remotely imagine why this only happens sometimes!
You are calling evalJSON twice, actually with different parameters each time.
Normally, I wouldn't expect this to have any side-effects, and indeed the prototype documentations for this method don't mention any. However, I remember that earlier versions of firebug were known to manipulate the XMLHttpRequest in weird ways (in order to capture the data going in and out), so maybe this is still relevant today.
Try changing the log statement to this instead:
console.log(db_json);
I found the answer. It makes me want to slam my head. My $('someArray1target') div sometimes was not loaded yet.
I was so focused in finding something weird in my JSON instead of searching for the more obvious, "standard" errors.