cross domain jsonp request.. what am i doing wrong? - javascript

I am really lost here, and I have no idea what I am doing wrong.
I have exposed an api which gives a json output, and I want to fetch this data from another domain. Since jsonp is way to go, I am trying the code below.. Inspection on firebug shows that the response to the request is proper JSON, but the callback functions never seem to execute. Any help?
$(function(){
console.log('aa');
$.ajax({
url: 'http://domain/api.php',
data: {f:'get_total_playtime',userid:'1',starttime:'2011-01-01',endtime:'2011-12-12'},
dataType: 'jsonp',
success: function(data){
console.log('suceess');
alert(data.time);
},
failure: function(data){
console.log('failure');
}
});
});
If this is not the right way to go about it, can anyone explain the right way?

Inspection on firebug shows that the response to the request is proper JSON
Then that is the problem. You have to return JSONP, not JSON.

Related

How to Get Response From rest URL using jquery

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.

Ajax response with JSONP, can see result cannot use it

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.

jQuery AJAX request getting response but no callbacks are fired

I have code as such:
$.ajax({
method: "GET",
url: page,
dataType: 'html',
data:data,
success: function(data){
console.log(data);
},
error: function(){
console.log('error');
}
});
Using either Chrome or Firefox's debugger I can see that the request is successful with a response of 200 OK and the response contains the expected data.
My problem is, however, that no callbacks fire whatsoever. "Success" does not fire nor does "Error". Furthermore, no deferred methods fire either, such as "done", "then", or "always".
I've been trying to trouble shoot this for the past few hours to no avail. I'm at a total loss. I've also tried using methods such as "$.get" with the same result.
In short, I'm getting the response, but the code in jQuery is not firing any callbacks and all without any visible errors in the console.
One thing I see wrong in your code is that:
method: "GET",
should be:
type: "GET",
I don't see any documented property for method in the jQuery doc. The type property is supposed to default to "GET" so this may not be the only thing wrong here.
In addition, there are cases where the error callback will not be called even if the ajax call fails (in cross-domain requests). From the jQuery doc for the error callback:
This handler is not called for cross-domain script and cross-domain JSONP requests.
This is because jQuery is expecting the server to send back a particular form of javascript and if the server doesn't do what is expected, then jQuery never knows when the request comes back and can't process it.
In these cases, you often have to figure out what might be going wrong from looking at the network trace in the debugger.
Other things to check to make sure you aren't accidentally cross domain:
Make sure the domain/subdomain are exactly the same between ajax call and the page. For example, one common mistake is for one to have www. on it and the other not.
Make both page and ajax URL are both same http or https.
If using a non-standard port number, make sure both page and ajax URL are using the same port.
The following code works. Also note that AJAX will not work with cross site scripting.
If you want to get the error you can print the "errorThrown"
<script>
$(document).ready(function () {
$('#getLink').on("click", function () {
var url = $("#myUrl");
alert(url.val());
$.ajax({
type: "GET",
url: url.val(),
dataType: 'html',
success: function (data, textStatus, xhr) {
$("#data").text(textStatus);
},
error: function (data,textStatus, errorThrown){
$("#data").text(errorThrown);
}
});
});
});
</script>
<input id="myUrl" name="myURL" type="text" value="http://localhost:35460/Home/TestPage.cshtml" />
<input type="button" value="getLink" id="getLink">
<span id="data"></span>

Get a JSON file from URL, XMLHttpRequest cannot load error

I need to read a JSON file from URL and display.
I have read a lot of posts but still couldn't fix the problem.
url : http://webapp.armadealo.com/home.json
I face this error : XMLHttpRequest cannot load
The code is below
$.getJSON("http://webapp.armadealo.com/home.json", function(data){
alert(data);
});
I have tried adding to the url
&callback=?
and making it a jsonp, still no luck. I have also used
<meta http-equiv="Access-Control-Allow-Origin" content="*" />
still no luck.
Is there anything that we need to do at the server side?
People who have faced such an error and have found a solution, Help me out please!
Thanks a lot!
You cannot make cross-domain AJAX requests like that due to security reasons. So if you want to load content from another domain, you will have to use a workaround: JSONP (more info, example)
Use the following code for the AJAX request:
$.ajax({
url: 'http://webapp.armadealo.com/home.json',
type: 'GET',
jsonpCallback: 'myCallback',
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});
In order for this to work, you will have to wrap the JSON data in parentheses and add the callback name at the beginning:
myCallback({ ... JSON ... })
EDIT: Just noticed you already tried to use JSONP... Well, at least the above code works for me, perhaps you want to give it a try. ;)

Calling a webservice using JQuery

I am using this code from http://www.joe-stevens.com/2010/01/04/using-jquery-to-make-ajax-calls-to-an-asmx-web-service-using-asp-net/
function callWebService(address) {
var result;
$("#result").addClass("loading");
$.ajax({
type: "POST",
url: address,
data: "{}",contentType: "application/json; charset=utf-8",
dataType: "json",
success: Success,
error: Error
});
}
function Success(data, status) {
$("#result").removeClass("loading");
$("#result").html(data.d);
alert("Success");
}
function Error(request, status, error) {
$("#result").removeClass("loading");
$("#result").html(request.statusText);
alert("Error");
}
I don't understand what is wrong with this code. It keeps returning "Error"
Also make sure that the service URL that you're trying to access is in the same domain as your site. AJAX calls won't succeed if you cross domains, since browsers subject AJAX calls to the same domain policy. Can you also include the URL you're trying to access?
If you're trying to access a resource at a different domain, you may want to consider a JSONP request instead. See the jQuery AJAX documentation for a discussion of how to use JSONP.
I think if you combine knowing the URL you're trying to access along with Justin and mohlsen's suggestions, I think we can help.
Your code looks fine at first glance.
I recommend you use FireBug to attempt to isolate the problem further, as it will allow you to see the actual HTTP requests, POSTed data, etc...
A few suggestions based on some code I have doing this. But as others have said, make sure to manually look at the data going out and coming back. Your link references asp.net webservice, is that what you are calling since you didn't mention it.
Make sure the "address" url is of the form /location/page.asmx/methodname
You might need to pass the data to the success method in the call
success: function(msg) {
//msg is a json object, .d is the data field returned by asp.net
if (msg.d.length > 0)
ProcessData(msg.d);
else
HandleError('No data was returned.');
},
error: function() {
HandleError('There was a problem calling the webservice.');
}

Categories

Resources