Ajax call not fetching data from model in cakephp - ajax

My ajax is getting called but it is not fetching data from the model, so validations are not happening.In controller data is not getting picked from model and consequently the success function is not capturing any data.
I am doing in the first name field in signup tab popup.
Here is the ajax call code
JS code, validation.js
var ajaxHandler = function() {
$.ajax({
method: 'post' ,
url : '/medicare/Users/validate_form' ,
params : {
field:$('#first_name').attr('id'),
value: $('#first_name').val()
} ,
success: function(data){
console.log("Successful");
} ,
error : function(e){
console.log(e) ;
}
}) ;
}
Controller action, validate_form
public function validate_form(){
if($this->RequestHandler->isAjax()){
$this->request->data['User'][$this->request['form']['field']] = $this->request['form']['value'];
$this->User->set($this->data);
if($this->User->validates()){
$this->autoRender = FALSE;
}
else{
$error = $this->validateErrors($this->User);
$this->set('error',$this->User->validationErrors[$this->request['data']['field']][0]);
}
}
}

There is no data sending on POST request because you wrote-
params: {
field:$('#first_name').attr('id'),
value: $('#first_name').val()
} ,
it should be as-
data : {
field:$('#first_name').attr('id'),
value: $('#first_name').val()
} ,

Related

ajax post not trapping errors, always trapping success

I have an ajax post method to ad new records to a database, the process itself works ok and my server side code traps errors (duplicate input, etc). When an eror happens, the ajax method doesnt 'see' it, the 'success' function is always called. This is my ajax post method
$.ajax({
url: '#Url.Action("Add", "Organisation")',
data: $form.serialize(),
async: true,
type: 'POST',
error: function (returnval) {
$form.parents('.bootbox').modal('hide');
bootbox.alert('There was an error saving this organisation : ' + returnval['responseText']);
},
success: function (returnval) {
// Hide the dialog
$form.parents('.bootbox').modal('hide');
bootbox.alert('New Organisation successfully added');
}
})
and the actionmethod on my controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Add(OrganisationEditCreateViewModel data)
{
InsertOrganisationRequest request = new InsertOrganisationRequest();
IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
var model = mapper.Map<OrganisationEditCreateViewModel, OrganisationDto>(data);
request.organisation = model;
var response = this._organisationService.InsertOrganisation(request);
if (response.isSuccess)
{
return Json(new { success = true, responseText = "New organisation added successfully" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { success = false, responseText = "Error adding new organisation : " + response.Message }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { success = false, responseText = "Error adding new organisation : Invalid input" }, JsonRequestBehavior.AllowGet);
}
so when I insert a duplicate record, the serverside code traps this and this branch of code is returned back to my ajax call
return Json(new { success = false, responseText = "Error adding new organisation : " + response.Message }, JsonRequestBehavior.AllowGet);
but the ajax call always calls this bit of code
success: function (returnval) {
// Hide the dialog
$form.parents('.bootbox').modal('hide');
bootbox.alert('New Organisation successfully added');
}
the error part never gets called, what am I doing wrong ?
Update your success method!
success: function (returnval)
{
if(returnval.success=true)
{
// Hide the dialog
$form.parents('.bootbox').modal('hide');
bootbox.alert('New Organisation successfully added');
}
if(returnval.success=false)
{
$form.parents('.bootbox').modal('hide');
bootbox.alert('There was an error saving this organisation : ' + returnval['responseText']);
}
}
hope helps!
You are not doing anything wrong.Actually your code is also working fine,the
reason is Success function always getting executing because your AJAX call successfully happening.
If AJAX call failed then only error function will get execute.
Example suppose if you gave Ajax attribute contentType wrong
ex:- contentType:'xyzfds';
in some scenario or may be because of any another ajax method attribute wrong value.So no need to worry about it.
If you want to display your error message then follow below approach it may help you.Thank You
success: function (returnval) {
if(returnval!=null){
if(returnval.success){
// Hide the dialog
$form.parents('.bootbox').modal('hide');
bootbox.alert('New Organisation successfully added');
}
if(returnval.success==false){
$form.parents('.bootbox').modal('hide');
bootbox.alert('There was an error saving this organisation : ' + returnval['responseText']);
}
}
}

how to fill field values using ajax in yii2?

I am using ajax in yii2.
How to fill fields without submit form. Without submitting the validation is working, but how to add field value.
In below code $this->name is my field name.
if($this->statusOk){
$this->name = "gana";
}else{
return $this->addError('branch_code', ' code can’t be found');
}
you can set your value in save function(in model) or before saving your model(in controller) ,and use custom validation just for validation.
Try this,custom ajax
$(document).ready(function () {
$("body").on("blur", "#id", function () {
var data = $("#nameField").val();
$.ajax({
url : "validURL",
type : "post",
data : {"sortcode":data},
success: function (response)
{
var json_obj = $.parseJSON(response);
if(json_obj.errorMessage) {
// do something
}else {
// do something
}

ajax - request error with status code 200

From client side, I wanna send some data to server and receive some <div> tags which responding from View (another controller).
My ajax code looks like this:
var sortTopic = function () {
var $list = [],
$address = '',
$formData = new FormData();
/* do something here to set value to $list and $address */
$formData.append('Category', $list);
$formData.append('Address', $address);
$formData.append('Tags', '[KM]');
$formData.append('Skip', 0);
$.ajax({
url: '/Topic/Sort',
type: 'POST',
data: $formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
if (!data.success) {
$('.jumbotron').html(data.ex);
} else {
$('.jumbotron').html(data);
}
},
error: function (xhr) {
alert(xhr.status); //xhr.status: 200
}
});
};
In TopicController, action Sort was:
[AllowAnonymous]
[HttpPost]
public ActionResult Sort(SortTopicViewModel model)
{
try
{
if (model.IsValidSortTopicModel())
{
return PartialView("../Home/_Timeline", new TopicMaster().Sort(model));
}
return Json(new { success = false, ex = "Invalid model." });
}
catch (Exception e) { return Json(new { success = false, ex = e.Message }); }
}
I'm sure that the model is valid and method new TopicMaster().Sort(model) was working fine (because I had put breakpoint to view the return data). And the partial view _Timeline is a partial view of HomeController.
My problem is: I don't understand why I get error with status code 200 in ajax:
error: function (xhr) {
alert(xhr.status); //xhr.status: 200
}
Can you explain to me?
Thank you!
as you told you receive <div> in response that is not json and you mention dataType:"json" in your ajax just remove it. this will solve your problem. error 200 occur when you did not get valid response which is you mention in ajax.
for mor information you can read it documentation

How to redirect to error page from onexception method instead of returning to jQuery/Ajax call in c# mvc

I'm trying to redirect to an Error page inside onexception method when an exception occurs. But the thing is I have Ajax function, so even if I redirect inside onexception class, it does not redirect to error page and it always end up with executing Ajax function. Please can anyone suggest a solution for this.
This is my controller method and when exception throws, it will call to base controller on exception method.
public ActionResult DeleteConfirmed(int id)
{
try
{
string displayMessage = string.Empty;
//Delete ward details and check successfulness of the function and return json result
if (wardManager.DeleteWard(id) == true)
{
displayMessage = CustomEnumMessage.GetStringValue(ConfirmationMessages.ConfirmationErrorMsg);
return Json(new { Message = displayMessage });
}
//Return json result if unsuccessfull
else
{
displayMessage = CustomEnumMessage.GetStringValue(ConfirmationMessages.ConfirmationRemovedMsg);
return Json(new { Message = displayMessage });
}
}
catch (System.Exception ex)
{
throw ex;
}
}
This is my base controller onexception method
protected override void OnException(ExceptionContext filterContext)
{
//Get exception type
System.Type ExceptionType = filterContext.Exception.GetType();
if (ExceptionType.Name == "DbUpdateException")
{
ViewData["ErrorMessage"] = filterContext.Exception.InnerException.Message;
this.View("DatabaseException", filterContext.Exception).ExecuteResult(this.ControllerContext);
}
else
{
ViewData["ErrorMessage"] = filterContext.Exception.Message;
this.View("ApplicationException", filterContext.Exception).ExecuteResult(this.ControllerContext);
}
}
This is my Ajax function
$.ajax({
type: "POST",
dataType: "json",
jsonpCallback: "onJSONPLoad",
url: '#Url.Action("Delete")',
data: $('#form').serialize(),
success: function (data) {
$('#submit').hide();
TriggerMsg(data.Message);
},
error: function (xhr) {
if (xhr.getResponseHeader('Content-Type').indexOf('application/json') > -1) {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
}
}
});
I built this Ajax function for only displaying Successful messages and it avoids me to redirecting to error page. The problem is even if i redirect to error page inside onexception method, finally fire into Ajax error: function and it does not redirect into DatabaseException or ApplicationException views. Can anyone suggest a solution for this issue.
Thanks
Your problem is that when you do a post from an ajax function, whatever result you have in your controller will always end up coming back to the success function.
What you want to do is return a url to your ajax function and from there redirect the user.
In your controller return the following
result = Json(new { redirect = Url.Action("ActionName", "ControllerName", new { area = "" }) });
Then in your javascript you will look for this redirect variable and set the window.location to it
success: function (data) {
if (data.redirect) {
window.location.href = data.redirect;
}
},
If you also want to pass a message then you can probably put it in the session such as Session["ErrorMessage"] = error from the controller and use it the same way in your error view

how to send an object from spring controller to jsp through Ajax

I have a transaction object and I am trying to send the object to the front page. I have no problem when I try to send a string, but I couldn't send an object.
So this is my controller:
#RequestMapping(value="/result/helloajax", method=RequestMethod.GET)
#ResponseBody
public MyTransaction helloahjax() {
System.out.println("hello Ajax");
MyTransaction tran = MyTransaction.getInstance();
tran.setId(123);
return tran;
}
#RequestMapping(value="/result", method=RequestMethod.GET)
public String show() {
return "result";
}
and this is my ajax call
button
<div class="result"></div>
function doajax() {
$.ajax({
type : 'GET',
url : '${pageContext.request.contextPath}/result/helloajax',
success : function(response) {
$('.result').html(response.id);
},
error: function() {
alert("asda");
}
});
};
I search around and see that other developers used "response.result.id" but I couldn't make it neither. Any suggestion please.
I would suggest to change your code like below.
1.Include JSON library to your classpath and add produces="application/json" attribute to RequestMapping for the helloahjax method.
#RequestMapping(value="/result/helloajax", method=RequestMethod.GET,produces="application/json")
2.Include dataType in your ajax call,like below
$.ajax({
type : 'GET',
dataType : 'json',
url : '${pageContext.request.contextPath}/result/helloajax',
success : function(response) {
var obj = JSON.parse(response);
//Now you can set data as you want
$('.result').html(obj.id);
},
error: function() {
alert("asda");
}
});
The URL would change to below when you are returning JSON from the controller method. In this case you don't need to parse the response. Instead you can directly access the object variables as response.abc
${pageContext.request.contextPath}/result/helloajax.json

Resources