Showing errors and messages on custom form in jqGrid - jqgrid

What I am trying to achieve it to show messages on a dialog form as asked and answered here. However, while the example above used the default editGridRow in the code, I have a custom dialog form loaded in via JSON. For example the JSON error/validation message returned could be:
{"CustomerName":{"isEmpty":"\u201cthis value is - not to be left empty.\u201d"}}
I need to be able to output them as "Customer Name - this value is not to be left empty" - at the top of the dialog form.
I have tried the solutions in A, B, C and D but I have not been able to customize them to work in my scenario yet.
I have a function call like so:
function LaunchEditForm(dialog)
{
$('form', dialog).submit(function ()
{
$.ajax({
url: '/customer/update-customer/',
type: this.method,
reloadAfterSubmit: true,
data: $(this).serialize(),
success: function (result)
{
if (result.success)
{
console.log(result);
//can I call a function here to prepend modal form
//with success message? how please?
}
else
{
console.log(result);
// can I prepend the dialog to show model errors here?
//var errorDetail = jQuery.parseJSON(result.responseText);
}
}
});
return false;
});
}
I have tried using afterSubmit like so:
afterSubmit: function (response, postdata)
{
if (response.responseText == "Success")
{
jQuery("#success").show();
jQuery("#success").html("Customer successfully updated");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else
{
return [false, response.responseText]
}
}
This has not worked yet - perhaps I have placed it in a different scope
and also tried errorTextFormat like so:
errorTextFormat: function (data)
{
if (data.responseText.substr(0, 6) == "<html ")
{
return jQuery(data.responseText).html();
}
else
{
return "Status: '" + data.statusText + "'. Error code: " + data.status;
}
}
Please help with this. I know I need some function that parses the JSON successfully and hopefully presents the errors and messages Oleg described

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']);
}
}
}

What is callback function in AJAX? How to implement a callback function in PreSaveAction function of SP2013 list NewForm?

I want to store the value of a variable and use it outside the ajax call. But being an asynchronous call it is giving me initial value of that variable. I am implementing my custom code for some validations in PreSaveAction function since I have to do validations on Save button click of SharePoint NewForm,Following is my code,
<script type="text/javascript">
var titleItem;
var flg=0;
var dataFromServer;
function PreSaveAction()
{
titleItem = $("input[title='Title']").val();
$.ajax({
url:"http://sp13dev:4149/Appraisals/_api/web/lists/GetByTitle('SkillMaster')/items?$select=Id,Title&$filter=Title eq '"+titleItem+"'" ,
type: "GET",
async: false,
headers: { "Accept": "application/json; odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val() },
success: function (data) {
if(data.d.results.length>=1)
{
flg=1;
$("#labelTitle").html("Skill already exists. Please enter another name.");
}
else
{
flg=0;
$("#labelTitle").html("");
}
},
error: function (error) {
alert(JSON.stringify(error));
}
});
if(flg==1)
{
// $("#labelTitle").html("Skill already exists. Please enter another name.");
return false;
}
return true;
}
</script>
It seems like you have misplaced your return call. You should have your return placed inside your
if(data.d.results.length>=1)
statement inside the success callback function.

Bind event after login

I have made a filter called auth that check if user is logged. If is not logged it redirect on the main page but if is a call ajax? I just checked if is it. If it is i just send an json status "no-log". Now i received my json response "no-log" on my client and i would like open a modal for ask login and password. The solution that i thougth was put easily for each ajax request an if statement to check if the response status is "no-log" and show the function of modal. BUT OF COURSE is not good for future update, I'm looking for a good solution where i can bind this event and if i want on the future add other status. Any suggest?
Route::filter('auth', function()
{
if (Auth::guest()) {
if ( !Request::ajax() ) {
Session::put('loginRedirect', Request::url());
return Redirect::to('/');
} else {
$status = "no-log";
return json_encode(array('status' => $status));
}
}
});
A example of call ajax
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
$.ajax({
type: "POST",
url: '/delete_post/' + USER,
data: { id_post: id_post.attr('id') },
beforeSend: function(request) {
return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content'));
},
success: function(response) {
if (response.status == "success") {
id_post.parents('div.shared_box').fadeOut();
}
},
error: function(){
alert('error ajax');
}
});
} else {
console.log("close");
}
});
});
After 10 days of exploring an idea I found a way to override ajax comportment:
It just need you replace every $.ajax() by a custom one.
If I re-use your code:
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
myCustomAjax({ // In place of $.ajax({
type: "POST",
...
Then this custom function allow you to add some action before or after each ajax callback:
For instance checking the JSON return value in order to decide if I trigger the success callback or I show a warning:
function myCustomAjax(options) {
var temporaryVariable = options.success;
options.success = function (data, textStatus, jqXHR) {
// Here you can check jqXHR.responseText which contain your JSON reponse.
// And do whatever you want
// If everithing is OK you can also decide to continue with the previous succeed callback
if (typeof temporaryVariable === 'function')
temporaryVariable(data, textStatus, jqXHR);
};
return $.ajax(options);
}
If you return a 401 for all not loggedin requests, you can use $.ajaxSetup to handle all ajax errors in your application.
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status == 401) {
window.location = 'your-login-page';
}
}
});

Smarty jQuery/Ajax call barrier

I'm modifying an existing system which uses Smarty. This particular problem is causing a major stumbling block as I just can't find a way around it.
I have a data-grid, each record has an action which calls ?module=the_module&action=the_action.
My corresponding function function the_module_the_action($postData, $getData) is used to perform the particular request.
The request for this module comes through from a jQuery $.ajax({}) request, simply because I don't want to loose the search form variables. So on success, I'll redirect the page using document.location='index.php?module=&action='.
This is fine as it allows me to detect that the action has been successful whilst maintaining the search filters on the grid.
But, I have a problem when the user action fails. The method the_module_the_action($postData, $getData) return echo 'success'; exit() on success but on a failure it should print out the Smarty template i.e. details of the record.
I believe the problem occurs because of a call through Ajax. The template is being served but because it is a call made using Ajax it isn't displayed.
How can I get around this problem?
Update:-
This is my function which Ajax calls:
public function module_action($post_data) {
$object=new Class((int)$post_data["id"]);
if($object->method()) {
echo "success";
exit();
}
else {
$this->assignToSmarty('_someSmartyVar', $someData);
$this->assignToSmarty('_data', $class->getData());
echo "failed";
}
}
The Ajax used to call this is:-
$(document).ready(function() {
$(".revokeButton").click(function(){
var selected=$(this).attr('id');
var filterBu = $('#filter_bu').val();
var filterJc = $('#filter_jc').val();
if(confirm("Are you sure you want to r.....")) {
$.ajax({
beforeSend: function() { },
url: 'index.php?module=module&action=action',
type: 'POST',
data: ({ bid:selected }),
cache: false,
success: function(data, textStatus) {
if(data == 'success') {
success_message = 'success';
} else if(data == 'failed') {
success_message = 'failed';
}
document.location='index.php?module=module&message='+success_message+'&filter_bu='+filterBu+'&filter_jc='+filterJc;
}
});
}
});
});
The success and failure are echoing out successfully, but the smarty stuff isn't.
I see two problems. First of all, you seem to have forgotten the smarty->display() function call in the failure leg of the module_action function. Secondly, you wrote:
if(data == 'success') {
success_message = 'success';
} else if(data == 'failed') {
success_message = 'failed';
}
This will always only output success or failure. You probably want to do something more like the following:
if(data == 'success') {
success_message = 'success';
} else {
// if got here, 'data' doesn't contain "success!", so it must contain
// something else, likely error data. You could either just display
// data as it is or first do some sort of check to ensure that it
// does, in fact, contain error data, and then display it.
success_message = 'error!<br \>\n' + data;
}

JQuery Validation Plugin: Use Custom Ajax Method

Looking for some assistance with the Jquery form validation plugin if possible.
I am validating the email field of my form on blur by making an ajax call to my database, which checks if the text in the email field is currently in the database.
// Check email validity on Blur
$('#sEmail').blur(function(){
// Grab Email From Form
var itemValue = $('#sEmail').val();
// Serialise data for ajax processing
var emailData = {
sEmail: itemValue
}
// Do Ajax Call
$.getJSON('http://localhost:8501/ems/trunk/www/cfcs/admin_user_service.cfc?method=getAdminUserEmail&returnFormat=json&queryformat=column', emailData, function(data){
if (data != false) {
var errorMessage = 'This email address has already been registered';
}
else {
var errorMessage = 'Good'
}
})
});
What I would like to do, is encorporate this call into the rules of my JQuery Validation Plugin...e.g
$("#setAdminUser").validate({
rules:{
sEmail: {
required: function(){
// Replicate my on blur ajax email call here
}
},
messages:{
sEmail: {
required: "this email already exists"
}
});
Wondering if there is anyway of achieving this? Many thanks
You are doing an AJAX request, ergo: the validation is already finished working when your custom validator returns either true or false.
You will need to work with async. See also this post: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
Lets say we have a custom validation to check the Unique Mobile, So we will add a new method as follows to check the unqiue Mobile no :
jQuery.validator.addMethod("uniqueMobile", function(value, element) {
var response;
$.ajax({
type: "POST",
url: <YOUR SERVER SCRIPT/METHOD>,
data:"mobile="+value,
async:false,
success:function(data){
response = data;
}
});
if(response == 0)
{
return true;
}
else if(response == 1)
{
return false;
}
else if(response == 'logout')
{
return false;
}
}, "Mobile is Already Taken");
You can add a custom validation method like this
$.validator.addMethod('unique',
function(value) {
$.get('http://localhost:8501/ems/trunk/www/cfcs/admin_user_service.cfc','?method=getAdminUserEmail&returnFormat=json&queryformat=column&emailData='+ value,
function(return_data) {
return return_data;
})
}
, "this email already exists"
);
then add the unique class to your email field or you can use something like this
$.validator.addClassRules("unique-email", {
unique: true
});
Try this:
$.validator.addMethod('unique',
function(value) {
var result = $.ajax({
async:false,
url:"http://yoursamedomain.com/checkemail",
data:'email='+ value,
dataType:"text" });
if(result .responseText) return true; else return false;
} , "This email address has already been registered");
For serverside AJAX validation use remote rule. This is same as standard jQuery AJAX request object. Your server must returns string "true" for valid value or "false" for invalid, also it can passes some string "This email was already taken", and this will be perceived as invalid, and render as an error message:
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $( "#username" ).val();
}
}
}
}
}
});
Read documentation here remote-method

Resources