Jquery unable to get the response from WCF REST service - javascript

I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.

You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
})​;​
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.

I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.

Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);

Related

NetSuite Restlet Using jQuery

I am trying to access a NetSuite restlet using jQuery. Here is my code for that:
jQuery.ajax({
url: "https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models",
type: "GET",
dataType: "json",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "NLAuth nlauth_account=ACCOUNT#, nlauth_email=EMAIL, nlauth_signature=XXXXXX, nlauth_role=ROLE#")
}
})
.done(function(data){
console.log(data);
});
When I check the "Network" tab in Chrome/FF it's giving me the following 401 response:
XMLHttpRequest cannot load https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.tracksandtires.com' is therefore not allowed access. The response had HTTP status code 401.
Am I not formatting the Authorization part correctly? I can't find any documentation on accessing a NetSuite Restlet via jQuery so I'm sort of shooting blind here. Should I just use vanilla javascript and not jQuery? Any help would be much appreciated!
Try using jsonp like this:
jQuery.ajax({
url: "https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models",
type: "GET",
crossDomain: true,
dataType: "jsonp",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "NLAuth nlauth_account=ACCOUNT#, nlauth_email=EMAIL, nlauth_signature=XXXXXX, nlauth_role=ROLE#")
}
})
.done(function(data){
console.log(data);
});
More info:
How does Access-Control-Allow-Origin header work?
Basically don't
Although #adolfo-garza 's answer does show JSONP correctly you gain nothing by using a Restlet and you give up a login that can never be used for something sensitive. Basically you've put one of your Netsuite credentials out on the public internet. Nothing good can come of this.
This is one of the use cases for Suitelets. You create a Suitelet that has public access (available without login; audience all roles) and then you don't need authentication (though there are ways to rely on shopping session or checkout session authentication if you need filtering information by customer).
If you are just trying to test a real Restlet Use Case then you should use Node or some non-browser based application to do that.

Get JSON(P) from other site [duplicate]

This question already has answers here:
Unexpected token colon JSON after jQuery.ajax#get
(2 answers)
Closed 7 years ago.
I am trying to get data with Ajax.
Data is json. I use jquery and angular.
But result is undefined or error.
Here is my jquery code:
$(document).ready(function() {
var url = "http://market.dota2.net/history/json/";
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
});
In Angular i am usin jsonp method. Whats wrong ?
By the way, in pure Java i can get data from this url...
Whats wrong?
You're trying to call an endpoint that provides JSON as though it provided JSONP. That won't work; they are different (though related) formats.
Example JSON:
{"foo":"bar"}
Example JSONP:
callback({"foo":"bar"})
Note the difference: JSONP is actually a JavaScript function call, wrapped around the JSON.
If the API supports JSONP, call an endpoint that supports it.
If not, you can't query it directly unless the provider supports Cross-Origin Resource Sharing and shares with your origin, because of the Same Origin Policy that applies to ajax calls.
By the way, in pure Java i can get data from this url...
Because the Java code is not running in a context that is controlled by the SOP, and so can get the data from that endpoint (as JSON) and use it. This is also the same reason that just posting that URL into a browser address bar lets us see the data. But ajax calls are governed by tighter rules.
If you expect json, dont use jsonp but json.
$(document).ready(function() {
var url = "http://market.dota2.net/history/json/";
$.ajax({
type: 'GET',
url: url,
async: true, /* it fails with false */
contentType: "application/json",
dataType: 'json',/* <== here */
success: function(data) {
console.log(data);
}
});
});
Are you using jsonp consciously ? Do you know what it is ? If not, use json. Or get informed about JSonP: https://en.wikipedia.org/wiki/JSONP
I tried on Safari:works.
On Chrome & FFox: does not work + Erreur "Cross Domain Origin"
XMLHttpRequest cannot load http://market.dota2.net/history/json/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
That means you cannot get JSon with your client/machine from the API server. So you should indeed use JSonP, but... you miss the callback or something in the API documentation.

SOAP-request No 'Access-Control-Allow-Origin' header soapUI header

Im trying to accomplish SOAP-post to get back XML data.
Problem is that "No 'Access-Control-Allow-Origin' header" and I suppose that the server needs to add the header.
So I created a MockService in SOAPui and copied the server response. But I still get the same problem. In soapUI in the response I added this http://imgur.com/TZXM2Ca
function soap() {
var sr = MySoapRequest;
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("SOAPAction", "x");
},
type: "POST",
dataType: "xml",
data: sr,
crossDomain: true,
success: function (data) {
console.log(data);
},
error: function (error) {
},
contentType: "text/xml; charset=\"utf-8\""
});
}
By default, browsers cannot make POST requests via AJAX to URLs which are not in the same origin as the current page. For example, if you have open a page that sits in the URL http://foo.com, and that page tries to post some data (via AJAX) to http://bar.com, you will normally get the error you are seeing now.
If you want to make this work, you have to configure your server to accept requests via Cross-Origin Resource Sharing (CORS). I suggest that you get some information about CORS, you can find a lot of documentation online about it. An extensive overview can be found here.
As for the actual implementation of CORS on your server, it depends on which platform you are using. If you are using PHP, have a look at this question.

using $ajax to perform GET request from tomcat server always fail jQuery

I have backend webService on tomcat server.always when I perform any request (post, get),code enters on error method.
jQuery code is:
var jqxhr = $.ajax(
{
type:"GET",
url:url
success: function() {
alert("success");
},
error: function() {
alert("fail");
}
});
my url is:
http://"192.168.20.220":6060/NostServices/rest/user/resend_activation_email/mailex#blah.com
error message on log is:
XMLHttpRequest cannot load http://"192.168.20.220":8080/NostServices/rest/user/resend_activation_email/dsgg#sdfkmj.com.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://"192.168.20.220":8383' is therefore not allowed access.
web service server is tomcat.
response of this requset can be 1 for success and -1 for mail not valid
and always enter on fail method and when I try to alert response it output [object object]
thanks you for your help
It's a JSONP request so your server side script needs to return data wrapped in callback:
For example
var url = 'http://example.com/req.json?callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json);
},
error: function(e) {
console.log(e.message);
}
});
And on server side:
jsonCallback({});
As your error says your code is failing because of the cross domain error problem. A very detailed answer is found here:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access
Please put in some effort to google these issues, this is a very common thing your trying and all errors have been encountered before and have been resolved somewhere. People will get very annoyed here if you show no effort to debug it yourself or provide all the required detail such as:
All relevant code
Print out of any variables in the code e.g. URL's
Any error message
A list of things you have tried
On a side note a URL should not have quotes it it. It should not be
http://"192.168.1.1":.........
it should be:
http://192.168.1.1:........

How can I use make HTTP calls to an API in Javascript?

How can I use public APIs in a Javascript application? For example I want to make a call to the Zillow API using JQuery AJAX.
When issuing the request in JQuery AJAX (shown below) I get the following error:
XMLHttpRequest cannot load "MY HTTP REQUEST URL". Origin "MY WEB DOMAIN" is not allowed by Access-Control-Allow-Origin.
var requesturl = "http://www.zillow.com/webservice/GetRegionChildren.htm?zws-id="+zwsid+"&state="+state+"&city="+city+"&childtype=neighborhood";
Code:
var jqxhr = $.ajax({
url: requesturl
})
.done(function(data) {
console.log(data);
});
I've also tried adding crossDomain, dataType and headers params (shown below), but they haven't helped.
var jqxhr = $.ajax({
url: requesturl,
crossDomain: true,
dataType: 'xml',
headers: { 'Access-Control-Allow-Origin': '*' },
beforeSend: setHeader
})
.done(function(data) {
console.log(data);
});
Most popular public API's support JSONP request. Refer API documentation for details.
Cross ajax domain request is restricted. So you will be needing to make JSONP request. Don't worry JQuery will handle most of it.
Sounds like you need to register your url with Zillow, maybe contact them / hunt around on their doc pages. Also jquery has a get method which makes ajax requests even simpler. There's also getJSON if that is the return format.

Categories