How to send boolean result to ajax call - ajax

I want to send Boolean result in ajax call.
Ajax call
function myMethod() {
$.ajax({
type : "GET",
url : myurl
dataType : "json",
contentType: "application/json",
crossDomain: true,
success : function(data) {
alert("success :"+data);
},
error : function(data) {
alert("Fialed to get the data");
}
});
}
Controller method from where I want to send Boolean result.
#RequestMapping(value = "/myMethod", method = RequestMethod.GET)
#ResponseBody
public boolean myMethod(empId) {
flag = false;
try {
if (empId != null)
newName = Employee.getName(empId);
else
newName = Employee.getName();
} catch (Exception e1) {
flag = true;
System.out.println("flag :" + flag);
e1.printStackTrace();
}
return flag;
}
i want to send the Boolean flag result to ajax call.
How do i send it. dont mind about the logic .. I just want to know how can i send boolean result to ajax call. Please help .

Ajax uses HTTP which is a text protocol and has no concept of booleans. However, you can return the strings "1" or "0" to represent your boolean values.
Then, in your "success" callback:
success : function ( data ) {
if ( data * 1 ) {
// true result
} else {
// false result
}
}

Without passing the Boolean value to the Ajax call, you can do some thing like this using a map. Using this map you can send anything rather than only limiting to Boolean values.
#RequestMapping(value = "/myMethod", method = RequestMethod.GET)
#ResponseBody
public Map<String, Object> myMethod(empId)
{
flag=false;
try {
if(empId != null)
newName = Employee.getName(empId);
else
newName = Employee.getName();
} catch (Exception e1) {
flag=true;
System.out.println("flag :"+flag);
e1.printStackTrace();
}
final Map<String, Object> map = new TreeMap<String, Object>();
map.put("flagdata", flag);
return map;
}
Then you can access this 'flagdata' object in the Ajax call.
Your Ajax code will be some thing like this.
$.ajax({
type : "GET",
url : myurl
dataType : "json",
contentType: "application/json",
crossDomain:true,
success : function(data) {
alert("success :"+data.flagdata);
},
error : function(data) {
alert("Fialed to get the data");
}
});
Hope it helps.!

Related

How return a empty JSON in Spring MVC?

I'm using ajax with GET method, I'm waiting receive a JSON but sometime the response is null and get the error:
SyntaxError: Unexpected end of JSON input
ajax:
$(document).ready(function() {
$("#form_data").submit(function(e) {
e.preventDefault()
var expediente = $('#expediente').val();
$.ajax({
url : 'buscarPaciente' + '?expediente=' + expediente,
dataType : "json",
type : "GET",
contentType : 'application/json',
mimeType : 'application/json',
success : function(data) {
console.log(data.nombre);
},
error : function(xhr, status, error) {
console.log(error)
}
});
})
});
in the controller:
#RequestMapping(value="/buscarPaciente", method = RequestMethod.GET)
public #ResponseBody MntPaciente
buscarPaciente(#RequestParam("expediente") String expediente) {
MntPaciente mntPaciente = servicePx.findByexpediente(expediente);
if (mntPaciente!= null) {
return mntPaciente;
}
return null; // Should I return an empty json? how?
}
There are several ways to do it. The first is to configure the JSON library that used to serialise JSON .In case of Jackson , you can use #JsonInclude to exclude all the empty properties not to serialise and just return an empty MntPaciente :
#JsonInclude(Include.NON_EMPTY)
public class MntPaciente {
}
public #ResponseBody MntPaciente buscarPaciente(#RequestParam("expediente") String expediente) {
....
return new MntPaciente();
}
To apply globally rather to configure for each object , you could use
ObjectMapper om = new ObjectMapper();
om.setSerializationInclusion(Include.NON_EMPTY);
The other way is to change the controller method to return ResponseEntity and directly return a empty JSON string :
public #ResponseBody ResponseEntity buscarPaciente(#RequestParam("expediente") String expediente) {
if (mntPaciente!= null) {
return ResponseEntity.of(mntPaciente);
}else{
return ResponseEntity.of("{}");
}
}

NullReferenceException showing for ValidateAntiForgeryToken in MVC 5

I'm trying to save data using ajax in MVC 5. When I'm posting form data without #Html.AntiForgeryToken(), it's working nicely. But it's showing me Object reference not set to an instance of an object error for using #Html.AntiForgeryToken(). Here is my ajax code:
$.ajax({
type: "POST",
url: "/Employees/Create",
data: data,
async: false,
success: function (result) {
if (result == 1) {
window.location.href = '/Employees';
}
else {
$('#error-span').html('Error in insert.');
}
},
error: function () {
alert('Failed');
}
});
Here is my controller method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Address,JoinDate,DoB,Gender,BloodGroup,Email,LastName,FirstName,Mobile,UpdateDate,UpdatedBy,Status,EmployeeType,CreatedBy,CreateDate,DesignationId")] EmpDetail empDetail)
{
try
{
Regex rgx = new Regex("[^a-zA-Z0-9 - .]");
empDetail.FirstName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(rgx.Replace(empDetail.FirstName, "").ToLower()).Trim();
empDetail.LastName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(rgx.Replace(empDetail.LastName, "").ToLower()).Trim();
empDetail.Email = empDetail.Email.ToLower().Trim();
empDetail.UpdateDate = DateTime.Now;
empDetail.CreatedBy = 234;
empDetail.CreateDate = DateTime.Now;
empDetail.UpdatedBy = 234;
empDetail.Status = 1;
if (ModelState.IsValid)
{
db.EmpDetails.Add(empDetail);
db.SaveChanges();
return Json(1);
}
else
{
return Json(2);
}
}
catch (Exception e)
{
return Json(e.Message);
}
}
This is happening because the data is being sent via JSON instead of HTML Form data. You should try to pass the token in the headers. For example:
View:
<script>
#functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
$.ajax("api/values", {
type: "post",
contentType: "application/json",
data: { }, // JSON data goes here
dataType: "json",
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
</script>
Controller:
void ValidateRequestHeader(HttpRequestMessage request)
{
string cookieToken = "";
string formToken = "";
IEnumerable<string> tokenHeaders;
if (request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
{
string[] tokens = tokenHeaders.First().Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken);
}
Source: https://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks

send data from ajax to spring controller

var form_data = {
itemid: globalSourceItem.substr(globalSourceItem.indexOf("-") + 1),
columnName: jqInputs[0].value,
displayName: jqInputs[1].value,
format: jqInputs[2].value,
KBE: jqInputs[3].value,
dgroup: jqInputs[4].value,
dupkey: jqInputs[5].value ,
measurement: jqInputs[6].value ,
times: new Date().getTime()
};
// console.log(form_data);
// console.log($("#tourl").html());
$.ajax({
url: $("#tourl").html(),
type: 'POST',
datatype: 'json',
data: form_data,
success: function(message) {
var j_obj = $.parseJSON(message);
// console.log(j_obj);return false;
if (j_obj.hasOwnProperty('success')) {
toastr.info('Item updated successfully');
setTimeout(function(){
window.location.reload();
},1000);
} else {
toastr.info('There was a problem.');
}
},
error: function(xhr, textStatus, errorThrown)
{
toastr.info('There seems to be a network problem. Please try again in some time.');
}
});
}
Hii friends , this code is working for php and i need to send the same data to the spring mvc through the ajax , can anyone please help me with the exact solution where to make changes as Iam struckup with the same doubt for like 2 weeks...
public class TestController {
#RequestMapping(value = "url", method = RequestMethod.POST)
public ModelAndView action(#RequestBody FormData formData) {
...
}
}
public class FormData {
private String itemid;
public String getItemid() {
return itemid;
}
public void setItemid(String itemid) {
this.itemid = itemid;
}
//...
}
Try sth like this. You should be able to map JSON Object to Java Object.
Maybe you could use annotation #ResponseBody and convert JSONObject to String:
#RequestMapping(value = "/ajax", method = RequestMethod.POST, produces="application/json")
#ResponseBody
public String ajax(#RequestBody ListDataDefinition listDataDefinition) {
System.out.println("id="+listDataDefinition.getItemid());
int i=SchemaDAOI.updateldd(listDataDefinition);
String message="success";
JSONObject obj = new JSONObject();
try {
obj.put("success", "success");
}
catch (JSONException e) {
e.printStackTrace();
}
if(i==1){
System.out.println("success");
}
else{
System.out.println("failure");
}
return obj.toString();
}
}
If you send String to View as ResponseBody and set produces as JSON it should be treated as pure JSON RQ.

how to send serialized form to webapi Method

im trying to send my from with ajax( $.post ) to a webApi . ajax request run succesfull but when i send data to method in web api form collection get null then my method return "false"
please help me
My WebApi Method
[System.Web.Http.HttpPost]
public string AddRecord([FromBody]FormCollection form)
{
try
{
PersonBLL personbll = new PersonBLL();
var person = new tbl_persons();
person.firstname = form["txt_namePartial"];
person.lastname = form["txt_lastnamePartial"];
person.age = byte.Parse(form["txt_agePartial"]);
var result = personbll.AddRecord(person);
return result;
}
catch (Exception)
{
return "false";
}
}
my Ajax function
function AddRecordWithFormCollection(url, callback) {
$.post("/api/Person/AddRecord",JSON.stringify(url) , function (data, status) {
if (status == "success") {
hidePreloader();
unloadDiv("div_operation");
BindTable();
//AddRowTable(data, obj.name, obj.lastname, obj.age);
return callback(data);
} else {
alert("Error in Method [AddRecord]");
hidePreloader();
}
});
}
I often use that :
var form = $("#body").find("form").serialize();
$.ajax({
type: 'POST'
url: "/api/Person/AddRecord",
data: form,
dataType: 'json',
success: function (data) {
// Do something
},
error: function (data) {
// Do something
}
});
Get a try because I never used the FormCollection object type but just a model class.
This should be:
url=$("#form").serialize();
function AddRecordWithFormCollection(url, callback) {
$.post("/api/Person/AddRecord",url , function (data, status) {
if (status == "success") {
hidePreloader();
unloadDiv("div_operation");
BindTable();
//AddRowTable(data, obj.name, obj.lastname, obj.age);
return callback(data);
} else {
alert("Error in Method [AddRecord]");
hidePreloader();
}
});
}

Ajax - mvc request always fails

I would like to hit an action in a controller from a view, have it return a result. However I always get a "request failed", then the action code in the controller executes. I am trying to use this in the view:
$("#State").change(function() {
if ($(this).val() != "Va") {
$.ajax({
url: '#Url.Action("ProcessOrder","Checkout")',
type: 'POST',
success: function(result) {
if(result.success) {
alert("good " + result);
} else {
alert("bad " + result);
}
},
error: function() {
alert("request failed");
}
});
} else {
formSwitcher($(this).val());
}
});
And this in the controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ProcessOrder()
{
string sURL = #"https://someUrl/?OrderId=" + Id ;
var badUrl = string.Empty;
try
{
Response.Redirect(sURL, true);
HttpWebRequest request = null;
HttpWebResponse httpWebResponse = null;
request = HttpWebRequest.Create(sURL) as HttpWebRequest;
request.Method = "GET"; // Supports POST too
httpWebResponse = (HttpWebResponse)request.GetResponse();
return Json(new { success = true });
}
catch (Exception ex)
{
badUrl = "~/Shared/error.aspx";
}
return Json(new { success = false, error = badUrl });
}
What am I doing wrong?
So the problem was Response.Redirect(sURL, true); was throwing an exception which was caught by ajax before it was caught in the try catch. The result was that the ajax said there was a failure, the code continued to run.

Resources