been having trouble with this script, ive managed to get it working in ie8, works on chrome fine.
initilize: function(){
$('#my_form').submit(function(){
if ($.browser.msie && window.XDomainRequest) {
var data = $('#my_form').serialize();
xdr=new XDomainRequest();
function after_xhr_load()
{
response = $.parseJSON(xdr.responseText);
if(response.number =="incorrect format"){
$('#errors').html('error');
}
else
{
$('#errors').html('worked');
}
}
xdr.onload = after_xhr_load;
xdr.open("POST",$('#my_form').attr('action')+".json");
xdr.send(data);
} else {
$.ajax({
type: "POST",
url: $('#my_form').attr('action')+".json",
data: $('#my_form').serialize(),
dataType: "json",
complete: function(data) {
if(data.statusText =="OK"){
$('#errors').html('error');
}
if(data.statusText =="Created"){
response = $.parseJSON(data.responseText);
$('#errors').html('Here is your code:' +response.code);
}
}
});
}
return false;
});
}
I understand that ie7 does not have the XDomainRequest() object. How can I replicate this in ie7.
Thanks, in advance
You are not going to get that code to work in IE7 since is cross domain calls are not supported in that old browser. You either need to change the backend to do a JSONP call or you need to use a serverside proxy.
Related
I'm working on this ajax request with CodeIgniter 3. What I'm doing is press on checkbox and the event calls the function changVisib(). as you will see in the snippet, everything goes well because alert() is called.
But $.ajax() call is completely ignored. I tried $.post(). but no response.
I have searched the web for similar issues, but mine seems different. That's why I'm obliged to ask.
function changVisib(elem, picId) {
if (elem.type === 'checkbox') {
var cva = 0;
if (elem.checked) {
cva = 1;
} else {
cva = 0;
}
alert('ok up to here');
$.ajax({
type: "POST",
url: "<?php echo base_url()?>admin/gallery_update",
data: {id: picId, shown: cva},
dataType: "json"
});
}
}
Other jQuery functions work perfectly well. But the call to ajax, post, get seems not to work.
You need to add a success handler so that you know that the ajax request finished
function changVisib(elem, picId) {
if (elem.type === 'checkbox') {
var cva = 0;
if (elem.checked) {
cva = 1;
} else {
cva = 0;
}
alert('ok up to here');
$.ajax({
type: "POST",
url: "<?php echo base_url()?>admin/gallery_update",
data: {id: picId, shown: cva},
dataType: "json",
success: function(data){
alert( "success" );
}
});
}
}
data - the return data from the ajax request
Read more about the ajax jquery method here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...in_statement
I just discovered where the issue was. ajax queries were ignored because I was using the slim version of jQuery.
I have come to learn that jquery-3.5.1.slim.min.js does not include ajax and effects, according to https://jquery.com/download/.
The below code doesn't run in IE7/8. I researched online, .innerhtml will not work in IE 7/8 Browser. I really need this code to run in those browsers.
$(document).ready(function(){
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1);
$.ajax({
type: "GET",
url: "/get_header",
data: hashes,
success: function(data) {
if (!$.support.leadingWhitespace) {
alert('j');
document.getElementById('logo-bar').innerHTML = data;
} else {
$('#logo-bar').html(data);
}
},
error: function(data) {}
});
You're using jQuery for the AJAX request, so you may as well use it to update the DOM too. If you are concerned about leading whitespace in the response text, you can use $.trim() to remove it:
success: function(data) {
$('#logo-bar').html($.trim(data));
},
Is there a way to add a custom http header into the request done by an <iframe> when changing the source (src) using javascript?
You can have the results of an ajax request that has custom headers be set as the content of an iframe like so:
$.ajax({
type: "GET",
url: "https://app.icontact.com/icp/a/",
contentType: "application/json",
beforeSend: function(xhr, settings){
xhr.setRequestHeader("some_custom_header", "foo");},
success: function(data){
$("#output_iframe_id").attr('src',"data:text/html;charset=utf-8," + escape(data))
}
});
This is assuming the iframe is pointing at a cross domain src. It is simpler if everything is on the same domain.
Edit: Maybe try this variation.
$.ajax({
type: "GET",
url: "https://app.icontact.com/icp/a/",
contentType: "application/json",
beforeSend: function(xhr, settings){
xhr.setRequestHeader("some_custom_header", "foo");},
success: function(data){
$("#output_iframe_id").attr('src',"/")
$("#output_iframe_id").contents().find('html').html(data);
}
});
Rather than using a data URI, or setting the contents to a string, you can use URL.createObjectURL(), and set it as the src of the iframe.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'some.pdf');
xhr.onreadystatechange = handler;
xhr.responseType = 'blob';
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
// this.response is a Blob, because we set responseType above
var data_url = URL.createObjectURL(this.response);
document.querySelector('#output-frame-id').src = data_url;
} else {
console.error('no pdf :(');
}
}
}
The object URLs are pretty interesting. They're of the form blob:https://your.domain/1e8def13-3817-4eab-ad8a-160923995170. You can actually open them in a new tab and see the response, and they're discarded when the context that created them is closed.
Here's a full example: https://github.com/courajs/pdf-poc
I ended up going with the approach proposed by the other answers here, that use ajax to get the html string and then directly set the contents of the iFrame.
However, I used the approach posted in this answer to actually set the contents of the iFrame, as I found it worked well cross platform with almost all devices I could dig up.
Tested - successful:
Chrome 54 (desktop) ^
Firefox 49 (desktop) ^
IE 11 (desktop) ^
IE 10 (desktop) in emulation mode ^
Safari/Chrome on iOS 8 (ipad)
Chrome on Android 6 (nexus phone)
Edge on Lumia 950 (Win 10 Phone)
^ confirmed that linked css and js in the content run correctly (others not tested)
Tested - unsuccessful:
IE 9 (desktop) in emulation mode
Safari/Chrome on iOS 7 (iPhone)
So putting them together gives something like this (Note: I havn't actually run this exact code):
$.ajax({
type: "GET",
url: "https://yourdomain.com/gethtml",
beforeSend: function(xhr) {
xhr.setRequestHeader("yourheader", "value");
},
success: function(data) {
var iframeDoc = document.querySelector('#myiframe').contentWindow.document;
iframeDoc.open('text/html', 'replace');
iframeDoc.write(data);
iframeDoc.close();
}
});
Here's an example of setting the iFrame contents in this JS Bin
Edit: Here's the html part
<iframe id="myiframe" src="about:blank"></iframe>
Edit 2:
The solution above appears to no longer be working in Firefox (50.1.0) for some unknown reason. Using the solution in this answer I've now changed to code to the example below, which also seems to be more robust:
$.ajax({
type: "GET",
url: "https://yourdomain.com/gethtml",
beforeSend: function(xhr) {
xhr.setRequestHeader("yourheader", "value");
},
success: function(data) {
var iframe = document.getElementById('myiframe');
iframe.contentWindow.contents = data;
iframe.src = 'javascript:window["contents"]';
}
});
The following code works. It is a modification of the code provided by Matthew Graves, modified to use the srcdoc attribute to solve the problem of CSS and JavaScript references not been ran. Unfortunately, it is only working in Chrome.
$.ajax({
type: "GET",
url: "https://app.icontact.com/icp/a/",
contentType: "application/json",
beforeSend: function(xhr, settings){
xhr.setRequestHeader("some_custom_header", "foo");},
success: function(data){
$("#output_iframe_id").attr('srcdoc',data)
}
});
Edit: Finally, I have resolved the issue of the scripts blocks cross-browser, by reassigning them to the iframe on document.ready function:
$(document).ready(function () {
var doc = $(document);
if (frames.length > 0) {
doc = frames[0].document;
$(doc).find('script').each(function () {
var script = document.createElement("script");
if ($(this).attr("type") != null) script.type = $(this).attr("type");
if ($(this).attr("src") != null) script.src = $(this).attr("src");
script.text = $(this).html();
$(doc).find('head')[0].appendChild(script);
$(this).remove();
});
}
});
Hi I have built a web app and everything was working ok until I tested on IE9 with JSON files coming from another domain
Basically all of out JSON files are stored on AMAZON.
The idea on the first load is that I get a site.json file and this initializes and setups the app - but in IE9 and periodically in Safari and Chrome I am getting cross domain errors
So this is some extracts from the head of my homepage
<meta http-equiv="Access-Control-Allow-Origin" content="*"/>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
<script type="text/javascript">
var SiteConfig, frameworkHost;
$(document).ready(function() {
var promise = $.ajax({
url: '//s3-ap-southeast-2.amazonaws.com/****/site.json',
method: 'get',
dataType: 'json'
});
$.when(promise).then(function(result) {
SiteConfig = result.data;
frameworkHost = '//s3-ap-southeast-2.amazonaws.com/**/public_html';
var requireTag = document.createElement('script');
requireTag.setAttribute('type', 'text/javascript');
requireTag.setAttribute('src', frameworkHost + '/js/require/require.js');
requireTag.setAttribute('data-main', frameworkHost + '/js/bootstrap');
document.head.appendChild(requireTag);
});
});
</script>
but the problem is as soon as the url to get site.json is not local on IE9 it fails.
Also in chrome, and safari on iphone 4s with ios 5 on occasions i get this error
XMLHttpRequest cannot load http://s3-ap-southeast-2.amazonaws.com/*. Origin It is not allowed by Access-Control-Allow-Origin
when i clear the cache this works though. It works perfectly on FF.
Can anyone help?
Thanks
if ($.browser.msie && window.XDomainRequest) {
// Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.open("get", "someurl");
xdr.onload = function () {
var JSON = $.parseJSON(xdr.responseText);
if (JSON == null || typeof (JSON) == 'undefined')
{
JSON = $.parseJSON(data.firstChild.textContent);
}
processData(JSON);
};
xdr.send();
} else {
$.ajax({
type: 'GET',
url: "someurl",
processData: true,
data: {},
dataType: "json",
success: function (data) { processData(data); }
});
}
I'm trying to make a JavaScript that is fetching a JSON (IP DATA) and retrieves data from it (GEO IP) with AJAX and this is what I have so far:
$(document).ready(function(){
var path_to_the_webservice = "http://www.pathtothescript.com/check.php";
$.ajax({
url: path_to_the_webservice,
success: function(html)
{
if(html)
{
alert('3');
$('#content').append(html);
}
else
{
alert('4');
}
}
});
});
and I get alert(4), WHY?
Basically when you access http://www.pathtothescript.com/check.php from browser, retrieves a JSON that I have to parse with:
$.getJSON(path_to_the_json,
function(data)
{
$.each(data, function(i,item)
{
});
}
but I'm not sure how to make it.
The JSON looks like this http://j.maxmind.com/app/geoip.js
Any help?
It can be caused by Same origin policy.
Try to use JSONP request:
$.getJSON('http://example.com?callback=?', function(data) {
console.log(data);
});
Handling the response from http://j.maxmind.com/app/geoip.js
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.get('http://j.maxmind.com/app/geoip.js', function(data) {
console.log('Retrieved data:',
data,
'is type of', typeof data);
// Now we have some functions to use:
console.info('Some info:', geoip_country_name(),
geoip_latitude(),
geoip_longitude());
});
Fiddle
UPDATE:
In chat we found that my previous example works good in Google Chrome but doesn't work in Mozilla Firefox.
Though I played a little bit with it and found the solution:
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.ajax({
url: 'http://j.maxmind.com/app/geoip.js',
type: 'GET',
success: function(data) {
// Now we have some functions to use:
alert(geoip_country_name() + ': ('
+ geoip_latitude() + '; '
+ geoip_longitude() + ')');
},
error: function(e) {
console.log('Error:', e);
},
contentType: 'application/javascript; charset=ISO-8859-1',
dataType: 'script'
});
Fiddle
Also I've set a charset accordingly to service documentation.