jQuery JSONP callback function not found - javascript

I'm trying to get data from external server using JSONP, but I've stuck on the callback function.
function processLinks(data) {
alert('IT WORKS!');
};
function getLinks() {
$.ajax({
type: 'GET',
url: 'https://external-site.com/test.cgi',
dataType: 'jsonp',
success: function (data) {
console.log(data)
}
});
};
When I call getLinks(), I get ReferenceError: processLinks is not defined.
External site returns processLinks({"mark": "dog", "number":"33"});.
Thank you for any help

Related

Promise and callback function in ajax, when does success take place ?

Right now I have a code like this:
$.ajax({
url: apiUrl + valueToCheck,
data: {
format: 'json'
},
error: function () {
},
dataType: 'json',
success: function (data) {
checkAgainstDBHelperWH(data, valueToCheck);
},
type: 'GET'
});
If I am not mistaken, checkAgainstDBHelperWH is known as a callback function. The function executes once the servers sends back response for this particular HTTP /ajax request.
I want to try writing something like the one below, but I don't know what are the effects or is it even logical:
var request = $.ajax({
url: apiUrl + valueToCheck,
data: {
format: 'json'
},
error: function () {
},
dataType: 'json',
success: function (data) {
checkAgainstDBHelperWH(data, valueToCheck);
},
type: 'GET'
})
arrayOfPromises.push(request);
$.when.apply(null, arrayOfPromises).done(function () {
//...some javascript here
});
I want to understand if the .done(function () is fired after the callback function checkAgainstDBHelperWH is completed? Or whatever I am trying to write above does not flow consistently with how ajax works?
Thanks!
I tested it, your code only work if the function(in this case, 'checkAgainstDBHelperWH') doesn't call ajax.
If you want to wait finishing the inner ajax process, use then() and return inner ajax.
var ajaxs =
$.get("xxx").then(function() {
return $.get("yyy").done(function() {
});
});
Here is the jsfiddle.
I'm not sure whether this way is general or not.

Getting Data from Ajax request displayed

I've already read this article How do I return the response from an asynchronous call? However I couldn't come up with a solution.
I'm doing an ajax request
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
And Console displays everything fine but when I say
var chinese = getdata();
to get the data. I keep getting:
Uncaught TypeError: Cannot read property 'length' of undefined error for this line
var text = chinese[Math.floor(Math.random()*chinese.length)];
Can anybody help me here?
The problem is that you are using an asynchronous method expecting a synchronous result.
Therefore you should use the code in the result of the asynchronous call like the following:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
error: function(xhr) {
console.log('Error', xhr.status);
},
success: function(chinese) {
var text = chinese[Math.floor(Math.random()*chinese.length)];
// Do something else with text
}
});
}
getData('http://myserver.com/myscript.php');
I hope it helps :)
The error you get is because of the asynchronous nature of the call. I suggest you to assign the value after you get the success response from the API like below.
var chinese = getdata();
Then the function getdata() will be like
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
initChinese(response.data);
}
});
}
And create a function initChinese() like
var text;
function initChinese(chinese){
text = chinese[Math.floor(Math.random()*chinese.length)];
}
You can also declare the text variable in global scope and then assign the value to text variable inside the success function without having to create a new function initChinese.
The problem is your getdata function does not return anything. In your getdata function you're doing a ajax request, which is an asynchronous request. So the data you're requesting won't, and can't be returned with your getdata function.
But you will have the requested data in your success function:
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
var text = response[Math.floor(Math.random()*response.length)];
}
});
}
As I'm not able to test your code, you've to debug the rest on your own. But the response variable will be most likely your "chinese" variable.
You could try using callbacks or you could look at Promises.
The idea with callbacks is that you pass a function that is run after the ajax request is finished. That callback can accept a parameter, in this case the response.
Using callbacks:
function getData(url, successCallback, errorCallback) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
errorCallback(xhr.status);
},
success: function(response) {
successCallback(response);
}
});
}
var chinese;
getData("http://myserver.com/myscript.php", function(response) {
chinese = response; // you can assign the response to the variable here.
}, function(statusCode) {
console.error(statusCode);
});
Using Promises (< IE11 doesn't support this):
function getData(url) {
return new Promise(function(resolve, reject) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
reject(xhr.status);
},
success: function(response) {
resolve(response);
}
});
});
}
var chinese;
getData("http://myserver.com/myscript.php").then(function(response) {
chinese = response;
console.log(chinese);
}, function(statusCode) {
console.error(statusCode);
});

Google API url use by javaScript

I have this url as json object which is provided by google API.
https://www.googleapis.com/customsearch/v1?key=AIzaSyAo6DqmlMti9ID7lL532A7-6Miu1QHcMqI&cx=013881670411723352605:b1y6-jfsiki&q=web%20developer?alt=json-in-script&callback=listEvents
I want to use javaScript and want to see complete json object.This is my script code , but it doesn't work. please help me , i am struggling from 3 days.
function listEvents(root){
$.getJSON('https://www.googleapis.com/customsearch/v1?key=AIzaSyAo6DqmlMti9ID7lL532A7-6Miu1QHcMqI&cx=013881670411723352605:b1y6-jfsiki&q=web%20developer?alt=json-in-script&callback=listEvents', function(data) {*/
alert(root)
});
}
function init() {
listEvents();
}
window.onload = init;
Thanks in advance
You are giving a callback option in url that is again a call to listEvents(). That is not correct. Use your own success callback. this will work:
function listEvents() {
$.getJSON('https://www.googleapis.com/customsearch/v1?key=AIzaSyAo6DqmlMti9ID7lL532A7-6Miu1QHcMqI&cx=013881670411723352605:b1y6-jfsiki&q=web%20developer?alt=json-in-script', function (data) {
console.log(data)
});
}
Demo example
The output is in JSONP format and not JSON
JSONP({JSON})
Jquery JSONP: http://learn.jquery.com/ajax/working-with-jsonp/
(function($) {
var url = 'https://www.googleapis.com/customsearch/v1?key=AIzaSyAo6DqmlMti9ID7lL532A7-6Miu1QHcMqI&cx=013881670411723352605:b1y6-jfsiki&q=web%20developer?alt=json-in-script&callback=listEvents';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'listEvents',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
BTW your Google Daily Limit Exceeded

Can this JavaScript Defer code be simplified?

I have a JavaScript bootstrapper module that I'm trying to keep very clean and simnple: Currently I have code like:
function bootStrapper() {
xmlRepository.getAll().done(function (result) {
autoPolicyForm.show();
});
}
In xmlRepository I am using a deferred object within getAll();
function getAll () {
var d = $.Deferred();
$.ajax({
type: "GET",
url: "http://localhost/Autopolicy/dataSource.xml",
dataType: "xml",
success: function (xml) {
d.resolve(xml);
}
});
return d.promise();
}
This code is working well but I would really like to simplify the bootstrapper code further to something like:
function bootStrapper() {
var result = xmlRepository.getAll();
autoPolicyForm.show();
});
}
Everything I try results in 'result' being undefined due to the async nature of call.
Does anyone know how to modify the code to move the complexity to the xmlRepository so that the above can be achieved?
Thanks
In modern jQuery the ajax function returns a promise so you can simplify getAll to :
function getAll () {
return $.ajax({
type: "GET",
url: "http://localhost/Autopolicy/dataSource.xml",
dataType: "xml"
});
}
In other words it is now possible to do
$.ajax(url).done(function(xml){...});
You could also change getAll to
function fetchAll (callback) {
$.ajax({
type: "GET",
url: "http://localhost/Autopolicy/dataSource.xml",
dataType: "xml"
}).done(callback);
}
So you'll do
xmlRepository.fetchAll(function (result) {
autoPolicyForm.show();
});
But apart setting async to false, you can't avoid passing a function as the execution is asynchronous. And you should consider that a javascript application is naturally event based so it's fine for the users of an API to use and pass anonymous functions (callbacks).

Return value from function with ajax call [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Synchronous calls with jquery
I am trying to return a value from a function that contains an ajax call (please see code below).
The returnValue variable is undefined at the alert and when it returns. Can anyone help please?
function getLightboxImages(){
var returnValue;
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
async: false,
dataType: "jsonp",
success: function (result) {
returnValue = result
}
});
alert(returnValue);
return returnValue;
}
The alert would have to be placed in the success function, as that is called when ajax returns. What you have above will send the request and then try to alert the returned value before the request is completed.
try this code, for JSONP you have to use callback function rather than success method.
$.ajax({
url: 'http://test.domain.com/WebService.svc/GetAllI',
type: 'GET',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpCallbackfunction",
error: function () {
alert("Error in Jsonp");
}
});
function jsonpCallbackfunction(responseData) {
alert(responseData);
}
http://cmsnsoftware.blogspot.com/2012/02/how-to-use-cross-domain-ajax-request.html#0
function getLightboxImages(){
var returnValue;
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
async: false,
dataType: "jsonp",
success: function (result) {
returnValue = result
}
});
alert(JSON.stringify(returnValue));
return returnValue;
}
Cross-domain requests can only be async, as cross-domain requests rely on a dynamic script tag, which can never be synchronous and must use datatype json and the GET method.
For same domain requests, try stringifying json objects before alerting, like above!
You can't make synchronous JSONP requests.
Use a callback instead of return:
function getLightboxImages(callback) {
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
dataType: "jsonp",
success: function (result) {
callback(result);
}
});
}
Usage:
getLightboxImages(function(result){
alert(result);
});

Categories

Resources