jQuery.ajax({
type: "GET",
url: 'http://example.com/restaurant/VeryLogin(username,password)',
dataType: "json",
success: function (data) {
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
it alerts success, but data was null. The url returns xml data, if we specify the dataType we can get the json data,but here it was not getting any data.
Any help appreciated.
Javascript is subject to the same domain policy. This means for security a JS Script in a client browser can only access the same domain as it came from.
JSONP is not subject to the same restrictions.
Check the jQuery docs on JSONP here:
http://api.jquery.com/jQuery.getJSON/
Here is a working example of using JSONP to access a cross-domain service via JQuery AJAX:
http://jsbin.com/idasay/4
And just in case JSBIN deletes this paste in the future:
jQuery.ajax({
type: "GET",
url: 'http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo',
dataType: "jsonp",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
alert(JSON.stringify(data));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
It's impossible to use Ajax to get cross-domain data directly without changing backend. It's called Same origin policy.
You can set the special header Access-Control-Allow-Origin in backend(how do to this). Or you can use JSONP.
Look for jsonp datatype.
jQuery.ajax({
type: "GET",
url: 'http://xxx.com/restaurant/VeryLogin(username,password)',
dataType: "jsonp",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
here is a fantastic article to make GET and POST cross-domain call :
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
It just helped me a lot....shoot comments for any query.
Related
i got a problem in meteor when i try to make a cross origin call.
when i make the call using Ajax.
$.ajax({
type: 'GET',
url: signoutUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (nullResponse) {
console.log('success');
},
error: function (e) {
console.log('error in HTTP :: >>>>' + JSON.stringify(e));
}
});
it works fine with no problem. but when i am using meteor's HTTP.call method for the same Http request it sent me the error.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
i set the parameters and header in meteor Http.call are
HTTP.call(method, URL,
{params: {
async: false,
contentType: "application/json",
dataType: 'jsonp'},
headers:{'Access-Control-Allow-Origin':'https://www.google.com/*'}
}, function (err, result) {}
but when i check the request. i found the header is like
access-control-request-headers:access-control-allow-origin
so, help me where i am wrong in this HTTP request and how to resolve it
I am using vb.net 2.0 and asp.net in my project.
I am sending ajax request from a page to get response.
$.ajax({
type: "POST",
url: "GetMyData.aspx?i=2",
data: '{ugData: \"10\"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
return false;
},
failure: function (response) {
alert("Failed");
}
});
In this code, after ajax request I can see that the variable "ugData" is in the Request Payload in Developers tool.
Can any one help me out How can i able to read this "ugData" variable value in my Page "GetMyData.aspx".
Thank You..
I am not able to get correct error code in the error handler of AJAX request. Everytime the error occurs, it returns me statusCode = 500. I tried to set it explicitly in my service as HttpContext.Current.Response.StatusCode = 403;, but still it gives me status = 500.
This is how my AJAX request looks like:
$.ajax({
type: "POST",
url: "Services/someSvc.asmx/SomeMethod",
cache: true,
contentType: "application/json; charset=utf-8",
data:"{}",
dataType: "json"
error: ajaxFailed
});
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' + //This is always 500.
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
What am i missing here?
Looks like you were almost there, here is an example [WebMethod] that would throw a StatusCode 403.
[WebMethod]
public static string HelloWorld(string name)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.StatusCode = 403;
return null;
}
Here is the calling jQuery Code.
$(document).ready(function ()
{
var jsonRequest = { name: "Zach Hunter" };
$.ajax({
type: 'POST',
url: 'Demo.aspx/HelloWorld',
data: JSON.stringify(jsonRequest),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data, text)
{
$('#results').html(data.d);
},
error: function (request, status, error)
{
$('#results').html('Status Code: ' + request.status);
}
});
});
If you don't return a value as specified in your method signature you'll get a status code 500 returned.
According to the documentation:
error(jqXHR, textStatus, errorThrown)
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn. Note: This handler
is not called for cross-domain script and JSONP requests. This is an
Ajax Event.
So change your code to something more like this:
$.ajax({
type: "POST",
url: "Services/someSvc.asmx/SomeMethod",
cache: true,
contentType: "application/json; charset=utf-8",
data:"{}",
dataType: "json",
error: ajaxFailed (jqXHR, textStatus, errorThrown)
});
function ajaxFailed(jqXHR, textStatus, errorThrown) {
alert(errorThrown + ' \n\r ' + textStatusText);
}
You might also find this answer provides some additional info.
I would like consume cross-domain web-service from client with jquery.here is my code
function getId() {
var testid = ($('#<%=PreviousTest.ClientID %> OPTION:selected').val());
jQuery.support.cors = true;
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
}
my webservice returns values in this format
{"Table":[{"minlatency":16.0,"Time":"/Date(1328248782660+0530)/"},{"minlatency":7.0,"Time":"/Date(1328248784677+0530)/"},{"minlatency":13.0,"Time":"/Date(1328248786690+0530)/"},{"minlatency":6.0,"Time":"/Date(1328248788690+0530)/"},{"minlatency":20.0,"Time":"/Date(1328248790707+0530)/"},{"minlatency":12.0,"Time":"/Date(1328248792723+0530)/"},{"minlatency":26.0,"Time":"/Date(1328248794723+0530)/"},{"minlatency":18.0,"Time":"/Date(1328248796723+0530)/"}]}
Calls in cross-domain work in a different way. They create dynamic javascripts that are inserted to the page using a callback function. This function is used to handle the response from the service. The Jquery calls add a "?callback=?" to the URL of the service, where "callback" is the name of the function that will be inserted.
To call cross-domain services with JQuery you have to do the following:
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //The data type that you must use is JSONP. Basically tells JQuery that the request is cross-domain
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
},
jsonpCallback: 'callback' //Dude to the fact that the JS is being generated dynamicaly, this tells JQuery to use the name "callback" for the function that will handle the result, as it adds "?callback=?" to the URL
});
You could also use "jsonp" instead of "jsonpCallback" if you want to "override the callback function name in a jsonp request" (from JQuery).
It worked for me (in WCF REST services which communicate with JSON messages, but it should work the same way in your case). This is all explained in the JQuery Ajax documentation.
Hope this helps.
I am simply learing Ajax with jQuery and have a simple page method that takes in a parameter and returns a string. For some reason, I am not getting the return string but I am getting to my 'success' message:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "testFormMatt.aspx/sayHello",
contentType: "application/json; charset=utf-8",
data: '{"name": "matt"}',
dataType: "json",
success: function(msg) {
$.jGrowl('The web service has been successfully called');
$('#result').append(msg);
}
});
});
When you call append, you need to specify the property of the JSON object that you want to append.
So if your page is returning:
{ message: "Hello, Matt" }
Then you'd need to call append like this:
$("#result").append(msg.message);
If your page is not returning JSON, then you need to take the dataType: "json" out of the $.ajax call. The dataType parameter is for specifying the expected data type of the response, not the data type of the request.