Validation on onCellChange with Slickgrid - slickgrid

I have just started to use slickgrid (++ to the author btw) - running into a few small issues - I want to dynamically update some fields using the in-context editing. Once editing is done I wish to send this to the server which also should validate what was sent. If there is an error I would like to handle the error in a similar way to how the validatr event works? e.g. highlight the cell and not let the user to move away until it is valid, however I do not see how I can do so? any advice on this would be much appreciated!
Code so far...
grid.onCellChange.subscribe(function(e, args) {
var item = args.item;
var column = args.cell;
var row = args.row;
var value = data[args.row][grid.getColumns()[args.cell].field];
var id = args.item.id;
var field = grid.getColumns()[args.cell].field;
var dataString = "id="+id+"&field="+field+"&value="+value;
var status = false;
$.ajax({
type: "POST",
url: "/en/<?php echo $this->controller; ?>/updateattribute/&callback=?'",
data: dataString,
dataType: "json",
success: function(a) {
console.log(data);
if(a.status == true) {
status = true;
} else {
status = false;
}
return false;
}
});
if(!status) {
return false;
}
grid.invalidateRow(data.length);
data.push(item);
grid.updateRowCount();
grid.render();
});
Many thanks

Ajax requests are, by default, asynchronous, which means that
if(!status) {
return false;
}
grid.invalidateRow(data.length);
data.push(item);
grid.updateRowCount();
grid.render();
will probably be executed before the success callback. A couple different solutions:
Make the ajax request synchronous (not recommended):
$.ajax({ ... async: false, ...})
Put all of the code that follows the ajax request in the success or complete callback. Something like this (not tested):
grid.onCellChange.subscribe(function(e, args) {
// snip...
$.ajax({
type: "POST",
url: "/en/<?php echo $this->controller; ?>/updateattribute/&callback=?'",
data: dataString,
dataType: "json",
success: function(a) {
console.log(data);
if(a.status) {
grid.invalidateRow(data.length);
data.push(item);
grid.updateRowCount();
grid.render();
}
}
});
});
jQuery's deferred object can also provide a clean way to write this.

I would recommend one of two options:
Submit your change to the server for validation. Display a spinner to visually indicate that a background process is running and temporarily disable editing and cell navigation while the validation is going on. When you've received the response, re-enable the editing and navigation or switch the cell back into edit mode and display a validation error.
Same as above, but keep the navigation going, just disable the editing. Add an onBeforeCellEdit event handler to display a gentle message to the user informing them that a cell cannot be edited because the server hasn't responded yet and cancel the edit.

Related

Kendo Tooltip is empty

dI use a kendo tooltip on cells of a column of a kendo grid but the content of the tooltip is empty.
When I use the chrome debugger, values are correctly set but there is nothing in my tooltip.
$("#gri").kendoTooltip({
filter: "span.tooltip",
position: "right",
content: function (e) {
var tooltipHtml;
$.ajax({
url: ".." + appBaseUrl + "api/Infobulle?id=" + $(e.target[0]).attr("id"),
contentType: "application/json",
dataType: "json",
data: {},
type: "GET",
async: false
}).done(function (data) { // data.Result is a JSON object from the server with details for the row
if (!data.HasErrors) {
var result = data.Data;
tooltipHtml = "Identifiant : " + result.identifiant;
} else {
tooltipHtml = "Une erreur est survenue";
}
// set tooltip content here (done callback of the ajax req)
e.sender.content.html(tooltipHtml);
});
}
Any idea ? Why it is empty ?
After looking at the dev's answer on telerik forums, i found out that you need to do something like
content: function(){
var result = "";
$.ajax({url: "https://jsonplaceholder.typicode.com/todos/1", async:false , success: function(response){
result = response.title
}});
return result;
}
changing directly with e.sender.content.html() won't work, instead we have to return the value. And i tried several approach :
i tried mimick ajax call with setTimeOut, returning string inside it or using e.sender.content.html() wont work
i tried to use content.url ( the only minus i still don't know how to modify the response, i display the whole response)
the third one i tried to use the dev's answer from here
AND check my example in dojo for working example, hover over the third try

Ajax calls and JQuery: stop previuos ajax calls

In a jsp page, when a user clicks a button, an ajax call is triggered.
If the user clicks again and again the button, I would that only the last ajax call be valid and only its response be considered.
I use:
var lastRequest=null;
$('#button').click(function() {
if (lastRequest) {
lastRequest.abort();
lastRequest = null;
}
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
response= $('<div/>').append(response);
}
});
});
With Firebug, I see that some request are aborted, but not all.
I think that if an ajax call is triggered, it's not possible to ignore the response, is it?
EDIT
If I set a var in MyAction.do and I read it in the success callback, is it possible to have a conflict in the success callback?
In case, how could I prevent that behaviour?
My experience with aborting ajax-calls is that it can be pretty random when it works.
A workaround that I've used once or twice is counters:
var lastRequest=null;
var started = 0, finished = 0;
$('#button').click(function() {
++started;
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
//Only do stuff on the last active request
if(++finished == started)
response= $('<div/>').append(response);
}
});
});
use object.abort() to discard data that have been called by service
i have add the code as to click on a button to abort service you can try it with respect to your case :)
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
response= $('<div/>').append(response);
}
});
});
$(document).click(function() {lastRequest.abort() });

e.stopImmediatePropagation is not a function

This error is 9lesson.info site EDITDELETEPAGE template is
So This error is EDIT and DELETE functions have. error name is
e.stopImmediatePropagation is not a function
$(document).ready(function()
{
$(".delete").live('click',function()
{
var id = $(this).attr('id');
var b=$(this).parent().parent();
var dataString = 'id='+ id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "delete_ajax.php",
data: dataString,
cache: false,
success: function(e)
{
b.hide();
e.stopImmediatePropagation();
}
});
return false;
}
});
how to add add button please help me?
Possibly because you are using .live() to bind your events. From the jQuery documentation:
Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events.
Depending on which version of jQuery you are using, simply changing the live event handler to on (jQuery on) may fix the problem.

jQuery.ajax() sequential calls

Hey. I need some help with jQuery Ajax calls. In javascript I have to generste ajax calls to the controller, which retrieves a value from the model. I am then checking the value that is returned and making further ajax calls if necessary, say if the value reaches a particular threshold I can stop the ajax calls.
This requires ajax calls that need to be processes one after the other. I tried using async:false, but it freezes up the browser and any jQuery changes i make at the frontend are not reflected. Is there any way around this??
Thanks in advance.
You should make the next ajax call after the first one has finished like this for example:
function getResult(value) {
$.ajax({
url: 'server/url',
data: { value: value },
success: function(data) {
getResult(data.newValue);
}
});
}
I used array of steps and callback function to continue executing where async started. Works perfect for me.
var tasks = [];
for(i=0;i<20;i++){
tasks.push(i); //can be replaced with list of steps, url and so on
}
var current = 0;
function doAjax(callback) {
//check to make sure there are more requests to make
if (current < tasks.length -1 ) {
var uploadURL ="http://localhost/someSequentialToDo";
//and
var myData = tasks[current];
current++;
//make the AJAX request with the given data
$.ajax({
type: 'GET',
url : uploadURL,
data: {index: current},
dataType : 'json',
success : function (serverResponse) {
doAjax(callback);
}
});
}
else
{
callback();
console.log("this is end");
}
}
function sth(){
var datum = Date();
doAjax( function(){
console.log(datum); //displays time when ajax started
console.log(Date()); //when ajax finished
});
}
console.log("start");
sth();
In the success callback function, just make another $.ajax request if necessary. (Setting async: false causes the browser to run the request as the same thread as everything else; that's why it freezes up.)
Use a callback function, there are two: success and error.
From the jQuery ajax page:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// Do processing, call function for next ajax
}
});
A (very) simplified example:
function doAjax() {
// get url and parameters
var myurl = /* somethingsomething */;
$.ajax({
url: myurl,
context: document.body,
success: function(data){
if(data < threshold) {
doAjax();
}
}
});
}
Try using $.when() (available since 1.5) you can have a single callback that triggers once all calls are made, its cleaner and much more elegant. It ends up looking something like this:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
alert( jqXHR.responseText )
});

Proper jQuery technique to disable button with ajax post then re-enble button onComplete

I have a button that performs an ajax post -- I want to disable the button, then perform my work, then upon completion -- I want to re-enable the button. My interaction includes swapping out the image button (to a grayed out image button), and presenting a spinner. When complete, I hide the spinner and restore the original button image.
My approach includes unbinding, then rebinding the click event.
Here's my code -- it works great -- but, I want to know if this is a proper/efficient/acceptable strategy?
// Update club name
$j('#btnUpdateClubName').bind('click', updateClubName);
function updateClubName() {
var $this = $j(this);
var $spinner = $this.next('.spinner');
var renderURL = RES.BuildClubUpdateURL("UpdateClubName");
$this.ajaxStart(function() {
$this.attr("src", imgPathSaveAndUpdateBtnDisabled).unbind('click').addClass('wait-cursor');
$spinner.show();
});
$j.ajax({ type: "POST", data: $j('#hidStandingOrderId, #txtClubName, #clubOrderIdEditClubName').serialize(), url: renderURL, dataType: 'html', contentType: 'application/x-www-form-urlencoded',
success: function(data) {
// do some stuff
}
}
});
$this.ajaxComplete(function() {
$spinner.hide();
$this.attr("src", imgPathSaveAndUpdateBtn).bind('click', updateClubName).removeClass('wait-cursor');
$j("#cbEditClubName").colorbox.close();
});
}
What you have works but it is a bit wasteful, as it adds a new ajaxStart and ajaxComplete handler each time the function runs, I would make one suggestion though, change your .unbind() call to be more specific since you have the information. If you change this:
.unbind('click')
To this:
.unbind('click', updateClubName)
You can have other click events without the .unbind() interfering, it'll only unbind that one handler.
An overall better alternative (to me, you can debate whether it's "better") without rebinding would be to store a variable to know you're currently posting using $.data() and .data(), for example:
$j('#btnUpdateClubName').bind('click', updateClubName);
function updateClubName() {
if($.data(this, "posting")) return false; //are we posting? abort!
$.data(this, "posting", true); //set variable
var $this = $j(this);
var $spinner = $this.next('.spinner');
var renderURL = RES.BuildClubUpdateURL("UpdateClubName");
$this.attr("src", imgPathSaveAndUpdateBtnDisabled).addClass('wait-cursor');
$spinner.show();
$j.ajax({ type: "POST", data: $j('#hidStandingOrderId, #txtClubName, #clubOrderIdEditClubName').serialize(), url: renderURL, dataType: 'html', contentType: 'application/x-www-form-urlencoded',
success: function(data) {
// do some stuff
$spinner.hide();
$this.attr("src", imgPathSaveAndUpdateBtn).removeClass('wait-cursor')
.data("posting", false); //clear it out, ready to post again
$j("#cbEditClubName").colorbox.close();
}
});
}
With this approach if you're doing a POST the data for "posting" is true, and future clicks just abandon out...not until the response comes back and your success code runs is the button re-enabled. It's the same effect but no duplicate handlers and no re/un-binding.

Resources