Syntax Error Unexpected token only for Jelly bean phones - javascript

I have an HTML5 based android app. The app was working perfectly fine and was able to fetch data from the backend system. However, since today the app is reporting a weird error while fetching data SyntaxError Unexpected token and shows some gibberish character. This error is occurring only on phones having Jelly Bean (Android 4.2.1); it was working perfectly fine till last week and there has been no change in the code. In the below code the ajax call goes into the error section for Android 4.2.1.
function getData() {
jQuery.support.cors = true;
$.ajax({
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('X-SMP-APPCID', connectionID);
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(appUser + ":" + appPass));
},
url: calURL, //calURL is the connection to backend
crossDomain: true,
dataType: "json",
processData: false,
xhrFields: {
withCredentials: true
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error fetching Data - " + errorThrown);
hideMainContent(false);
document.getElementById("data").innerHTML = "Error fetching data - " + errorThrown;
if(errorThrown.indexOf("Unauthorized") > -1){**// Invalid token reported here**
document.getElementById("setButton").innerHTML = "<p>Unauthorized error can occur if your password has expired or changed. Below option can be used to change application password to your new Password.</p><button onclick=\"changePassword()\" class=\"ui-btn style=\"margin:10% 25%;width:50%;\">Change Password</button>";
}
else{
document.getElementById("setButton").innerHTML = "<p>Temporary communication error. Please refresh after some time.</p>";
}
},
success: function(jsonData) {
},
});
return;
}
Any help in this regards is highly appreciated.
Thanks!

Related

how to show custom REST API error messages in javascript client

I have Java REST API generated using swagger, in that if client is unauthorized then then i am sending custom error messages in response
public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, String authBase64String) throws NotFoundException {
// do some magic!
ErrorRequestObject erb;
ArrayList <ErrorRequestObject> erbs = new ArrayList<ErrorRequestObject>();
if (authBase64String == null)
{
erb = new ErrorRequestObject(); erb.setError("Missing Authorization in Header"); erb.setPath("Header:Authorization");
erb.setProposedSolution("Authorization Header should contain user:pwd:nhPath as Base64 string");
erbs.add(erb);
}
if (erbs.size() == 0)
{
//success code here
}
else
{
return Response.status(400).entity(erbs).build();
}
}
I call this API using ajax as follows,
$.ajax({
url : URL,
type : "DELETE",
dataType : "json",
contentType : "application/json",
async : false,
success : function(result){
Response.resolve(result);
console.log("Response : " + JSON.stringify(result));
}
});
now when i call this API with ajax call it without authorization in header it gives me 400 status that is fine as expected but how do i get error object created with java ? can anyone please tell me how do i get this error object at javascript client ?
Something like this:
$.ajax({
url : URL,
type : "DELETE",
dataType : "json",
contentType : "application/json",
async : false,
success : function(result){
Response.resolve(result);
console.log("Response : " + JSON.stringify(result));
},
error: function(err) { /* your code here*/})
});
You can use the error function like
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
Where,
The jqXHRobject, textStatus - a string describing the type of error that occurred and an optional exception object as errorThrown, if one occurred. So, you can manipulate the statusCode and everything from this parameters like,
jqXHR.status == 400

AJAX call doesn't go into "error:" block if the API server returns http 500

I want to implement a retry logic in my javascript code. This is how I'm calling the API:
$.ajax({
url: api_url + 'report',
type: 'GET',
dataType: 'json',
async: false,
tryCount : 0,
retryLimit : 3,
headers: {
"Authorization": "Basic " + btoa(api_username + ":" + api_pass)
},
data: {start: start_date, end: end_date},
success: function(result) {
data = result.results;
console.log("success");
},
error : function(xhr, textStatus, errorThrown ) {
console.log("in error");
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
console.log("try count:");
console.log(this.tryCount);
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
console.log("still 500");
} else {
console.log("still !500");
}
}
});
So when there are issues with the server and it returns http 500 then still my control in the above JS file doesn't go into the "error:" block and this line: "console.log("in error");" doesnt get printed on the console.
How can I correctly implement a retry logic in my code in case my server returns 500 then it should keep on retrying for some x amount of times?
500 error generally means that something is wrong with backend server. So it doesn't get into error block of client JavaScript. I don't think there is anything you can do. But in general you can always ask backend developers to do better error handling and return apt error response if possible.

AJAX request not working on remote host

I've got an AJAX request which pulls the data from the form and POSTs it to an API. The weird thing is it works perfectly fine on localhost but fails silently when I upload to remote server. And I mean silently: the response code is blank, there's nothing in the logs. I've checked on Firefox and Chrome. jQuery is loaded, function is firing properly. The code is below:
function send() {
console.log("preparing");
var beacon = {
beaconID: $("#beaconID").val(),
name:$("#beaconName").val(),
campaignID:$("#campaignID").val(),
clientID:$("#clientID").val()
}
console.log("payload:");
console.log(beacon);
$.ajax({
type: 'POST',
url: '../beaconAPI/index.php/createBeacon',
data: JSON.stringify(beacon),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
console.log("done:");
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
From the comments you posted
10:33:21.046 "{"readyState":0,"responseText":"","status":0,
"statusText":"error"}" addBeacon.html:34 10:33:21.046 "AJAX error: error : "
A status code of zero means one of two things:
You are running off file protocol
The page refreshed as Ajax call is made
Since you said this is on production, sounds like it is a case of #2.
So you need to cancel the action that is causing the page to refresh. Since you do not show how you call send, here is some basic ways of cancelling the action.
onclick="send(); return false"
onsubmit="send(); return false"
$("#foo").on("click", function(e) {
send();
e.preventDefault();
});

Ajax crossdomain request with jquery and BASIC-authentication?

I really appreciated if somebody could tell me what is wrong in that authentication? I take the authentication off from the server to test without it, but javascript is broken.
$('#btnSignIn').click(function() {
var username = $("#username").val();
var password = $("#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var final = "Basic " + $.base64.encode(tok);
console.log("FINAL---->" +final);
alert("FINAL---->" +final);
return final;
}
$.ajax({
type: "GET",
contentType: "application/json",
url: "http://localhost:8080/SesameService/webresources/users/secured/login",
crossDomain: true,
dataType: "text",
async: false,
data: {},
beforeSend: function (xhr){
xhr.setRequestHeader('authorization', make_base_auth(username, password));
},
success: function() {
alert('Thanks for your signin in! ');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(' Error in signIn-process!! ' +textStatus);
}
});
});
ERROR: If I take the
beforeSend: function (xhr){
xhr.setRequestHeader('authorization', make_base_auth(username, password));
-part off from the function, I can get into REST-service. I haven't got authentication on at the moment. Could this be the reason or shoud I have the authentication on in the server when using that header?
contentType: "application/json",
#GET
#Path("/secured/login")
#Produces({"text/plain"})
public String login() {
return "Is it working or not?";
}
When using beforeSend-part in JS, I got an error:
[Exception... "Failure" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://localhost:8383/Sesame/assets/js/jquery.min.js :: .send :: line 3" data: no] { message="Failure"
, result=2147500037
, name="NS_ERROR_FAILURE"
,
If I have understood correctly, "authorization + Basic " in header tells the Glassfish-server, that basic-authentication will be done. After authentication it goes to REST-service and in my case returns json-object to HTML5-client. HTML5-client is running in localhost:8383 and the rest services are running in localhost:8080.
If I run secured rest-services straight in localhost:8080, it is working, so that is not the problem. The problem is that when I am using or trying to use rest-services from different domain localhost:8383, I get get the JS-error console.log('----ERROR IN ------Siging IN----------'); I am not 100 % sure, but I think that the problem is 401 unauthorized, so cross domain authentication is not working.
Shoud I insert crossDomain: true? I have seen it somewhere, maybe that can be the case?
In serverside I've got the filter:
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>util.CrossOriginResourceSharingFilter</param-value>
</init-param>
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
response.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "content-type");
return response;
}
QUESTIONS
1) is it possbile that if server is not configured for authentication and I still use the authorization-header breaks the app and cause the error?
2) What that JS-error means?
Cheers,
Sami

Post Photo to Facebook Page not associated with User

I am building a website that will allow any authenticated Facebook user to post photos to a specific album associated with a Facebook page. I am using the JavaScript SDK for this task. This is the code I have so far:
window.fbAsyncInit = function () {
FB.init({
appId: "492414284132122",
status: true,
cookie: true,
xfbml: true,
channelUrl: "http://wineoclock.dev.mag/ClockMoments/channel.html"
});
};
function uploadPhoto() {
console.log("called uploadPhoto()...");
FB.login(function (response) {
if (response.authResponse) {
document.getElementById("access_token").value = FB.getAuthResponse()["accessToken'];
var form = document.getElementById("fbPhotoUpload");
var formData = new FormData(form);
// indicate to user that upload is in progress
document.getElementById("btnUpload").value = "Posting...";
document.getElementById("btnUpload").disabled = true;
// post photo to Facebook
$.ajax({
type: "POST",
// post to "Timeline Photos" album
url: "https://graph.facebook.com/283773431737369/photos",
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function (response, status, jqXHR) {
console.log("Status: " + status);
if (!response || response.error) {
alert("Error occured:" + response.error.message);
}
else {
document.getElementById("fbPhotoUpload").reset();
$("#ThanksModal").reveal();
}
document.getElementById("btnUpload").value = "Post Photo";
document.getElementById("btnUpload").disabled = false;
},
error: function (jqXHR, status, errorThrown) {
console.log("AJAX call error. " + status);
console.log("errorThrown: " + errorThrown);
},
complete: function (jqXHR, status) {
console.log("AJAX call complete. " + status);
}
});
}
else {
alert("Login failed: " + response.error);
}
});
}
Running the code above, I discovered that the selected image gets uploaded, but it is uploaded to Facebook account that is logged in. This is not what I wanted. I wanted to upload it to the target fan page (designated in the AJAX POST request), instead of the logged in user.
I have read on the Internet that I need to request a page access token, instead of a user access token. To do so I would need to log in as the target page, as described in the Facebook doc here.
Is there a way to retrieve the page access token without having to login as the administrator of the Facebook page? If required, can the login be done behind-the-scenes?
EDIT:
I think i misunderstood You; the process described at link i posted results in getting access token for ANY user, you only have to do this once.
I do strongly believe that this is not possible; if it would be doable, practically any app could post at any fanpage.
According to solution from here:Extending Facebook Page Access Token, You need have administrator privileges to convert your short-lived page access token to a long-lived (2 months actually instead of couple of hours). The whole process is well described at the link.

Categories

Resources