Question

Im trying to get the callback from this:

$.getScript( 'http://gdata.youtube.com/feeds/api/videos/<?php echo $m; ?>?v=2&alt=json-in-script', function(data)
{
  alert(data);
});

But the alert just returns alert with "undefined" ? And I also tried:

$.getScript( 'http://gdata.youtube.com/feeds/api/videos/<?php echo $m; ?>?v=2&alt=json-in-script&callback=?', function(data)
{
  alert(data);
});

Then it doesn't return any alert at all. (i believe the function doesnt run).

But....if i do:

$.getScript( 'http://gdata.youtube.com/feeds/api/videos/<?php echo $m; ?>?v=2&alt=json-in-script&callback=myfunction');

and then have:

function myfunction ( data ) { alert(data); }

Then it do work and returns the data how I wanted. But I do not wish to do this.

How can this be solved?

tried this too:

        var URL = 'http://gdata.youtube.com/feeds/api/videos/<?php echo $m; ?>?v=2&alt=json-in-script';
        $.ajax({
        url: URL,
        dataType: 'jsonp',
        jsonpCallback: 'youtubeFetchDataCallback'
        });

but where in this should i have a function and alert the data from the callback?

Was it helpful?

Solution

The getScript method is used to execute the returned script. By the time it makes it to your callback, the script will have already been run. If you are actually returning data, say JSON, you should be using getJSON to make your cross-domain request, with a datatype of jsonp. If you really are getting a script that runs on your page, you shouldn't actually need the callback function.

Quoting from the docs:

The callback is passed the returned JavaScript file. This is generally not useful as the script will already have run at this point.

Using getJSON it might look like (note I split the string to make it more readable)

var url = 'http://gdata.youtube.com/feeds/api/videos/<?php echo $m; ?>';
$.getJSON( url + '?v=2&alt=json-in-script&callback=?', 
    function(data) {
        alert(data);
});

OTHER TIPS

To do a JSONP request in jQuery, which is, I think, what you are trying to do, do the following:

$.ajax({
    url: 'http://gdata.youtube.com/feeds/api/videos/<?php echo $m; ?>?v=2&alt=json-in-script',
    type: 'GET',
    dataType: 'jsonp',
    success: function(data) {
        alert(data);
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top