I have an iOS app that loads local HTML via a UIWebView. The HTML is connected to jquery with AJAX. For the HTML, I have a content folder and a container folder. The Content folder has a lot of html files and the container folder has one html file that opens the smaller html's in the container folder in a specific order. The problem is the Container HTML will not load anything from the container folder because of the cross-domain restrictions in AJAX. Is there anything I can add via Xcode that will let me by pass the restrictions or anything I can add the HTML/Jquery that will let me Bypass it? Thanks in advance!
//ReplaceDIV
function loadInDiv(source)
{
// alert('start');
$.ajax({
url: source,
async: false,
crossDomain: true,
success: function(data) {$('#content').append(data);},
});
// $.get(source, function(data) {
// alert(data);
// $('#contents').append(data);
// });
// $(destination).load(source);
}
remove:
crossDomain: true,
you should be all set.
Edit:
As I understand it, the task at hand is using ajax to load the contents of one html file to another on the same server. When that is done in a UIWebView from a local resource that would be a localhost request. From the [JQuery Documentation:
If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain.
On a localhost request, forcing a cross domain request would break the request causing it to load nothing. Also, as a side note, cross domain requests are incompatible with synchronous requests, which you have set with:
async: false,
Related
I am loading a user-selected page into an iframe using the src property. If the load fails, I would like to report the problem in terms that will make sense to the user. iframe does not, in general, support onerror according to http://www.w3schools.com/jsref/dom_obj_frame.asp.
The page may come from the user's domain, not mine, so I cannot view the content of the iframe.
I can set a timeout and cancel it from my onload handler if the load is successful, but it would need to be a long timeout to avoid false error reports, and meanwhile Safari on my iPhone has displayed an alert that may confuse the user. Even this does not work for the Kindle Fire browser - it delivers a load event to my handler regardless of whether the load was successful.
Is there any event I can use to detect failure? Is there any way to suppress the default Safari behavior? Any way I can tell whether the load attempt has failed? (If I could do that, I could use a shorter timeout and poll until the load attempt is resolved).
I can require the use of up to date browsers, but would like a solution that is portable among as many smartphones and tablets as possible.
I have tested the AJAX Get idea, and it unfortunately does not work. A cross-domain AJAX Get to an arbitrary URI results in an exception, regardless of whether the target exists and can be loaded into the iframe or not.
You could set your iframe and/or ajax request to always call a page you control (ie: loader.php), sending loader.php the user's requested page via get. From loader.php, use curl or even just file_get_contents to fetch the external page. If the request fails to come back to loader.php, you can check the error there, and return whatever you want your iframe to display.
While my example references the use of php, curl is supported in a variety of scripting languages. It is likely more complicated than other solutions you might have, but would give you access to the response headers as well for troubleshooting why a page load failed.
As you've hinted, you'll face same-origin-policy type restrictions when you try to query anything inside the iframe if it's on a separate domain.
You could make an AJAX GET request to the iframe's URL before you pass it into the src of the frame. If you don't get an HTTP 200 response back from the AJAX call, then the site won't be able to load inside the frame either.
This will add overhead to the whole process, and is only useful if you're checking whether the iframe's document is a real URL that works. It won't help if you need to know when the iframe document has fully loaded.
If you need to know when the iframe has loaded, and it's on an external domain, then I believe you have no other option but to ask for some code to be added to those external sites to notify the parent page that they've loaded successfully.
Or, if it makes sense to do so, ask the end user to click a link to flag up that the content isn't loading correctly.
Late to the party, but I've managed to crack it:
At first, I thought to do an AJAX call like everyone else, except that it didn't work for me initially, as I had used jQuery. It works perfectly if you do a XMLHttpRequest:
var url = http://url_to_test.com/
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status != 200) {
console.log("iframe failed to load");
}
};
xhttp.open("GET", url, true);
xhttp.send();
Edit:
So this method works ok, except that it has a lot of false negatives (picks up a lot of stuff that would display in an iframe) due to cross-origin malarky. The way that I got around this was to do a CURL/Web request on a server, and then check the response headers for a) if the website exists, and b) if the headers had set x-frame-options.
This isn't a problem if you run your own webserver, as you can make your own api call for it.
My implementation in node.js:
app.get('/iframetest',function(req,res){ //Call using /iframetest?url=url - needs to be stripped of http:// or https://
var url = req.query.url;
var request = require('https').request({host: url}, function(response){ //This does an https request - require('http') if you want to do a http request
var headers = response.headers;
if (typeof headers["x-frame-options"] != 'undefined') {
res.send(false); //Headers don't allow iframe
} else {
res.send(true); //Headers don't disallow iframe
}
});
request.on('error',function(e){
res.send(false); //website unavailable
});
request.end();
});
I am using .ajax function to read data from an external page .
I am not able to read the page and I get the exception as Access Control Allow origin.
i want to show the data of another page in my page I even set crossdomain:true but it dint help
$.ajax({
type: "GET", url: myurl,
dataType: "html",
crossDomain:true,
success:parsehtml});
How to read an external html page using jquery ?
The underlying Javascript engines in most modern browsers don't permit Cross-Domain transactions. You will have to use a server-side language such as PHP to do this. Mozilla has a fairly decent description of this issue.
There is one solution without using any server side technologies. Please see this
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-cross-domain-ajax-request-with-yql-and-jquery/
You may have to process the returned output to suit your need.
I am developing a Chrome/Chromium extension that will be reading school grades from the school system with grades. Problem is that site doesn't remember logged user. Because of this, I cannot use AJAX.
Only if I'm logged to that page on other tabs. But I want to login to that page in the background and automatically. The solution may be maybe iframe tag, but Chrome/Chromium don't allow me to read and manipulate with iframe content. Is there any solution how to manipulate in the page as the logged user? Thank you
You can emulate form submit through javascript from a background page. First you need to carefully inspect what data is sent through the login form and to which URL (form could be altered with javascript before sending so you need to know what actually is sent, not just what's in <form> element). You can use Chrome's console for simple stuff, if it is not enough then there is Tamper Data plugin for Firefox, and for hardcore traffic inspection you can use Wireshark analyzer.
Then in a background page (I am using jQuery here):
$.ajax({
url: "https://login_form.html",
type: "GET",
dataType: "html",
success: function() {
$.ajax({
url: "https://login_form_submits_to.html",
type: "POST",
data: {
"username": "username",
"password": "password",
"extra_field": "value"
},
dataType: "html",
success: function(data) {
//now you can parse your report screen
}
});
}
});
Good thing is that Chrome persists session and cookies, so it is like logging in manually (if you now open your site in the browser you should be logged in).
How about using cURL to invisibly log the user into the system, and then return the results from a JSONP call?
I have a problem with sending some custom headers to with a jQuery ajax JSON (or JSONP) request.
Code looks like this:
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader("X-VER", VER);
xhr.setRequestHeader("X-TIMESTAMP", now);
},
type: 'GET',
data: null,
url: site_uri,
dataType: 'jsonp',
success: function(msg){$(selector).html(msg);}
});
Firebug shows no custom headers. In addition the url changes with jsonp (can I change this?)
Edit:
I found that it probably violates http://en.wikipedia.org/wiki/Same_origin_policy but have no idea how to get it fixed (the script can't be on the same domain).
Thanks for any help
If you have server access, a solution would be HTTP access control modification. Otherwise, probably the best idea is some kind of reverse proxy solution, I have no idea how good of support access control has outside of Firefox.
jsonp isn't XHR (you are simply adding script elements to the head), emulating XHR. Hence, you can't set custom headers.
I'm using the flickr api to create a simple gallery based on images pulled in by their tag.
The gallery is working fine in every browser except ie6. When you navigate to the page (by clicking a link) in ie6, the $.ajax success/error code blocks refuse to fire, however when the page is reloaded, or navigated to directly (by entering a url) there are no problems.
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=" + api_key + "&user_id=" + user_id + "&tags=" + tags + "&format=json&jsoncallback=?",
cache: false,
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
success: function(data) {
alert('good');
},
timeout: 2000,
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
The above code is obviously a simplified version of the actual javascript, but the bug is still present.
Any help would be greatly appreciated. This seems to be a very weird bug. Perhaps it's a caching issue?
This problem is pretty recurrent. IE caches AJAX calls. You need to append a random number or string to your call each time so that it doesn't run a cached call.
url: "http://[your url]&rand=" + Math.Random(),
Two thoughts:
Is your call within a
$(document).ready() block?
Try getting rid of the ampersand
right at the beginning of the query
string:
/?method=flickr.photos.search&...
How is the "link" triggering the AJAX load?
inline onclick="doSomething();"
inline href="javascript:doSomething();"
via jQuery $('#somelink').bind('click', doSomething);
something else?
I ask because IE6 has a known bug whereby if you have/use the javascript: protocol on a link... then use JavaScript to load a different page it requests the page but never renders it. I wonder if (depending on how your AJAX is attached) if the above bug extends to AJAX requests not just location.href requests.
Four things related to your code but not to your question:
timeout is not taken into account by $.ajax when dealing with jsonp
nor is contentType
the error callback is never called in the context of a jsonp request
You should really use the data parameter (the code would be far cleaner than with the custom url building it currently shows)
Point 1 & 3 are due to limitations in the way $.ajax is implemented. I recommend http://code.google.com/p/jquery-jsonp/ if you really need those features.
Now, apart from what karim79 pointed out, I see nothing wrong with your code. So my guess is you have something else going wrong prior to it in the function you feed to $(document).ready(). IE is far less lenient than other browsers when it comes to javascript syntax. Try putting the $.ajax call as early as possible.
Also:
Does it work in IE7?
What version of jQuery are you using?