Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: url is not defined

I keep getting this error at referring to 'url' in this block of code.

Uncaught ReferenceError: url is not defined.

Although the URL is defined clearly in a variable above the ajax. What am I doing wrong?

$.ajax({
url: url,
dataType: 'jsonp',
cache: true,
jsonpCallback: 'wCallback_1'
});

Here is the full code

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>


<script type="text/javascript" language="javascript">

$(function () {
// Specify the location code and units (f or c)
var location = 'SPXX0550';
var u = 'c';


// Run the query (pull data from rss feed)
var query = 'SELECT * FROM rss WHERE url="http://xml.weather.yahoo.com/forecastrss/' + location + '_' + u + '.xml"';
var cacheBuster = Math.floor((new Date().getTime()) / 1200 / 1000);
var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&_nocache=' + cacheBuster;
});

window['wCallback_1'] = function(data) {
    var info = data.query.results.item.forecast[0];
    $('#wIcon').append('<img src="http://l.yimg.com/a/i/us/we/52/' + info.code + '.gif" width="34" height="34" title="' + info.text + '" />');
    $('#wTemp').html(info.temp + '&deg;' + (u.toUpperCase()));
    $('#wText').html(info.text);
};

$.ajax({
    url: url,
    dataType: 'jsonp',
    cache: true,
    jsonpCallback: 'wCallback_1'
});

like image 969
ServerSideSkittles Avatar asked Jan 14 '23 03:01

ServerSideSkittles


1 Answers

Because you define and populate url in the block of code surrounded by $(function() { }), that runs when the document is loaded.

However, the code following it (where you try to use url) is run immediately (before the document has loaded).

Just put all the code inside the $(function() { }) block and it will work fine...

$(function () {
    // Specify the location code and units (f or c)
    var location = 'SPXX0550';
    var u = 'c';


    // Run the query (pull data from rss feed)
    var query = 'SELECT * FROM rss WHERE url="http://xml.weather.yahoo.com/forecastrss/' + location + '_' + u + '.xml"';
    var cacheBuster = Math.floor((new Date().getTime()) / 1200 / 1000);
    var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&_nocache=' + cacheBuster;

    window['wCallback_1'] = function(data) {
        var info = data.query.results.item.forecast[0];
        $('#wIcon').append('<img src="http://l.yimg.com/a/i/us/we/52/' + info.code + '.gif" width="34" height="34" title="' + info.text + '" />');
        $('#wTemp').html(info.temp + '&deg;' + (u.toUpperCase()));
        $('#wText').html(info.text);
    };

    $.ajax({
        url: url,
        dataType: 'jsonp',
        cache: true,
        jsonpCallback: 'wCallback_1'
    });
});
like image 185
Reinstate Monica Cellio Avatar answered Jan 16 '23 20:01

Reinstate Monica Cellio