Rendering JSON object to AJAX calls in grails - javascript

I am trying to auto-populate employee details on entering employee number.
In the controller I am calling a method that returns JSON object:
Gson gson = new Gson();
System.out.println(gson.toJson(objEmp));
return gson.toJson(objEmp);
In the controller I am returning to AJAX call as:
render(contentType: "application/json") {[data]}
AJAX call is as follows:
$(document).keypress(function(e) {
if(e.which == 13){
var URL="${createLink(controller:'employeeAdd',action:'getDetails')}";
var empNo = $("#empNo").val();
alert("empNo: " + empNo);
$.ajax({
type: "GET",
url:URL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
empNo:empNo
},
success: function (data) {
$("#empNo").val(data.employeeNumber);
$("#employeeName").val(data.employeeName);
},
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;
}
},
});
};
});
I am not getting any error. Also nothing is auto populated even though data is present in JSON format. I am new to JSON and AJAX calls. I tried codes from internet still I couldn't get the desired output. I am unable to find the error. Any pointers will be of great help. Thank you.

I made the following changes and the code worked:
Returned employee object from method.
Rendered the object as JSON ==> render dataEmp as JSON
Extracted data in AJAX call funtion ==> success: function (dataEmp)

Related

Ajax result always returns error even if function is successful

I have an Ajax function that looks like this
$.ajax({
type: "POST",
url: "#IGT.baseUrl/SODetailsAjax/AddUnits",
traditional: true,
data: {
__RequestVerificationToken: token,
so_id: #Int32.Parse(Request["orderId"]),
site_id: site,
addItem_id: items,
addItem_qty: itemsqty,
addItem_disc: itemsdisc,
addComp_id: comps,
addComp_qty: compsqty,
addComp_disc: compsdisc,
addPart_id: parts,
addPart_qty: partsqty,
addPart_disc: partsdisc
},
success: function (data) {
if(data.success === "False"){
var errorMessage = data.Message;
alert("Error:" + errorMessage);
return;
}
if(data.success === "True"){
location.href = "../SalesOrders/Details?id=#so.ID";
}
},
error: function (jqXHR, status, error) {
alert("Error:" + error);
}
});
And I have a JSON ActionResult method that does this in it.
if (!canCreate)
{
var errorMessage = string.Join(",", errors);
var stock = new { success = "False", Message = errorMessage };
return Json(stock, JsonRequestBehavior.AllowGet);
}
else
{
var result = new { success = "True" };
return Json(result, JsonRequestBehavior.AllowGet);
}
But everytime Success is true it returns an error message saying "Error:Not defined" when I click "OK" it proceeds. But how can I make it so it just proceeds instead of sending an error message?
You have a couple of errors. In your if (data.Success = "false") statement, this is not a condition. This is an assignment. You should do if (data.success === "false") this would check for the condition. Also note that "success" is all lower case because it's converted to Json. You also need to note that "False" does not equal "false" so you must pick a casing. Either do "False"/"True" in both c# and JavaScript or "false"/"true".

Sending data through controller, in mvc pattern using ajax

Using knockout I am trying to send data, from my UI to the controller. This is the javascript used to send my ajax request(PUT)
var model = new Object();
model.StudentID = "";
model.ActiveProgram = "";
model.ProgramDesc = self.programData();
model.Cohorts = self.associationData();
model.LoadIntent = self.loadIntentData();
model.Francophone = self.frenchData();
model.Gender = self.genderData();
$.ajax({
url: putStudentRegRequirementsUrl,
type: "PUT",
contentType: jsonContentType,
dataType: "json",
data: JSON.stringify(model),
//jsonData:model,
success: function (data) {
$('#notificationHost').notificationCenter('addNotification', { message: "Updated.", type: "info" });
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status != 0)
{
$('#notificationHost').notificationCenter('addNotification', { message: "Unable to update registration requirement.", type: "error"});
}
}
});
But when I debug it to see my controller, the string comming in is blank. This is my controller
[HttpPut]
public async Task<JsonResult> UpdateRegistrationRequirementAsync(string regRequirementJson)
{
try
{
var regRequirementModel = JsonConvert.DeserializeObject<RegistrationRequirement>(regRequirementJson);
var response = await ServiceClient.L09PutRegistrationRequirementAsync(CurrentUser.PersonId, regRequirementModel);
return Json(response);
}
catch( Exception ex)
{
Logger.Debug(ex, "Error updating Registration Requirement for user failed.");
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Error updating Registration Requirement.");
}
}
Action will parse parameters from client by its name, so you need to pass parameter with name regRequirementJson contains your json. So change this line
data: JSON.stringify(model)
to
data: { regRequirementJson: JSON.stringify(model) }
and remove contentType: jsonContentType.
Or you can try another way. Since ASP.NET can deserialize json by itself you can keep your js code as is and update your controller to
[HttpPut]
public async Task<JsonResult> UpdateRegistrationRequirementAsync(RegistrationRequirement regRequirementModel )
{
try
{
var response = await ServiceClient.L09PutRegistrationRequirementAsync(CurrentUser.PersonId, regRequirementModel);
return Json(response);
}
catch( Exception ex)
{
Logger.Debug(ex, "Error updating Registration Requirement for user failed.");
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Error updating Registration Requirement.");
}
Since you are sending a "RegistrationRequirement" object then in your controller you can do it this way :
[HttpPut]
public async Task<JsonResult> UpdateRegistrationRequirementAsync(RegistrationRequirement registrationRequirement)
{
try
{
var response = await ServiceClient.L09PutRegistrationRequirementAsync(CurrentUser.PersonId, registrationRequirement);
return Json(response);
}
catch( Exception ex)
{
Logger.Debug(ex, "Error updating Registration Requirement for user failed.");
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Error updating Registration Requirement.");
}
}

ajax can't going into success method

here is controller:
#ResponseBody
#PostMapping("/signup")
public String signUp(HttpServletRequest request) {
try {
log.info("-------signup page");
String username = request.getParameter(Constant.PARAMETER_USERNAME);
if (userDetailService.findByUsername(username)!=null) {
log.error("----------username is exist!!");
return Constant.MESS_EXIST_USER;
}
log.info("----------username is not exist!!");
User user = new User();
user.setUsername(username);
user.setPassword(passwordEncoder.encode(request.getParameter(Constant.PARAMETER_PASSWORD)));
user.setEmail(request.getParameter(Constant.PARAMETER_EMAIL));
user.setPhonenumber(request.getParameter(Constant.PARAMETER_PHONE)) ;
user.setAddress(request.getParameter(Constant.PARAMETER_ADDRESS));
user.setFullname(request.getParameter(Constant.PARAMETER_FULLNAME));
String status = userService.save(user);
log.info(status );
return status;// return "success" or "fail"
}
}catch (Exception e) {
log.error("sign up has been error: ",e);
return Constant.MESS_FAIL; // "fail"
}
}
and js:
var data = $('form#form1').serialize();
$.ajax({
url: '/signup',
data: data,
type: "POST",
datatype : "text",
success: function(data){
console.log(data);
if(data == "success"){
alert("signup success!");
window.location.href = "/index";
}else if(data=="existUser"){
alert("username is exist!");
window.location.href = "/index";
}
else if(data=="fail"){
alert("signup fail!");
window.location.href = "/index";
}
}
});
}
log of save(user) is success but ajax not alert("signup success!"), it show error page. When I debug in js and java, ajax worked and show alert("signup success!"). I try search in google but it can't run. Anyone help me :(
EDIT
I try use datatype = 'text' and not dublicate save(user). When I run it then seem it not going into success function but when i debug in js then my program is running normally :(

Upload files using ajax and jquery is returning network error for SOME files

I made a complete javascript function using jquery and ajax to upload files ... Everything is working perfectly untill I realized that for some files the error function is fired in ajax instead of success function. Below is my code:
$.ajax({
url: 'MyService.asmx/UploadFiles',
type: "POST",
contentType: false,
processData: false,
data: fileData, // form data that contains file and some data
dataType: "text",
success: function (response) {
...
}
error: function (jqXHR, exception) {
//alert(jqXHR.status);
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);
}
});
The error thrown is "Not connect.\n Verify Network".
I have searched for this error I found that it is thrown when service is not reachable or when cross-site scripting (access is denied) ... The weird thing is that some files are uploaded successfully, others are not, which means service is reachable and access is not denied ... And concerning file types, they are all docs files with max size of 5 MB, whenever I delete everything inside the file that could not be uploaded and I try again to upload: function succeeds... So why some file are uploaded successfully and others are not? How can I resolve my problem in order to be able to upload all files?
Update
I am firing the upload function in onchange event:
<input type="file" class="HideFile" onchange="UploadFilesnew();" onclick="resetInput(this)" id="UploadFilenew" /> ;
My input is inside an asp:UpdatePanel in a .aspx page, so no forms and actions
Please add the following code in web.config. And try again. I think sometimes the request fails due to the size of the file.
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>

Change ajax data on retry

Is there a way to change the supplied data on an ajax retry? I want to make the first call with user="auth" passed in the data params , if it fails then change the user to "ANON" and retry the call this new data param. The user shows up as undefined with the way I have it set up below.
$.ajax({
url : proxyurl,
type : 'GET',
dataType : 'xml',
user : "auth",
tryCount : 0,
retryMax : 2,
data : {'apireq': apiurl+"?user="+this.user},
success : function(data){
},
error: function(xhr,textStatus,errorThrown){
if (textStatus == 'parsererror') {
this.user = "ANON";
this.tryCount++;
if (this.tryCount <= this.retryMax) {
$.ajax(this) //try the call again
return;
}
return;
}
}
});
We were able to reach the following solution:
error: function(xhr,textStatus,errorThrown){
if (textStatus == 'parsererror') {
this.user = "ANON";
this.data = {'apireq': apiurl + "?user=" + this.user };
this.tryCount++;
if(this.tryCount <= this.retryMax) {
$.ajax(this); //try the call again
return;
}
return;
}
}

Categories

Resources