JSONP and DOCTYPE Errors - javascript

I'm running into a weird problem.
I'm communicating with my server using AJAX. (I'm running my web application on localhost).
Server is located on, say, http://www.example.com
To bypass the Same Origin Policy, I'm using JSONP. I dynamically create a <script> tag and load the data from my server.
So far so good.
Then I decided to upload my web application to this subdomain: http://m.example.com
That's when I run into crazy errors. Sometimes the page loads, sometimes it doesn't. When it doesn't load, Firebug throws a DOCTYPE error.
I did some research and came across this stackoverflow post: firebug returns syntax error in doctype?
Quoting an answer in this link:
This usually happens because you are loading an HTML document as a script. This is often caused by <script src=""></script> (i.e. a relative URI pointing at the current, HTML, document)) or one of the scripts pointing to a 404 error.
Pretty helpful stuff. Based on all that, I've concluded from all the above that whenever my server responds slowly, the <script> tag's src attribute is null. Since that throws a 404 error, I get a DOCTYPE error in Firebug. Whenever my server responds quickly, there are no issues and everything works fine.
How do I solve this problem? I could put a manual timeout or something, but that wouldn't exactly be foolproof and an elegant solution.
Any help guys?
EDIT:
Here's some code:
This function is used to create the script tag dynamically:
function appendScriptToHead() {
var element = document.createElement("script");
element.src = 'http://www.example.com/?data&callback=callfunction';
document.getElementsByTagName("head")[0].appendChild(element)
}
This callback function is called when the above url containing JSONP data is loaded:
function callfunction(response) {
alert(response);
}

I think there's a bit of misunderstanding here. Your script element will always have its src property set, but its contents depends on your server's response. I doubt it'll be error 404 (as it refers to the element not found, which is hardly repetitive), but it can be of 500 flavors.
I suggest debugging your queries just as they are (i.e., opening http://www.example.com/?data&callback=%callfunction% with your browser or some scripted HTTP UserAgent, if you feel industrious), to see what might be wrong with the logic which selects the script to be loaded.

Related

How can I get the reason for img.onerror firing?

For example, the webserver sends back a 403 forbidden and the image fails to load. I can detect the general failure through the error event, but I want to get some more information about why. The browser obviously knows, but is there a way to get it from javascript?
Workarounds may be to try and load the image via ajax or issue a HEAD request and assume the error will reoccur. Neither seem great though.
just open fire-bug or developers tools and look in net tab. there should be every request the browser made with corresponding response including all headers and response body. Find the call for your image and you should see what the server answer really is.
edit> oh sorry, now I see you need to get the info with javascript

Replacing entire page via AJAX causes Permission Denied error in IE only

I have an AJAX post that retrieves data from the server and either replaces part of the page or in some cases the full page. This is controlled by a javascript fullRefresh parameter. The problem is the refresh code works find in Firefox but causes a Permission Denied error in the bowels of JQuery after it runs in IE although it would appear to actually replace the page contents successfully.
IE version 11.0.9600.16659
JQuery version 1.8.2
Error message
Unhandled exception at line 2843, column 3 in http://localhost:62761/Scripts/jquery-1.8.2.js
0x800a0046 - JavaScript runtime error: Permission denied
My code is
function RefreshScreenContent(formActionUrl, formHTML, fullRefresh) {
fullRefresh = (typeof fullRefresh === "undefined") ? false : fullRefresh;
if (fullRefresh) {
document.write(formHTML);
document.close();
}
else {
$("#content-parent").html(formHTML);
}
}
The partial refreshes work fine but the full refreshes are the problem. I have tried hardcoding the document.write call to write a well formed simple html page rather than formHTML in case that was somehow the problem but even a simple single word page causes the error.
The actual error occurs a some point later with a callback inside JQuery.
The AJAX post to the server is in the same application i.e. is not a cross domain request. I have seen posts online talking aboue cross domain stuff that is not applicable here.
Can anyone tell me why this is happening and how to stop it? Is there an alternative IE way of replacing the page contents?
Your code is fine (at least at first glance). My guess is that you make the call in such a way, that it is interpreted as cross-domain.
I would suggest checking:
http vs https (most common)
the destination port
the root url
maybe the "destination" page makes some requests of its own, check to be on same domain
The reason why IE may be the only one with the problem is that it has higher security demanding by default that other browsers (check advanced security settings - can't remember where they are put in menu) so it interprets requests in a more "paranoid" manor.
I repeat, what I said is just a guess, based on cases I've been put into.
In the end I used the approach here to replace the body tag in the pgae with the one in the markup the AJAX receives back https://stackoverflow.com/a/7839921/463967
I would have preferred to replace all content not just the body but I can always adapt later to include the header etc as body is enough for my uses right now. This works in IE and Firefox.

HTML5 - Cross Browser Iframe postmessage - parent to child communication

I wrote a content script that injects an iframe to any website (therefore different domain).
I need the parent website to send some information to the child iframe, however I couldn't find a way to do it.
The code
var targetFrame = $('#myIframe')[0];
targetFrame.contentWindow.postMessage('the message', '*');
Doesn't work somehow and i get a Cannot call method 'postMessage' of undefined error.
But then when I tried the same code directly in Chrome's console, it worked.
I had no trouble sending a postMessage from the child to the parent though but just need a way for the parent to send messages to the child iframe.
I recently wrote code that did postMessage to an iframe and I encountered quite a similar issue where it said contentWindow is undefined.
In my case, my iframe was not yet part of the DOM tree, it was a variable created by document.createElement('iframe').
Once I put it hidden (width and height 0px, visibility hidden) into the body of the page, contentWindow was no longer undefined and everything worked as expected.
I found the Mozilla Developer Network page for postMessage extremely useful when I was working on my project.
I've had success using the following library:
http://easyxdm.net/wp/
It doesn't require any flash/silverlight, only javascript. And it is compatible as far back as as IE6.
It took a little doing to get it up and running, but once it was things ran very smoothly.
Keep in mind that if the iFrame you're opening on the other domain uses a different protocol (HTTP vs. HTTPS) the browser will kick out a warning which prevents your script from running (unless the user says they will accept the risk). If you have access to both protocols it may be wise to host the contents of the iFrame on both HTTP and HTTPS and load the appropriate script accordingly.
Good luck!
You don't need to target contentWindow. Try this:
var targetFrame = $('#myIframe')[0];
targetFrame.postMessage('the message', '*');

javascript failing with permission denied error message

I have a classic ASP web page that used to work... but the network guys have made a lot of changes including moving the app to winodws 2008 server running iis 7.5. We also upgraded to IE 9.
I'm getting a Permission denied error message when I try to click on the following link:
<a href=javascript:window.parent.ElementContent('SearchCriteria','OBJECT=321402.EV806','cmboSearchType','D',false)>
But other links like the following one work just fine:
<a href="javascript:ElementContent('SearchCriteria','OBJECT=321402.EV806', 'cmboSearchType','D',false)">
The difference is that the link that is failing is in an iframe. I noticed on other posts, it makes a difference whether or not the iframe content is coming from another domain.
In my case, it's not. But I am getting data from another server by doing the following...
set objhttp = Server.CreateObject("winhttp.winhttprequest.5.1")
objhttp.open "get", strURL
objhttp.send
and then i change the actual html that i get back ... add some hyperlinks etc. Then i save it to a file on my local server. (saved as *.html files)
Then when my page is loading, i look for the specific html file and load it into the iframe.
I know some group policy options in IE have changed... and i'm looking into those changes. but the fact that one javascript link works makes me wonder whether the problem lies somewhere else...???
any suggestions would be appreciated.
thanks.
You could try with Msxml2.ServerXMLHTTP instead of WinHttp.WinHttpRequest.
See differences between Msxml2.ServerXMLHTTP and WinHttp.WinHttpRequest? for the difference between Msxml2.ServerXMLHTTP.
On this exellent site about ASP you get plenty of codesamples on how to use Msxml2.ServerXMLHTTP which is the most recent of the two:
http://classicasp.aspfaq.com/general/how-do-i-read-the-contents-of-a-remote-web-page.html
About the IE9 issue: connect a pc with an older IE or another browser to test if the browser that is the culprit. Also in IE9 (or better in Firefox/Firebug) use the development tools (F12) and watch the console for errors while the contents of the iFrame load.
Your method to get dynamic pages is not efficient i'm afraid, ASP itself can do that and you could use eg a div instead of an iframe and replace the contents with what you get from the request. I will need to see more code to give better advice.

Image Replacement (JS/JQuery) working in IE but not FF

I have tried multiple solutions for replacing broken images (both JS & jQuery) and all work perfectly with IE but not in FF, is there a reason for this?
Are images handled differently in FF that may cause this?
JQuery Example:
$("img").error(function(){
$(this).unbind("error").attr("src", "nopic.jpg");
});
Javascript Example: (triggered by onError event in img tag)
function noimage(img){
img.onerror="";
img.src="nopic.jpg";
return true; }
Both of these examples work perfectly in IE but not at all in FF. What gives?
Thanks in advance!
You're testing locally, aren't you, by pointing at a file URL?
Try testing on an actual server, even if it's just local. I believe that Firefox relies on the HTTP status code returned from the image GET to trigger an error; if you're loading from a file://... URL there's no server involved, so you don't get the error.
From the jQuery API docs for error():
This event may not be correctly fired when the page is served locally. Since error relies on normal HTTP status codes, it will generally not be triggered if the URL uses the file: protocol.
EDIT: As we've discussed in the comments, this appears to be because for some reason your intranet server is not responding to a missing resource with a 404 (or any other error, by the sounds of things.)
Because Firefox doesn't receive an error, it doesn't trigger the error handler, which seems like sane behaviour.
I think your problem just became "my server doesn't return 404 errors for missing content", but you might need to experiment a bit more to gather evidence before asking that one (and possibly ask it on Serverfault rather than on SO...)
You have to bind the error handler first, before setting the src of an image. So setting the src in HTML and then bind it via JavaScript is not working.
You can prove this for yourself: http://jsfiddle.net/4Wcnj/2/.
HTML:
<img width=500 id=img height=500 src="missing1">
JavaScript:
// At this point, missing1 is having an error, but no handler set so far
$("#img").error(function() {
alert("Missing: " + $(this).attr("src"));
});
// The bind handler has been set, now if you set the src wrongly, you
// get the alert
$("img").attr("src", "missing2");

Categories

Resources