I want to taking data out of the Ajax Jsonp.
Why doesn't work this app?
Please Help.
var res;
$.ajax({
url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35416355&dimensions=ga:pagePath&metrics=ga:users&filters=ga:pagePath==/p/etkinlikler.html&start-date=2015-10-25&oauth_token=AQAAAAAVs-uLAASpEAf-MmJK_kHgpU9Fwv8WArM',
dataType: 'jsonp',
async: false,
success: function(result) {
res = result.totalsForAllResults["ga:users"];
}
});
$("div").html(res);
https://jsfiddle.net/q6vfgemp/
The data is retrieved correctly but since the request is async you cannot set the html outside of the success callback, put it inside the success callback and it will work.
Also it's a good practice to console.log the data when you're not sure where the problem is to make sure it is retrieved successfully.
Edit: Here is why the async: false option is not working, check the accepted answer for the details.
In JSONP you should add a callback parameter to the request.
The response would be a script calling your callback with the requested data.
So, you should call a URL like this:
http://domain.ext/?callback=xxx
And you should have a function with name "xxx":
function xxx(data) {
// Here you can manage the received data
}
Also, the requested resource should support JSONP, if it doesn't you will not receive anything in your callback.
Since the request is asynchronous, your code sets the "div" before the result is actually retrieved. In order to make sure you retrieve the result, and then set the div, do this:
$.ajax({
url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35416355&dimensions=ga:pagePath&metrics=ga:users&filters=ga:pagePath==/p/etkinlikler.html&start-date=2015-10-25&oauth_token=AQAAAAAVs-uLAASpEAf-MmJK_kHgpU9Fwv8WArM',
dataType: 'jsonp',
async: false,
success: function(result) {
res = result.totalsForAllResults["ga:users"];
$("div").html(res);
}
});
Related
I am calling the twitch TV API to get users info from one endpoint and I want also to call another endpoint in the same API to check if those users are streaming live or not, but only if the first ajax call is successful. Can anyone give me a hint on how to do it?? My first call below:
var getUserInfo = $.ajax({
type: "GET",
url: "https://api.twitch.tv/helix/users/?login=ESL_SC2&login=freecodecamp&login=noobs2ninjas",
// contentType: ('application/x-www-form-urlencoded; charset=UTF-8'),
crossDomain: true,
headers: {
"Client-ID": "5k4g3q59o69v6p9tudn39v50ro1mux",
},
dataType: "json",
success: function (json) {
console.log(JSON.stringify(json, null, 2));
},
error: function () {
console.log("OOPS!!!");
},
})
The jQuery ajax function is built using the callback design to deal with its asynchronicity. You have two callbacks, success and error, one of which will fire when you receive a response from the Twitch API. If you want to make another ajax request depending on if your previous request was successful then you can simply write a very similar ajax request inside your success callback function pointing to the new location you are trying to acccess. I would recommend splitting that off into a separate function to maintain the readability of your code however.
The success function only runs if the call was successful.
Trigger the code for the second request from the success function.
I have a very simple $.ajax call that is suppose to get the json data from a given url. Currently the url does get called and the data does get returned, however the localHsonpCallback function doesn't seem to get fired.
Here is my code.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
}
function localJsonpCallback(json) {
console.log("Fired");
if (!json.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
So as mentioned above for some reason the localJsonpCallback doesn't seem to get fired at all.
Also I should mention that in my Chrome Dev tools the request link ends up looking like this for reason
http://localhost/api/users?callback=localJsonpCallback&_=1429708885454
Any help in this question would be greatly appreciated.
Thank you.
Try the callback method as an anonymous function directly inside the parameter list.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: function(data){
console.log("Fired");
if (!data.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
});
}
If youre not appending the callback onto the url you can set the jsonp oprion to false and then, as you are doing, set the callback in the options.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonp: false,
jsonpCallback: "localJsonpCallback"
});
}
Since javascript is sequential its also a good idea to define your functions before theyre called. ie - define your callback function before your ajax call.
http://api.jquery.com/jQuery.ajax/
jsonp
Type:
String Override the callback function name in a JSONP request.
This value will be used instead of 'callback' in the 'callback=?' part
of the query string in the url. So {jsonp:'onJSONPLoad'} would result
in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the
jsonp option to false prevents jQuery from adding the "?callback"
string to the URL or attempting to use "=?" for transformation. In
this case, you should also explicitly set the jsonpCallback setting.
For example, { jsonp: false, jsonpCallback: "callbackName" }
Maybe this piece of code it will help solve your problem:
$.ajax({
type: 'GET',
url: 'http://localhost/api/users',
data:{todo:"jsonp"},
dataType: "jsonp",
crossDomain: true,
cache:false,
success: success,
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
//your code here
};
This either a server side problem that the callback parameter is not used properly or the parameter name callback does not exist for the server side they are looking for something different.
You said the result is returning, what is the format? JSONP must return a script block not pure data so be sure the result is in below format.
{callbackFunctionName}({hugeDataFromServer});
Basically it is script that calls your function.
if it is not the server side that means it is more likely they are using a different name for callback parameter e.g. cb , _callback etc
I have a URL https://aua.maharashtra.gov.in/aua/rest/checkauastatus
When I visit the URL in a browser, I get an XML response. I want to collect that response in a String using Javascript or jQuery. I tried many things but nothing worked.
Please help me to get that response in a String.
Try this:
$.ajax({
type:'POST',
url:'https://aua.maharashtra.gov.in/aua/rest/checkauastatus',
success: function(response)
{
alert(response);
}
Just see if your expected reponse is coming or not.
Hope this helps.
If you are trying to make a request to other domains, use the below code for reference.
$.ajax({
url: 'https://aua.maharashtra.gov.in/aua/rest/checkauastatus',
dataType: 'jsonp',
jsonpCallback: 'dataResult',
jsonp: 'callback',
});
function dataResult(data) {
//Access your data here.
};
If you are calling ajax with different domain , then ajax will not work, You have to call your server and collect data. For e.g using curl, then return as response. You can also use jsonp if it supports.
I have the following javascript:
jQuery(document).ready( function($) {
var id = "123";
var api = "example.com:8999/".concat(id)
$.ajax({
url : api,
type: 'GET',
dataType: 'jsonp',
// jsonpCallback: "localcallback",
success: function (data) { alert('success'); }
})
});
I can see the response in chrome dev tools, but the alert isn't getting called. Ultimately I need to work with this response to set the value of a div.
Image of chrome tools:
Thanks
EDIT: Put 'POST', was using 'GET', still not working. Also, I think I'd prefer "mom and pop" json, but due to CORS and the fact I'm not good with the web and am just trying to hack this together.
Your server is not returning JSONP. It's returning plain JSON. If you specify JSONP, then the server must explicitly create a JSONP formatted response or the ajax response will not be received and processed properly.
FYI, a JSONP request is sent via a script tag (that's how it gets around the same-origin limitation for cross domain requests) and the response has to be formatted as a script that calls a function and passed the requested data to that function. You can read about how JSONP works here.
Just make your ajax call without specifying the 'dataType' attribute, then control should come back to your success callback if your ajax call completes successfully.
FYI: jQuery will try to find the response data type based on the MIME type of that response.
Example:
$( function() {
$.ajax({
url :"http://example.com:8999/123",
type: 'GET',
success: function (data) {
console.log(data); // Prints the response on console
alert('success');
}
})
});
If you want to make this call only with JSONP then it would be better to share the reason with us, so that we can suggest a better solution if possible.
Hi all;
var v_name = null;
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
$.data(document.body, 'v_name', mydata);
}
});
v_name = $.data(document.body, 'OutputGrid');
alert(v_name);
first alert undefined before alert work why ?
In addition to the other answers, also keep in mind that by default .ajax GET requests are cached, so depending on your browser, it may look like all of your requests are returning the same response. Workarounds include (but are not limited to): using POST instead of GET, adding a random querystring to your url for each request, or adding 'cache: false' to either your ajax call or to the global ajaxSetup.
To make it work, you have to place the alert() in the success function:
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});
AJAX calls are asynchronous, and therefore JavaScript would evaluate alert(v_name); before the server responds to the AJAX call, and therefore before the success function is called.
Your AJAX applications must be designed in such a way to be driven by the AJAX response. Therefore anything you plan to do with mydata should be invoked from the success function. As a rule of the thumb, imagine that the server will take very long (such as 1 minute) to respond to the AJAX request. Your program logic should work around this concept of asynchrony.
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});