Why won't this script do anything in IE - javascript

I could use another pair of eyes. This script does what I want in Chrome (renders a gallery of images from a google picasa web album), but doesn't render anything in IE8, can anyone see anything obvious?
$(function () {
var json_Photo_URI = "https://picasaweb.google.com/data/feed/base/user/111727095210955830593/albumid/5420114965919213729?alt=json&fields=entry(title, media:group)&thumbsize=75"
$.ajax({
type: 'GET',
url: json_Photo_URI,
success: function (data) {
var photo_URL = "";
var photo_Thumb_Url = "";
$.each(data.feed.entry, function (i, item) {
$.each(item.media$group.media$content, function (i, item) { photo_URL = item.url; });
$.each(item.media$group.media$thumbnail, function (i, item) { photo_Thumb_URL = item.url; });
var photo_Description = item.media$group.media$description.$t;
$('#gallery').append("<a href='" + photo_URL + "' title='" + photo_Description + "'><img src='" + photo_Thumb_URL + "'></a>");
});
$('#gallery a').lightBox({ txtImage: 'Photo', txtOf: '/' });
}, dataType: 'json'
});
});

Replace:
dataType : 'json'
with
dataType : 'jsonp'
See: http://jsfiddle.net/b36v5/2/

It's about cross domain AJAX requests. The site you are trying to access correctly sets the access-control-allow-origin: * response header in order to allow AJAX requests for browsers that support CORS. And IE supports CORS, partially. In fact in IE in order to support CORS you have to use a different object called XDomainRequest as explained in the following blog post in order to achieve cross domain requests. Except that jQuery.ajax doesn't support it out of the box. And if you look more carefully in the bug ticket you will see that it is closed because there are plugins that allow to achieve that.

Related

Opera not handling Ajax patch request properly on rails

I'm having issues with submitting data to Rails app from Opera browser. Chrome, Firefox, Safari and IE all seems to be working, but Opera is failing at PATCH request.
My script is:
var sendForm = function(type){
if (type == "POST")
var url = window.location.protocol + '//' + window.location.host + '/account/surveys/' + $('#survey-id').val() + '/respond';
else
var url = window.location.protocol + '//' + window.location.host + '/account/surveys/' + $('#survey-id').val() + '/respond_upd';
$.ajax({
type : type,
url : url,
dataType: 'json',
contentType: 'application/json',
data : JSON.stringify({
"survey": {
"id": $('#survey-id').val(),
"survey_answers_attributes": responses(),
"user_qualities_attributes": serializeQualities()
}
})
});
};
So POST and PATCH are using pretty much the same thing, just targeted at different urls.
Now POST works fine, I get it all working and Rails log shows following params:
parameters: {"survey"=>{"id"=>"66", "survey_answers_attributes"=>[{"question_id"=>"1", "response"=>"Don't know", "survey_id"=>"66", "user_id"=>"155"}, {"question_id"=>"2", "response"=>"Don't know", "survey_id"=>"66", "user_id"=>"155"}, {"question_i....
PATCH however results in params like that:
parameters: {"id"=>"66", "survey"=>{}}
Any idea what might be happening here? This issue is killing me

Read media\\:thumbnail RSS feed with Jquery

I'm writing a chrome extension and I'm trying to get the RSS feed "media:thumbnail" but the function el.find('media\:thumbnail').attr('url') outputs 'undefined'.
Here's my code :
$.get("http://www.reddit.com/.rss", function (data) {
$(data).find("item").each(function () { // or "item" or whatever suits your feed
var el = $(this);
$("tbody").append("<tr><th>" + el.find('media\\:thumbnail').attr('url') + "</th><td>" + el.find("title").text() + "</td></tr>");
});
});
There is something in JS that is called "same origin policy". It means that you cannot query stuff, that is not from the same domain, using the same protocol and uses the same subdomain.
You need to research "cors" to make calls to another domain possible, but in this case, this won't help you. Cors needs you to include stuff in the http response header.
Another way out is to configure your web server as a reverse proxy and mask the requests from reddit as a local call.
Here is the scripts that will help
First, you need a server script that will pick crosdomain content
<?php // crossdomain php script
header('Content-type: application/xml');
header('Access-Control-Allow-Origin: *');
ini_set('error_reporting', E_WARNING );
$str_xml = '';
if ($_POST['source'] === 'reddit') {
$str_xml = file_get_contents('http://www.reddit.com/.rss');
}
die($str_xml);
?>
Then make Ajax requests and parse response xml
$.ajax({
type: "POST",
url: "crossdomain.php",
dataType: "xml",
data:{source:"reddit"},
success: function(xml){
var xmlText = new XMLSerializer().serializeToString(xml);
$(xmlText).find("media\\:thumbnail").each(function(){
$("tbody").append("<tr><th>" + $(this).attr('url') + "</th><td>" + $(this).parent().find("title").text() + "</td></tr>");
});
}
});
I found a workaround. I use the element "description" of the RSS feed. It contains the link to the image.
Xml :
<description>
<table> <tr><td> <img src="http://b.thumbs.redditmedia.com/50jHjrHnJTSIX_Q86UUXe1Kc-rAxYyhEd90GeUDJHao.jpg" alt="Cat walks into a bar." title="Cat walks into a bar." /> </td><td> submitted by _dear_ms_leading_ to funny <br/> [link] [69 commentaires] </td></tr></table>
</description>
Jquery :
$('' + el.find('description').text()).find("img").attr("src")
I cannot believe that people do not understand this question and give an answer about something else.
The questioner does not mention CORS or any possible error that could point to it.
The question is simply asking about JQuery selectors on XML nodes rather than HTML, the fact that he is using AJAX to get an RSS feed is irelivant, so one can assume that CORS is not an issue in this case.
I had been struggling with the exact same thing, apparently double backslash is supposed to escape, but doesn't seem to work in this case.
What I did instead is use the JQuery attribute selector with the attribute url, all thumbnails have url attributes in my case.
So your code would be:
$.get("http://www.reddit.com/.rss", function (data) {
$(data).find("item").each(function () { // or "item" or whatever suits your feed
var el = $(this);
$("tbody").append("<tr><th>" + el.find('[url]').attr('url') + "</th><td>" + el.find("title").text() + "</td></tr>");
});
});
Update
It might be better to use map
$.get("http://www.reddit.com/.rss", function (data) {
var tbody = $('tbody');
tbody.append(
$(data).find("item").map(function () { // or "item" or whatever suits your feed
var el = $(this);
return $("<tr><th>" + el.find('[url]').attr('url') + "</th><td>" + el.find("title").text() + "</td></tr>");
}).get()
);
});
I have tested it mind

Jquery Ajax url two times

I have an strange problem with Ajax.
var base_url = 'https//m4th.nl/'; // Alle groepen van deze school ophalen
$.ajax({
type: "POST",
async: false,
url: base_url + "rapportage/get/groups/",
success: function(data) {
$.each($.parseJSON(data), function(i, item) {
$('select[name="leerling-groep"]').append('<option value="' + item.id + '">' + item.naam + '</option>');
});
}
});
But in my console i get this error:
"NetworkError: 404 Not Found - https://m4th.nl/rapportage/https//m4th.nl/rapportage/get/groups/"
Very strange because input of the url is ok but the code duplicate the url.
Does somebody know what i did wrong?
Thanks!
change this line
var base_url = 'https//m4th.nl/';
to
var base_url = 'https://m4th.nl/';
you are missing the colon after https making the browser to think of the base url as extension -url

Client Side Ajax with jQuery reading a JSON

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.

why would .load not work in IE8

I have this code,
$(".delete").live("click", function () {
alert("!");
var self = $(this);
var loadUrl = $(this).attr('href');
var interestParents = self.parents('div:eq(4)').attr("id");
$.ajax({
type: "POST",
url: loadUrl,
data: "isAjax=1"
}).done(function (msg) {
self.parent().parent().parent().parent().parent().fadeOut('fast', function () {
$(this).remove();
});
//console.log($("#"+interestParents).load(site_url+"my_profile/interests " + "#" + interestParents).fadeIn('fast'));
//$("#UL_" + msg + "items").load(site_url + "my_profile/interests " + "#UL_" + msg + "items").fadeIn('fast');
$("#large_buttons").load(site_url + "my_profile #large_buttons > *").show();
});
return false;
});
and I cannot for life of me work out why the .load does not load the data into the large_buttons div, it definatly exists on the page, and it works in every other browser but IE8.
Check to make sure that the page you are "load"ing (my_profile) is valid HTML (no misplaced end tags, unclosed tags, etc). I had an issue like this with IE8 because the markup I was trying to load was invalid. Most browsers managed to interpret the bad markup, but IE8 failed.
An HTML validator may help you.
have you tried this way:
$("#large_buttons").show().load(site_url + "my_profile #large_buttons > *");
although i am unable to see where is the site_url variable, if this is a type then you should use this
$("#large_buttons").show().load(loadUrl + "my_profile #large_buttons > *");

Categories