Make an AJAX request from my phonegap app to servlet - ajax

I am trying to make an AJAX request from my phonegap app to a servlet running on my laptop.
It's hitting the server but the AJAX request is always going to error part. If I do the same request in a normal browser, it works fine.
\nfunction cred() {
var username = "hisari";
var password = "kumar";
var ul = "ip ; $.ajax({
type: "GET",
url: ul,
dataType: "json",
success: function(msg, textstatus) {
alert("success");
if (msg.id != null) {
}
else if (msg.error_id) {
//Error
alert('Error logging in:' + msg.error_message);
}
},
error: function(error) {
alert("Error connecting to the servers" + error.message);
}
});
}
Could you suggest what I can use instead of servlet for login validation?

Related

Ajax request fails in Cordova application Visual studio

I am Using visual studio 2015 to build android application using cordova. It works fine in the emulator. but when i am releasing it ajax request is failing where as same thing works on emulator.no error is seen in log but only the ajax error.
var url = 'http://oployeelabs.net/demo/demo_doctorola/doctorola-server/index.php/doctor_panel_api/validation_modified/format/json';
load();
$.ajax({
url: url,
data: { cell_no: phone, pass: pass },
method: 'POST',
dataType: 'json',
success: function (data) {
alert();
if (data == "false")
{
alert("Wrong password");
}
else
{
localStorage.doctorid = data[0].id;
localStorage.userinfo = JSON.stringify(data);
$.ajax({
url: "http://oployeelabs.net/demo/demo_doctorola/doctorola-server/index.php/api/information/meta-info/location/id/"+data[0].id+"/username/9791a47fef07649b1c3e70749e898153/password/2d593e25d0560b19fd84704f0bd24049/format/json",
method: 'GET',
dataType: 'json',
success: function (dt) {
localStorage.Chamberinfo = JSON.stringify(dt);
mainView.router.loadPage({ url: 'menu.html', ignoreCache: true, reload: true })
$('.toolbar').removeClass('hide');
}
});
}
//if (data === "ok") {
// $(".confirm_appointment").remove();
// var anc = "<a id='confirm_appointment' class='confirm_appointment' style='opacity: 0;' href='confirm.html' data-context='{\"slot_id\": \"" + slot_id + "\",\"slot_date\": \"" + slot_date + "\", \"email\": \"contact#john.doe\"}'>profile</a>";
// $(document).find('.page_content').append(anc);
// $(".confirm_appointment")[0].click();
//}
//else {
// myApp.hidePreloader();
// myApp.alert("", "Sorry, this slot has been booked. Please try with another slot.");
//}
},
error: function (xhr, status, exception) {
alert(xhr.responseText+" "+status+" "+ exception);
console.log("Error: " + xhr.responseText + " - " + exception);
},
complete: function () {
myApp.hidePreloader();
unload();
}
});
Strangely it worked after i uninstalled whitelist plugin and installed it again. i dont know why but i think its a bug of cordova.

RestFul PhoneGap and RestFul webservices

How to connect restful Web Services + phone gap. please give and sample demo.
Try this sample
$.ajax({
url: Your_webservice_url,
type: "GET",
data: {
ModifiedSince: modifiedSince
},
dataType: "json",
success: function(data) {
console.log("The server returned " + data.length);
//Play with the received json data.
},
error: function(model, response) {
alert("Web service error: " + response.responseText);
}
});
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data){
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});

Facebook wall post using ajax post request inconsistent with Chrome and IE

I am using the posted code for posting content to a Facebook wall.
FB.init({ appId: 'my app id', status: true, cookie: true, xfbml: true, oauth: true })
$('#share_button').click(function (e) {
if ($('#textfield').val() != 'Whats Happening' && $('#textfield').val() != '') {
var lin = window.location.href;
FB.login(function (response) {
if (response.authResponse) {
console.log("User is connected to the application.");
var accessToken = response.authResponse.accessToken;
var fbURL = "https://graph.facebook.com/me/feed?access_token=" + accessToken;
$.ajax({
url: fbURL,
data: "message=" + $('#textfield').val() + "&picture=MyUrl/images/logo.png&name=FutureZoom&link=MyUrl",
type: 'POST',
success: function (resp) {
$('#ValidationMessage').html(' Post has been shared on your wall!')
.css('color', 'green');
setTimeout(function () {
$('#ValidationMessage').html('');
}, 3000);
},
error: function (request, status, error) {
alert("Facebook Error : \n" + request.responseText + '\n' + status + '\n' + error);
}
});
}
}, { scope: 'publish_stream' });
}
else {
$('#ValidationMessage').html(' Please write something to share!')
.addClass('red');
}
});
Above is working fine in Firefox browser but problem is with IE and Chrome.
In Chrome, above code posts the comment on wall but when returns, it goes into error block instead of success. Below is the error getting in chrome.
Facebook Error:
{
"id": "100002506055900_30229318964214"
}
parseerror
SyntaxError: Unexpected token:
And in IE, nothing happens. Neither posts the comment nor returns in error/success block.
What could be reason?
Instead of doing a AJAX call to post something to the user's timeline, you should use the FB.api function in the Facebook JavaScript SDK instead. It simplifies the process:
FB.api('/me/feed', 'post', { message: body, picture: pic }, function(response) {
if ( !response || response.error ) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
You can see the documentation for the JS call here: http://developers.facebook.com/docs/reference/javascript/FB.api/
You will be able to reduce your code quite a bit by using this method.

Can I return custom error from JsonResult to jQuery ajax error method?

How can I pass custom error information from an ASP.NET MVC3 JsonResult method to the error (or success or complete, if need be) function of jQuery.ajax()? Ideally I'd like to be able to:
Still throw the error on the server (this is used for logging)
Retrieve custom information about the error on the client
Here is a basic version of my code:
Controller JsonResult method
public JsonResult DoStuff(string argString)
{
string errorInfo = "";
try
{
DoOtherStuff(argString);
}
catch(Exception e)
{
errorInfo = "Failed to call DoOtherStuff()";
//Edit HTTP Response here to include 'errorInfo' ?
throw e;
}
return Json(true);
}
JavaScript
$.ajax({
type: "POST",
url: "../MyController/DoStuff",
data: {argString: "arg string"},
dataType: "json",
traditional: true,
success: function(data, statusCode, xhr){
if (data === true)
//Success handling
else
//Error handling here? But error still needs to be thrown on server...
},
error: function(xhr, errorType, exception) {
//Here 'exception' is 'Internal Server Error'
//Haven't had luck editing the Response on the server to pass something here
}
});
Things I've tried (that didn't work out):
Returning error info from catch block
This works, but the exception can't be thrown
Editing HTTP response in catch block
Then inspected xhr in the jQuery error handler
xhr.getResponseHeader(), etc. contained the default ASP.NET error page, but none of my information
I think this may be possible, but I just did it wrong?
You could write a custom error filter:
public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new
{
// obviously here you could include whatever information you want about the exception
// for example if you have some custom exceptions you could test
// the type of the actual exception and extract additional data
// For the sake of simplicity let's suppose that we want to
// send only the exception message to the client
errorMessage = filterContext.Exception.Message
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}
and then register it either as a global filter or only apply to particular controllers/actions that you intend to invoke with AJAX.
And on the client:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
},
error: function(xhr) {
try {
// a try/catch is recommended as the error handler
// could occur in many events and there might not be
// a JSON response from the server
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch(e) {
alert('something bad happened');
}
}
});
Obviously you could be quickly bored to write repetitive error handling code for each AJAX request so it would be better to write it once for all AJAX requests on your page:
$(document).ajaxError(function (evt, xhr) {
try {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch (e) {
alert('something bad happened');
}
});
and then:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
}
});
Another possibility is to adapt a global exception handler I presented so that inside the ErrorController you check if it was an AJAX request and simply return the exception details as JSON.
The advice above wouldn't work on IIS for remote clients. They will receive a standard error page like 500.htm instead of a response with a message.
You have to use customError mode in web.config, or add
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
or
"You can also go into IIS manager --> Error Pages then click on the
right on "Edit feature settings..." And set the option to "Detailed
errors" then it will be your application that process the error and
not IIS."
you can return JsonResult with error and track the status at javascript side to show error message :
JsonResult jsonOutput = null;
try
{
// do Stuff
}
catch
{
jsonOutput = Json(
new
{
reply = new
{
status = "Failed",
message = "Custom message "
}
});
}
return jsonOutput ;
My MVC project wasn't returning any error message (custom or otherwise).
I found that this worked well for me:
$.ajax({
url: '/SomePath/Create',
data: JSON.stringify(salesmain),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
alert("start JSON");
if (result.Success == "1") {
window.location.href = "/SomePath/index";
}
else {
alert(result.ex);
}
alert("end JSON");
},
error: function (xhr) {
alert(xhr.responseText);
}
//error: AjaxFailed
});
Showing the xhr.responseText resulted in a very detailed HTML formatted alert message.
If for some reason you can't send a server error. Here's an option that you can do.
server side
var items = Newtonsoft.Json.JsonConvert.DeserializeObject<SubCat>(data); // Returning a parse object or complete object
if (!String.IsNullOrEmpty(items.OldName))
{
DataTable update = Access.update_SubCategories_ByBrand_andCategory_andLikeSubCategories_BY_PRODUCTNAME(items.OldName, items.Name, items.Description);
if(update.Rows.Count > 0)
{
List<errors> errors_ = new List<errors>();
errors_.Add(new errors(update.Rows[0]["ErrorMessage"].ToString(), "Duplicate Field", true));
return Newtonsoft.Json.JsonConvert.SerializeObject(errors_[0]); // returning a stringify object which equals a string | noncomplete object
}
}
return items;
client side
$.ajax({
method: 'POST',
url: `legacy.aspx/${place}`,
contentType: 'application/json',
data: JSON.stringify({data_}),
headers: {
'Accept': 'application/json, text/plain, *',
'Content-type': 'application/json',
'dataType': 'json'
},
success: function (data) {
if (typeof data.d === 'object') { //If data returns an object then its a success
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
})
Toast.fire({
type: 'success',
title: 'Information Saved Successfully'
})
editChange(place, data.d, data_);
} else { // If data returns a stringify object or string then it failed and run error
var myData = JSON.parse(data.d);
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
footer: `<a href='javascript:showError("${myData.errorMessage}", "${myData.type}", ${data_})'>Why do I have this issue?</a>`
})
}
},
error: function (error) { console.log("FAIL....================="); }
});

detect a 407 error and persist for all subsequent requests

I have a simple javascript that uses $.ajax() from JQuery which works great for GET/POST. However, for some users that are behind a proxy, they receive the 407 error as outlined in the post below.
407 Proxy Authentication Required
Now, as you will see, I've updated that post stating that the usage of JSONP will suffice as a workaround. Where I'm at now, is I don't want to use JSONP all the time, only when it is required.
function original() {
$.ajax({
url: "http://somecool.url/foo",
data: { id:"bar"},
statusCode: {
407: foo()
},
success: function(data) {
$.each(data, function(k,v) {
$('#foo').append("<li>" + k + ":" + v + "</li>");
});
}
});
}
function foo() {
$.ajax({
url: "http://somecool.url/foo",
data: { id:"bar" },
dataType: "jsonp",
success: function(data) {
$.each(data, function(k,v) {
$('#foo').append("<li>" + k + ":" + v + "</li>");
});
}
});
}
$(document).ready(function() {
original();
});
Is it possible to persist the status of the first failure, which returns the 407 error when there is a proxy issue so that all subsequent requests do not go to the original() function and go to the foo() function?
My original answer (below) was dealing with function name override to accommodate the code in your question. However, there's a better solution, since after all you only want to switch all requests to JSONP if and only if you receive a 407 response code.
$.ajaxSetup() was designed to do exactly that:
function original() {
$.ajax({
url: "http://somecool.url/foo",
data: { id:"bar"},
statusCode: {
407: function() {
$.ajaxSetup({ dataType: "jsonp" });
// Now all AJAX requests use JSONP, retry.
original();
}
},
success: function(data) {
$.each(data, function(k,v) {
$('#foo').append("<li>" + k + ":" + v + "</li>");
});
}
});
}
With this strategy, once 407 is received, all the future AJAX requests will use JSONP.
For the sake of history, here is my original answer.
You can permanently change the function stored in original when you receive a 407 response code for the first time:
function original() {
$.ajax({
url: "http://somecool.url/foo",
data: { id:"bar"},
statusCode: {
407: function() {
window.original = foo;
foo();
}
},
success: function(data) {
$.each(data, function(k,v) {
$('#foo').append("<li>" + k + ":" + v + "</li>");
});
}
});
}
From then on, the name original will refer to foo(). You can even change the function and call its replacement at the same time:
407: function() {
(window.original = foo)();
}

Resources