Skip to content

Instantly share code, notes, and snippets.

@ggendre
Last active December 19, 2015 16:39
Show Gist options
  • Save ggendre/5985481 to your computer and use it in GitHub Desktop.
Save ggendre/5985481 to your computer and use it in GitHub Desktop.
how to make an ajax call on BB10 native (JS) side
//ajax call on BB10 JS side, based on jquery $.ajax options
function handleAjaxCall(options,callback){
var url= options.url;
var type= (options.type in [ 'POST', 'GET' ]) ? options.type : "GET"; //default to GET
var data = options.data ? options.data : {}; //default to empty params
var request = new XMLHttpRequest();
request.onreadystatechange=function() {
if(request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
console.log("Response = " + request.responseText);
try{
var response = JSON.parse(request.responseText);
}catch(e){
var response = request.responseText;
}
var params={
success : true,
data : response
}
callback(params);
}
else {
// This is very handy for finding out why your web service won't talk to you
console.log("Status: " + request.status + ", Status Text: " + request.statusText);
var params = {
error: true,
req: request,
err : request.statusText
}
callback(params);
}
}
}
var encodedString = encodeURIComponent(data);
request.open(type, url, true); // only async supported
// You might not need an auth header, or might need to modify - check web service docs
//request.setRequestHeader("Authorization", "Bearer " + yourAccessToken);
// Post types other than forms should work fine too but I've not tried
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Form data is web service dependent - check parameter format
var requestString = "text=" + encodedString;
request.send(requestString);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment