I have the following code below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$("#b1").click(function(event) {
var pm_url = 'http://www.flickr.com/services/rest/?method=flickr.test.echo&format=json&jsoncallback=wooYay&api_key=52c5c9441e7965eb55b7e54246bc6abf';
$.ajax({
url : pm_url,
dataType : 'jsonp',
jsonpCallback : 'wooYay',
jsonp : 'callback',
});
function wooYay(data) {
alert(data);
console.log('hi');
};
});
});
</script>
</head>
<body>
<div>
<button id="b1">
Click Me!
</button>
</div>
<div class="results"></div>
</body>
</html>
When I view this in Google Chrome dev tools, I clearly see a response like below:
wooYay({"method":{"_content":"flickr.test.echo"}, "format":{"_content":"json"}, "jsoncallback":{"_content":"wooYay"}, "api_key":{"_content":"52c5c9441e7965eb55b7e54246bc6abf"}, "callback":{"_content":"wooYay"}, "_":{"_content":"1357519661919"}, "stat":"ok"})
But somehow the function wooYay never executes. Also I want to keep the function wooYay in the code block. Could someone please tell me where the error is?
Thanks,
Jim
The biggest issue is you are confusing
jsonCallbackwith the AJAX success callback.The
wooYayin thejsonCallbackis to define the wrapper for the response which you see in response data you posted.jQuery also unwraps the data contained within this wrapper using the name provided or the one it creates if you don’t provide one
However this will not run the function you named
wooYay. This needs to be run in the success callback of $.ajax.Although it is unorthodox to define your function
wooYayinside the clcik handler it does work as follows:DEMO: http://jsfiddle.net/kT6dq/
Demo(refactored code) http://jsfiddle.net/kT6dq/1/