JavaScript - Results Displaying in IE but not Chrome or FF - javascript

So, i'm new to Javascript, let's get that out of the way.
Anyway, I have the following code that works in IE, but not in Chrome or FF. It's supposed to grab the data from the Reddit RSS, then just output it, that's it. It only is working in IE. Can anyone explain what I'm doing wrong here?
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var result = null;
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
document.write(result);
</script>
</head>
</body>
</html>

yes, this code doesn't look right. it's a race condition. document.write executes immediately. the ajax may or may not have set the result in time. you need to add the result to the page in the success event...something like:
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get', dataType: 'html',
async: false,
success: function(data) {
$("#some-div").html(data);
} });

You have race condition due to $.ajax being asynchronous. Display the result in the success handler instead, so that the request is guaranteed to have finished.
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
document.write(data);
}
});
Update
Since you set async to false, the above statement isn't applicable. However, I haven't ever found a good reason to use document.write(), which might be part of your issue. Try using another method to inject the data into your page such as .html(), .append(), alert(), etc. And it wouldn't hurt to do this inside document.ready either.
$(document).ready(function() {
var result = null;
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
alert(result);
$("body").append(result);
});

What about processing in this manner:
(function(url, callback) {
jQuery.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
})('http://www.reddit.com/.rss', function(feed) {
var entries = feed.entries,
feedList = '';
for (var i = 0; i < entries.length; i++) {
feedList += '<li>' + entries[i].title + '</li>';
}
jQuery('.rssfeed > ul').append(feedList);
});
HTML:
<div class="rssfeed">
<h4>RSS News</h4>
<ul></ul>
</div>
sample: http://jsfiddle.net/QusQC/

Related

How can I do a conditional statement so ajax fetchs the correct xml document

I have a simple code to fetch a xml file and display it as a drop down list. However, I would like to fetch the xml file according to a condition. If it equals to study1 then .ajax selects ctc3.xml, else it selects ctc5.xml.
My code was working fine if I was fetching a specific xml file, but the conditional does not work.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script lang="Javascript"> $.noConflict();
jQuery(document).ready(function($) {
var myField = $("#myList") var myOutputField = $("#myOutput").parent().parent().find("input");
myOutputField.attr("readonly",true);
var studyID="${studyName}";
if (studyID!="Test"){
$.ajax({
type: "GET",
url: "includes/ctcae3.xml",
dataType: "xml",
success: parseXML
});
}
else {
$.ajax({
type: "GET",
url: "includes/ctcae5.xml",
dataType: "xml",
success: parseXML
});
}
function parseXML(xml){
$(xml).find("atccode").each(function(){
myField.append($("<option />").val($(this).attr("code")).text($(this).find("description").text()));
});
myField.val(myOutputField.val());
}
myField.change(function(){
myOutputField.val(myField.val());
myOutputField.change();
});
});
</script><select id="myList"> <option val="None"/>None </select> `
problem resolved. Clearly my brain was already fried. It was just a matter of adding the ';' to var myField = $("#myList");

How to get title using ajax?

I'm using ajax functionality and trying to get title using ajax but not working. Here is a example
$('#ajaxlink').click(function(e) {
var $this = this.href;
$.ajax({
url: $this,
dataType: 'html',
success: function(html) {
var div = $('title', $(html));
$('#gettitle').text($title);
console.log(html);
}
});
e.preventDefault();
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="ajaxlink" href="https://jsfiddle.net/">Click</a>
<div id="gettitle">
</div>
Your request is failing because of CORS protection. You can't easily request html from other domains and parse the results, unless they have enabled CORS explicitly.
To make it work for same domain, try this
$('#gettitle').text($(html).filter('title').text());
I saw some problems in your code,
Please try this version of your code
$('#ajaxlink').click(function(e) {
var urlPath = $(e.currentTarget).prop('href'); // must be a valid url
$.ajax({
url: urlPath,
dataType: 'html',
success: function(html) {
$('#gettitle').text(html);
console.log(html);
}
});
e.preventDefault();
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="ajaxlink" href="https://jsfiddle.net/">Click</a>
<div id="gettitle">
</div>
You can use JSONP:
function logResults(json){
console.log(json);
}
$(document).ready(function(){
$.ajax({
url: "https://api.github.com/users/jeresig",
dataType: "jsonp",
jsonpCallback: "logResults"
});
});
or
function jsonCallback(json){
console.log(json);
}
$(document).ready(function(){
$.ajax({
url: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json",
dataType: "jsonp"
});
});

Displaying XML information in HTML from a Public XML source

I'm looking for a very basic way to display one piece of XML data from this public source in html: http://avwx.rest/api/metar.php?station=KTPF
Here is what I have so far, with no luck:
<script type="javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
dataType: "xml",
url: "http://avwx.rest/api/metar.php?station=KTPF",
success: xmlParser
});
});
function xmlParser(xml)
{
$(xml).find("Raw-Report")
{
$("#metar-text").append('<marquee class="metar-marquee">' + $(this).find("Raw-Report").text() + '</marquee>');
};
};
</script>
I have a div in the HTML with the id #metar-text that I would like scrolling (hence the conc. marquee tags) I only need to display the Raw-Report text.
Your code require some corrections to work.
<script type="javascript">
$(document).ready(function(){
$.ajax({//this part is OK
type: "GET",
dataType: "xml",
url: "http://avwx.rest/api/metar.php?station=KTPF",
success: xmlParser //note that success receives 3 arguments
});
});
function xmlParser(data, state, xhr)
{
var xml = xhr.responseXML; //xml document is here
if($(xml).find("Raw-Report").text()) //that is exists and not empty
{
$("#metar-text").append('<marquee class="metar-marquee">'
+ $(xml).find("Raw-Report").text()
+ '</marquee>'); //**this** is $.ajax in this context
};
};
</script>

JQuery text change in h3 tag

I am using ajax to call a page which looks like:
<div class="ui-block-a">
<div class="jqm-block-content invoicehomepage">
<h3>Invoices</h3>
<p>Pages</p>
<p>Navigation</p>
<p>Loader</p>
<p>Transitions</p>
</div>
</div>
and my ajax call is:
var pageContent = '';
$.ajax({
url: 'jsp/home/home.jsp',
type: 'POST',
dataType:'json',
success:function(data) {
$.each(data, function(i, v) {
$.ajax({
url: 'tmpl/homePortlet/'+v.link+'.html',
dataType : "html",
success: function(html_data) {
//var result = $('</div>').append(html_data).find('h3').html();
//$('h3').html(v.portletName);
pageContent += html_data;
//console.log(pageContent);
}
});
console.log(pageContent+'sssss');
});
}
});
I want to change text within h3 tag with the value i got from my second ajax call.
Thanks for help.
You need to change the HTML element h3 by finding it in the content that you have got in your Ajax Call something like this:
pageContent = $(html_data).find("h3:first").html(" YOUR-TEXT-YOU-WANNA-PUT ").parent();
Update:
I think you should use async: false in your second ajax call. And secondly, I don't think so that you needs to store/update html into some Variable as you have used pageContent. You should use JQuery .append() method:
$.ajax({
url: 'jsp/home/home.jsp',
type: 'POST',
dataType:'json',
success:function(data) {
$.each(data, function(i, v) {
$.ajax({
url: 'tmpl/homePortlet/'+v.link+'.html',
dataType : "html",
async: false,
success: function(html_data) {
var new_html_data = $(html_data).find("h3:first").html(v.portletName).parent();
$('.ui-grid-a').append(pageContent);
}
});
});
}
});
use: $('h3').text(v.portletName);
It seems your AJAX request is asynchronous..
You can add async : false, option in ajax request, so when the request end, second request begin and at success of second ajax request you can change text of H3 tag.
var pageContent = '';
$.ajax({
url: 'jsp/home/home.jsp',
type: 'POST',
dataType:'json',
async:false,// add this line so the success callback execute after response receive.
success:function(data) {
$.each(data, function(i, v) {
$.ajax({
url: 'tmpl/homePortlet/'+v.link+'.html',
dataType : "html",
async:false,// add this line so the success callback execute after response receive.
success: function(html_data) {
$('h3').html(v.portletName);
pageContent += html_data;
}
});
console.log(pageContent+'sssss');
});
}
);

Javascript image timout

Good day, i'm having a problem with my code, can't get to show the loading image for few seconds, while POST code is getting in database and gives backinformation to show.
$("#poll_vote").click(function(){
var answer = $("input.panswer:checked").val();
var p_id = $("#p_id").val();
$("#poll_load").html("<tr><td align='center'><img src='/images/ajax/ajax4.gif'/></td></tr>");
$.ajax({
type: "POST",
data: "action=poll_vote&p_id="+p_id+"&answer="+answer+"&module="+module+"",
dataType: 'html',
url: "/ajax.php",
success: function(data)
{
$("#poll_content").html(data);
}
});
});
I would hope on your fast help, i'm begginer in java, so can't dicide it myself.
If what you want is to create a delay so the loading animation shows (I believe that is... mmm different, I'm going with that...)
what you need is to set a timeout like so:
setTimeout(function(){ alert("Hello"); }, 3000);
now in your code the function could contain the ajax call:
$("#poll_vote").click(function(){
var answer = $("input.panswer:checked").val();
var p_id = $("#p_id").val();
$("#poll_load").html("<tr><td align='center'><img src='/images/ajax/ajax4.gif'/></td></tr>");
setTimeout(function(){
$.ajax({
type: "POST",
data: "action=poll_vote&p_id="+p_id+"&answer="+answer+"&module="+module+"",
dataType: 'html',
url: "/ajax.php",
success: function(data)
{
$("#poll_content").html(data);
}
});
}, 3000);
});
or be inside the success function, which I believe is better:
$("#poll_vote").click(function(){
var answer = $("input.panswer:checked").val();
var p_id = $("#p_id").val();
$("#poll_load").html("<tr><td align='center'><img src='/images/ajax/ajax4.gif'/></td></tr>");
$.ajax({
type: "POST",
data: "action=poll_vote&p_id="+p_id+"&answer="+answer+"&module="+module+"",
dataType: 'html',
url: "/ajax.php",
success: function(data)
{
setTimeout(function(){$("#poll_content").html(data);}, 3000, data);
}
});
});
I didn't test it, so check if in the second case data can be seen inside the callback function (it should I think...)
Hope it helps.

Categories

Resources