How to invoke rest service using dojo xhr? - dojo

try{
var targetURL ="http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/1/query?where=STATE_NAME%3D%27Florida%27&f=json";
var xhrArgs = {
url: targetURL,
handleAs: "json",
load: function(data) {
alert(data);
},
error: function(error) {
alert("An unexpected error occurred: " + error);
}
};
var deferred = dojo.xhrGet(xhrArgs);
}catch(e){
alert(e);
}
Is this the right way of calling rest service?
I am getting null response from the above code.

dojo/xhr cannot be used for cross domain requests.
Is http://sampleserver1.arcgisonline.com/ the same domain that loads the web page or a different server?
If it is the same server, drop the domain name (ie ArcGIS/rest/services/...);
If not, you can use jsonp
https://dojotoolkit.org/reference-guide/1.9/dojo/request/script.html#dojo-request-script
Another alternative is to call a service located on the web server that acts as a proxy and makes the call to the other server.

Related

ionic 2: http get request not working (proxy added)

I'm using Http from #angular/http to send GET requests, but the server is not receiving the request. The generated urls are correct because when I log them and open them in browser (I've tried all of Chrome, Firefox and Safari), the server does receive these requests.
This is how I am doing this:
let logButtonUrl = this.urlGenerator.generateTiramisuUrlTemp(this.servletPath,
argMap);
console.log("logButtonUrl:"+logButtonUrl);
return this.http.get(logButtonUrl).map(this.writeSuccess);
Function writeSuccess:
private writeSuccess(res: Response) {
let body = res.json();
let rows_affected = body.data[0].rowsAffected;
if (rows_affected == "1") {
return true;
} else {
return false;
}
}
I got no error message in browser console, so it's probably not because of the CORS issue discussed here:
http://blog.ionic.io/handling-cors-issues-in-ionic/
I also tried using a proxy. I added this in ionic.config.json:
{
"path": "/backendTemp",
proxyUrl": "http://128.237.217.70:8080" /*the ip address of the target server*/
}
And replace the ip address in my generated urls with "/backendTemp". Still not working.
Any suggestions/thoughts on this? Thanks a lot!
Use the $http (https://docs.angularjs.org/api/ng/service/$http):
.controller('RequestCtrl', function ($http) {
$http({
method: 'GET',
url: 'http://128.237.217.70:8080/backendTemp'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Titanium open remote data in url

I'm parsing remote data in to my app and uses it through arguments. One of the data types is a url adresse i want to open in the url. I have an idea that I have to open it with the openURL function but I can't seem to get it to work. Anyone have a working example?
You have to utilize in-built HttpClient
var url = "http://www.you_remote_url.com";
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("Received text: " + this.responseText);
alert('success');
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
// Prepare the connection.
client.open("GET", url);
// Send the request.
client.send();

Consuming authorized asp.net webapi service using jQuery ajax

I'm developing IPAD Application using phone gap, HTML5, and jQuery. My webservice is built upon ASP.NET WEBAPI with forms authentication. while accessing api, authentication window is asking for username and password. After providing username and password we can get the result. But while consuming the same service using jquery ajax, error thrown with a message "Unauthorized". Can any one help on this issue.
ScriptBlock in which i m accessing the url
$.ajax({
type: 'POST',
url: 'https://myservice.com/api/mypostmethod',
data: {
'item': ItemXml,
'room': RoomXml
'User_Id': 12313
},
success: function (result) {
ProcessResponse(result);
},
error: function (xhr, textStatus, error) {
console.log("Local To Live - " + xhr.statusText);
console.log("Local To Live - " + textStatus);
console.log("Local To Live - " + error);
}
});
How to call this service? I also tried to user jQuery xhr headers and used code is as below
function getAuthorizationHeader(username, password) {
var authType;
if (password == "") {
authType = "Cookie " + $.base64.encode(username);
}
else {
var up = $.base64.encode(username + ":" + password);
authType = "Basic " + up;
};
return authType;
};
$.ajax({
type: 'POST',
url: 'https://myservice/api/mypostmethod',
data: {
'item': '',
'room': '',
'User_Id': 12313
},
beforeSend: function (jqXHR, Settings) {
var AuthHeaders = getAuthorizationHeader("username", "password");
jqXHR.setRequestHeader("Authorization", AuthHeaders);
},
success: function (result) {
ProcessSyncResponse(result);
},
error: function (xhr, textStatus, error) {
alert("Error - StatusCode : "+xhr.status );
}
});
Kindly help on this issue.
Thanks.
If you're set on using forms authentication, take a look at this article for an example on how to use it over AJAX calls. Make sure you're communicating with the service over HTTPS or else you'll have major security problems.
I think the better solution would be to implement some kind of token authentication so you're not passing the username/password in your requests and don't have to maintain some kind of stateful connection with the server. You should look into this.

Same Origin Policy Error when using jQuery JSONP with CloudFlare API

I recieve an error (XMLHttpRequest cannot load https:// www.cloudflare.com/api_json.html?tkn=&email=&z=&a=rec_load_all&callback=%3F. Origin http:// domainmanager.tech-bytes.org is not allowed by Access-Control-Allow-Origin.) (spaces inserted in URLs due to Stack Overflow link limit) when trying to send a JSONP request via jQuery to CloudFlare. The CloudFlare API states that you can ask for a JSONP callback by appending a &callback=mycallback parameter. I am not sure if I am supposed to replace mycallback with something, I tried replacing it with ? as that is what some other resources said, or if I have to do some other modifications to my code.
Try in this way for cross domain request.
$.ajax({ url: "yourUrl",
data:{paramName1: JSON.stringify(paramValue1),paramName2: JSON.stringify(paramValue2)},
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(data) {
alert(data.d);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
You can use CORS for this purpose.
Example code:
jQuery.support.cors = true;
function CrosDom_ajax(url) {
if (window.XDomainRequest
&& $.browser.msie
&& $.browser.version < 10) {
xdr = new XDomainRequest();
if (xdr) {
xdr.onload = function () {
alert(xdr.responseText);
};
xdr.open("get", url);
xdr.send();
}
}
else {
$.ajax({
url: url,
success: function (response) {
},
error: function (data) {
}
});
}
}
Also you need to Write the following code in server side, to allow cross domain access
Response.AppendHeader("Access-Control-Allow-Origin", "*");

PhoneGap with WCF Rest Service

So I have started with PhoneGap/Cordova (windows phone) and WCF Rest Services, however, I am having problems on getting the Emulator to interact with the WCF Service.
At first I was thinking that maybe the Emulator could not connect to the localhost WCF Service, so I published the WCF Service on an external host however the problem still occured... i.e. still not able to make a call to the WCF Service.
The code I have is shown below:
The javascript file for the PhoneGap application is the following:
function getAjax() {
var jqxhr = $.ajax({
url: 'http://link.to.service.com/service1/',
//headers:
beforeSend: function (xhr) {
//xhr.overrideMimeType('text/plain; charset=x-user-defined');
},
dataType: 'json'
})
.done(function (data) {
var element = document.getElementById('ajaxCall');
element.innerHTML = JSON.stringify(data, null, "\t");
})
.fail(function (xhr, status, error) {
showError(error);
})
.always(function () { showAlert("complete"); });
}
Then the WCF Service contains the following method:
[WebGet(UriTemplate = "")]
public List<SampleItem> GetCollection()
{
return new List<SampleItem>()
{
new SampleItem()
{
Id = 1,
StringValue = "Hello" }
};
}
Therefore, when the a call to the javascript method "getAjax" is done, the WCF Service method should be called however it keeps entering the fail function instead showing an error message 'undefined'.
Is there something that I am missing out here?
After further investigation, this has been resolved using the line:
jQuery.support.cors = true;
Just a small quote from the jQuery library for those having the same issue, this is what the above line does:
cors is equal to true if a browser can create an XMLHttpRequest object and if that XMLHttpRequest object has a withCredentials property. To enable cross-domain requests in environments that do not support cors yet but do allow cross-domain XHR requests (windows gadget, etc), set $.support.cors = true;. CORS WD