Retrieving of Restful web service values in android for Titanium - appcelerator

We are using the same restful web service code from serviceutility.js for both android and ios. But the service is getting hit and values are retrieved only in ios. The same code is not working in android and we are getting the following error:
[ERROR] : TiExceptionHandler: (main) [2,821093] - In alloy/controllers/home.js:25,32
[ERROR] : TiExceptionHandler: (main) [0,821093] - Message: Uncaught TypeError: Cannot read property 'status' of null
[ERROR] : TiExceptionHandler: (main) [0,821093] - Source: if ("1" == response.status) alert(response.message); else if ("0"
[ERROR] : V8Exception: Exception occurred at alloy/controllers/home.js:25: Uncaught TypeError: Cannot read property 'status' of null.
Titanium SDK is 5.1.2 GA
exports.login = function(user, cb) {
var response = null;
if (Ti.Network.online) {
var xhr = Ti.Network.createHTTPClient({
timeout : 10000,
validatesSecureCertificate : false
});
xhr.onload = function() {// Onload
var responseTxt = this.responseText == '' ? '{}' : this.responseText;
try {
response = JSON.parse(responseTxt);
cb(response, 'SUCCESS');
} catch(e) {
cb(response, 'ERROR');
}
};
xhr.onerror = function(e) {
if (xhr.status === 0) {
cb(response, 'TIMEDOUT');
} else {
cb(response, 'ERROR');
}
};
url = "https://";
var postData = {
employeeId : user.employeeId,
password : user.password
};
xhr.open('POST', url);
xhr.setTimeout(10000);
xhr.setRequestHeader('employeeId', user.employeeId);
xhr.setRequestHeader('password', user.password);
xhr.send();} else {
cb(response, 'NO_NETWORK');
}};
The below code is for index.js file where the actual retrieval of values happen.
if (Ti.Network.online) {
loginUtil.login(user, function(response, status) {
Ti.API.info("status----" + status);
if (response.status == "0") {
Ti.API.info("status== " + response.status);
Ti.App.role = response.role;
Alloy.createController('home', {employeeId:$.userTextField.value,password:$.passwordTextField.value,from:"index"}).getView().open();
} else if (response.status == '1') {
alert(response.message);
} else {
alert("Please enter the correct credentials");
}
});
}
Please help us on this.

Looks like you are ONLY returning a string value instead of the entire response object. Then in your controller you attempt to access the .status property of the response object.
//this line returns the string responseTxt
response = JSON.parse(responseTxt);
Try returning the entire response object instead.
response = JSON.parse(this);
Then in your index.js controller use/ display the status property
alert(response.status);

Your index.js expected response to be an object, but that is only the case where you call callback like this:
response = JSON.parse(responseTxt);
cb(response, 'SUCCESS');
All other places where you call callback the response variable is null, since that is what you initialise it with on the second line.

Your callback returns two parameters, response & status, the second param is never used.
From reading the login function code, you only get to access the response object if status == "SUCCESS"
if(status === "SUCCESS"){
if (response.status == "0") {
Ti.API.info("status== " + response.status);
Ti.App.role = response.role;
Alloy.createController('home', {employeeId:$.userTextField.value,password:$.passwordTextField.value,from:"index"}).getView().open();
} else if (response.status == '1') {
alert(response.message);
} else {
alert("Please enter the correct credentials");
}
}
else {
alert("whoops, please try again !"); // a more generic message.
}

Related

React native: How to validate username and password while submitting

I have validate username and password,if username and password is wrong ,then i want through error like 'Invalid username/password'.if any one know,pls let me know.
async submit() {
//Validating username and password
const { username, password } = this.state;
if(username == ''){
this.setState({error:'Username is required'});
} else if(password == ''){
this.setState({error:'Password is required'});
} else {
this.setState({error: null})
let collection={};
collection.username=this.state.username;
collection.password=this.state.password;
// console.warn(collection);
var url = 'my url';
try {
let response = await fetch(url,
{
method: 'POST', // or 'PUT'
body: JSON.stringify(collection), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
});
let res = await response.text();
// console.warn(res);
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
console.log(accessToken);
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
// console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
//Handle error
console.log('Success:',response);
let error = res;
throw error;
}
} catch(error) {
console.log("error " + error);
}
}
}
response after giving invalid username/password:
0 {…}
field :password
message :Incorrect username or password.
I have written code like this based on status to validated username/password is correct/wrong.so here am posting code if it is useful for anyone in future.below code is,
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
console.log('Success:',response);
this.setState({error:'Invalid username/password'});
let error = res;
throw error;
}

AJAX call not hitting breakpoints in Async handler

I wrote a quick AJAX script to be called on a button press event which in turn invokes an asysnc handler to pull data from remote APIs. I modified that same script to invoke another handler that was not async and it works fine, I'm not sure why it's not hitting breakpoints in Visual Studio. Here's the AJAX script.
$("#RunNewShodanQuery").click(function (d) {
$.ajax(
{
type: "POST",
async: true,
url: "/Tools/Test?handler=UpdateResultsAsync",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
},
complete: function (res) {
console.log(res);
}
});
})
Here's the handler in question.
public async Task OnPostUpdateResultsAsync()
{
ModelState.Clear();
foreach (Entry e in _context.Entries)
{
// TBI
}
// Update Date of Last Scan so as not to make needless API calls spamming refreshes
DateOfLastScan = DateTime.Now;
// Dispose of the client once we're done
client.Dispose();
}
I've placed breakpoints in another test handler and modified the above AJAX with a URL to point to the new test handler and VS stops on breakpoints within that handler.
public void OnPostTestHandler()
{
int seven = 5;
}
I'm currently at a loss as to why Visual Studio isn't hitting breakpoints in the async handler. From the browser, I'm seeing entries return with status 200 and it appears that it is executing the handler code just not stopping in it. Any suggestions would be very welcome.
By convention, the name of the handler method is selected based the value of the handler parameter according to the scheme OnPost[handler]Async.
Which means that, for OnPostUpdateResultsAsync, the handler name is UpdateResults instead of UpdateResultsAsync.
For Razor page, PageActionInvoker will call DefaultPageHandlerMethodSelector.SelectHandlers to select the handler.
private List<HandlerMethodDescriptor> SelectHandlers(PageContext context)
{
var handlers = context.ActionDescriptor.HandlerMethods;
var candidates = new List<HandlerMethodDescriptor>();
// Name is optional, may not be provided.
var handlerName = GetHandlerName(context);
// The handler selection process considers handlers according to a few criteria. Handlers
// have a defined HTTP method that they handle, and also optionally a 'name'.
//
// We don't really have a scenario for handler methods without a verb (we don't provide a way
// to create one). If we see one, it will just never match.
//
// The verb must match (with some fuzzy matching) and the handler name must match if
// there is one.
//
// The process is like this:
//
// 1. Match the possible candidates on HTTP method
// 1a. **Added in 2.1** if no candidates matched in 1, then do *fuzzy matching*
// 2. Match the candidates from 1 or 1a on handler name.
// Step 1: match on HTTP method.
var httpMethod = context.HttpContext.Request.Method;
for (var i = 0; i < handlers.Count; i++)
{
var handler = handlers[i];
if (handler.HttpMethod != null &&
string.Equals(handler.HttpMethod, httpMethod, StringComparison.OrdinalIgnoreCase))
{
candidates.Add(handler);
}
}
// Step 1a: do fuzzy HTTP method matching if needed.
if (candidates.Count == 0 && AllowFuzzyHttpMethodMatching)
{
var fuzzyHttpMethod = GetFuzzyMatchHttpMethod(context);
if (fuzzyHttpMethod != null)
{
for (var i = 0; i < handlers.Count; i++)
{
var handler = handlers[i];
if (handler.HttpMethod != null &&
string.Equals(handler.HttpMethod, fuzzyHttpMethod, StringComparison.OrdinalIgnoreCase))
{
candidates.Add(handler);
}
}
}
}
// Step 2: remove candidates with non-matching handlers.
for (var i = candidates.Count - 1; i >= 0; i--)
{
var handler = candidates[i];
if (handler.Name != null &&
!handler.Name.Equals(handlerName, StringComparison.OrdinalIgnoreCase))
{
candidates.RemoveAt(i);
}
}
return candidates;
}

How to return error message from ajax post in Node.js

I am submitting a form to node js server via ajax and expect an error if any, but instead of showing me the error , i am redirected to a whole new page with the error. I have used res.send , res.json, res.writheHead()... But i am always redirect to a new page
$.ajax({
url: $this.attr('/api/adduser'),
type: $this.attr('POST'),
data: $this.serialize(),
dataType: 'json', // JSON
success: function(json) {
alert('Erreur : '+ json.reponse);
}
})
event.preventDefault()
and on the server side i have:
sql.query("INSERT into internes(email,nom,prenom,password,privilege,datenaissance,gender,details,user_Add_Mail)"+
" VALUES(lower($1),lower($2),lower($3),lower($4),lower($5),$6,$7,lower($8),lower($9))",
req.body.email,req.body.nom,req.body.prenom,req.body.pass1,priv,req.body.datenaissance,parseInt('0'),req.body.details,req.body.passAdmin)
.then(function(result){
res.redirect('/api/users');
})
.catch(function(erreur){
res.json(400, {'success': erreur})
})
It seems that the error you're getting is being identified as a successful response from your sql promise. To fix that do something like
sql.query("INSERT into internes(email,nom,prenom,password,privilege,datenaissance,gender,details,user_Add_Mail)"+
" VALUES(lower($1),lower($2),lower($3),lower($4),lower($5),$6,$7,lower($8),lower($9))",
req.body.email,req.body.nom,req.body.prenom,req.body.pass1,priv,req.body.datenaissance,parseInt('0'),req.body.details,req.body.passAdmin)
.then(function(result){
// look into your result to see if you have what you asked for
if(result.error) {
res.status(500).send({error: 'you have an error'});
}
res.redirect('/api/users');
})
.catch(function(erreur){
res.json(400, {'success': erreur})
})
One option is to use ajax error:
success: function (json) {
alert(json);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
}
Doc

What is XMLHttpRequest's life cycle? When will the XMLHttpRequest be destroyed?

When is XMLHttpRequest destroyed?
I just wrote the simple function below, and xmlhttp has been sent successfully, but responseText isn't sent to the function SetStringinDiv(). The variable str is empty and the variable location has value.
I have no idea how to fix it, and I don't know what the keyword for this problem is, either. If this kind of question already exists, please tell me how to find it or what the keyword is.
<script>
function foo(){
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var str = xmlhttp.responseText;
SetStringinDiv("div1", str);
}
}
xmlhttp.open("GET", "uri", true);
xmlhttp.send();
}
</script>
<script>
function SetStringinDiv(location, str) {
document.getElementById("location").innerHTML = location;
document.getElementById("str").innerHTML = str;
if (document.getElementByID(location) == null) {
document.getElementById("error").innerHTML += ">> error, can not find the div, "
+ location + "\n";
}
document.getElementByID(location).innerHTML = str;
}
</script>
Check for xmlhttp.status != 200 and print out an error. Print out the readystate and status on each call to onreadystatechange. I think you will see an error message in statusText.
These days it is recommended to not use the onreadystatechange callback. I use the code below. Note that if the server does not respond and does not close the connection that your request won't timeout for quite some time (2-5 minutes) - either in your code or that below. If it is sitting there, shut down the server. You will get an immediate error response then.
var req = new XMLHttpRequest(),
done = function(response) {
callback(cache[uri.split('/').pop()] = cache[uri] = response);
};
req.open("GET", uri + ".lispz", true);
req.onerror = function(err) {
done({
uri: uri,
error: err
});
}
req.onload = function() {
return (req.status != 200) ? req.onerror(req.statusText) : done(run(req.responseText));
};
req.send();

Spring mvc check if was BindingResult in javascript response

Is there a clear way to check if ajax success response controller returned view with validation errors?
controler:
if(result.hasErrors()) {
return "place/add";
}
javascript:
$.ajax({
url : "<spring:url value="/place/add"/>",
type : 'POST',
data : $("#newPlaceForm").serialize(),
success : function(response) {
How do I check if the response has no validation messages?
It's more clear to generate a HTTP response code to indicate the error.
For example: response.sendError(400, "Validation failed")
jQuery will execute the provided error handler based on the response code.
$.ajax( '/your/url').error(function (jqXHR) {
if (jqXHR.status == 400) {
console.log('Bad Request');
}
});
This is more clear since handling errors in a success handler doesn't make much sense. The failed request is also easier to debug with your browsers developer tools.
success : function(response){
if(response.status == "SUCCESS"){
// success code
}else{
// show validation errors
errorInfo = "";
for(var i =0 ; i < response.result.length ; i++){
errorInfo += "<br>" + (i + 1) +". " + response.result[i].code;
}
$('#errorId').html("Please correct following errors: " + errorInfo);
}, error: function(e){
alert('Error: ' + e);
}
I ended up with:
success : function(response) {
try {
var status = $.parseJSON(response);
if (status.status = 'OK') {
alertify.success("Akcja wykonana pomyślnie");
$("#newPlaceForm").hide();
$("#spotPlaces").show();
}
} catch (e) {
$("#newLocationBox").html(response);
}
}
and it seems clear for me, I dont't have to search for errors in html code, if everything goes Ok I just return in controller view which only has ${status} field and I add attribute status as stringified Json model.addAttribute("status", "{\"status\": \"OK\"}");

Resources