jqGrid inline edit using successfunc - javascript

I have a grid that allows inline editing. Here is my onselect that handles it:
onSelectRow: function(id)
{
$('tr[id="'+id+'"]').change(function () {
saveparameters = {
"successfunc" : function(response) {
alert(response)
},
"url" : null,
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
}
$('#breakdownGrid').jqGrid('saveRow', id, saveparameters);
});
if(id && id!==lastsel)
{
editparameters = {
"keys" : false,
"oneditfunc" : null,
"successfunc" : null,
"url" : null,
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
}
$('#breakdownGrid').jqGrid('restoreRow',lastsel);
$('#breakdownGrid').jqGrid('editRow',id, editparameters); lastsel=id;
}
}
});
You can see that I have a change event on the tr that fires off and runs saveRow. This works fine without using the successfunc or if I just return true in the successfunc. I am trying to figure out how I can use the response from the server in the successfunc. I need to do an additional check on my editurl page. I am not sure what I need to send back from that page. I can do all the work on that page and send back a true or false but it's not working. I have the alert in there right now and it just displays [object object].
I have also tried sending back JSON and parsing it but I cannot get it to work.
Any help on this would be great.
Thanks!

Please try
alert(response.responseText);

Related

Case insensitive search in search2.js

I am using select2.js in my project for drop down functionality. By default behaviour this is case sensitive i.e tag and Tag will be consider different.
But as per my requirement i required result populate is case insensitive i.e. when writing tag or Tag both need to considered to be small like in capital. I have tried many solution for this but non of that seems to working. I need to deal this client side only.
Issue is like this "https://groups.google.com/forum/#!topic/select2/vk86jUMfJTk"
$('#Taging').select2({
tags : true,
tokenSeparators : [ ',' ],
createSearchChoice : function(term) {
return {
id : term,
text : term,
n : "new",
s : ""
};
},
ajax : {
},
// Take default tags from the input value
initSelection : function(element, callback) {
var data = [];
$(splitVal(element.val(), ",")).each(function() {
data.push({
id : this,
text : this
});
});
callback(data);
},
});
sample Code
I modified my code and that works
createSearchChoice : function(term,data) {
if (term.trim().length > 0) {
if ($(data).filter(function () {
return this.text.toLowerCase().localeCompare(term.toLowerCase()) === 0;
}).length === 0) {
return {
id: term,
text: term,
n : "new",
s : "",
isNew: true // this is necessary to check if the item is newly added or not
};
}
}
},

jQuery dataTables and selecting a row

I am trying to get a jQuery dataTable to behave in such a way that a user can select a row and then click a button (located elsewhere on the page, but not on the table or in it) and have a JS alert pop up.
Here is my dataTable:
$("#my-datatable").dataTable( {
"bProcessing" : true,
// Commenting out next line
//"sDom" : 't',
"sAjaxSource" : "some/url/on/my/server",
"sAjaxDataProp" : "",
"bDestroy" : true,
"fnServerData" : function(sSource, aoData, fnCallback) {
aoData.push({
"name" : "asking",
"value" : "yes"
});
request = $.ajax({
"dataType" : "json",
"type" : "GET",
"url" : sSource,
"data" : aoData,
"success" : fnCallback
});
},
"aoColumns" : [
{
"mDataProp" : "name"
},
{
"mDataProp" : "expr"
},
{
"mDataProp" : "seq"
}
]
});
Here is my button:
<div id="bam-btn-div">
<input type="button" id="bam-btn" value="BAM!" onclick="bam();"/>
</div>
When the user selects a row in the dataTable, and then clicks the button, I want the following function called:
function bam() {
alert("Deleting the selected row");
// Delete the selected row in the dataTable
}
Finally, the HTML table that the jQuery dataTable is attempting to populate:
<div id="datatable-div">
<table id="optconfig-datatable">
<thead>
<tr>
<th>Name</th>
<th>Expression</th>
<th>Sequence</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
I tried to follow the example here but couldn't get anything to work. Can anybody spot what configurations I need to add (to the dataTable and/or otherwise)? Thanks in advance!
You are using jQuery, you might as well stay on track.
$('#bam-btn').on('click', function(){
alert("BAM!");
});
On a side note, ID's must be unique, but I'm sure you know that, so make sure you're not trying to re-use the same ID over and over.
Moreover, if this element is added into the DOM after .ready() execution, you'll need to attach the event handler to a static parent element so it may delegate the click event properly.
$(document).on('click', '#bam-btn', function(){
alert("BAM");
});
I'll leave the above in place, I don't like to delete entire portions of my answer as you never know who may find it helpful in the future
First, we need to create a variable that's available to all scopes of all functions. This way, we can reference the variable to get a hold of the element we want to remove.
We should place this variable outside of the document ready function
var theRow = '';
$(document).ready(function(){
//existing code here
});
Now that we have a 'global scope' variable prepared, we can modify it and access it anytime.
var theRow = '';
$(document).ready(function(){
$('tr').click(function(){
//we need to store a unique piece of information about this row.
//Without much to go on, I'm going to rely on the index.
theRow = $(this).index();
});
$('#bam-btn').click(function(){
$('tr').eq(theRow).remove();
});
});​
And here is your decent working jsFiddle as an example
For future users, and anyone else whom may find this useful
The :eq() selector provided by jQuery cannot leverage .querySelectorAll() to gain a decently large performance boost. Because of this, and for the time being, you should always use .eq() over :eq().
Please check that your:
function bam() {
alert("BAM!");
}
Is not in this statement:
$(document).ready(function() {
// STATEMENT
});
If your function is in the $(document).ready(), that means it's available only in that scope, in that particular function().
Move your code above or below the $(document).ready() statement, and your onclick event handler in your button will be able to find it and invoke it.
To delete a specific element from your data-table, try with this JavaScript:
$(document).ready(function() {
var oTable = $("#my-datatable").dataTable( {
"bProcessing" : true,
// Commenting out next line
//"sDom" : 't',
"sAjaxSource" : "some/url/on/my/server",
"sAjaxDataProp" : "",
"bDestroy" : true,
"fnServerData" : function(sSource, aoData, fnCallback) {
aoData.push({
"name" : "asking",
"value" : "yes"
});
request = $.ajax({
"dataType" : "json",
"type" : "GET",
"url" : sSource,
"data" : aoData,
"success" : fnCallback
});
},
"aoColumns" : [
{
"mDataProp" : "name"
},
{
"mDataProp" : "expr"
},
{
"mDataProp" : "seq"
}
]
});$("#my-datatable").dataTable( {
"bProcessing" : true,
// Commenting out next line
//"sDom" : 't',
"sAjaxSource" : "some/url/on/my/server",
"sAjaxDataProp" : "",
"bDestroy" : true,
"fnServerData" : function(sSource, aoData, fnCallback) {
aoData.push({
"name" : "asking",
"value" : "yes"
});
request = $.ajax({
"dataType" : "json",
"type" : "GET",
"url" : sSource,
"data" : aoData,
"success" : fnCallback
});
},
"aoColumns" : [
{
"mDataProp" : "name"
},
{
"mDataProp" : "expr"
},
{
"mDataProp" : "seq"
}
]
});
$('button#bam-btn').on('click', function() {
var anSelected = fnGetSelected( oTable );
oTable.fnDeleteRow( anSelected[0] );
} );
});
I had a similar problem with a table with dynamic data load. Every time I was adding contents, the old nodes disappear, losing the events linked.
I solved the problem invoking a function after the data load:
function insertevents(table_id){
var oTable = jQuery('#'+tableid).dataTable( {"bRetrieve": true });
oTable.$('tr').click(function(){
jQuery(this).toggleClass('row_selected');
} );
// Extra code here
}
It's important to add the "bRetrieve" parameter because the table was previously initialized.
Also, I've improved the functionality controlling keyboard events for accessibility:
oTable.$('tr').keyup( function(event) {
if (event.which == 13 || event.which == 32) {
event.preventDefault();
jQuery(this).toggleClass('row_selected');
}
} );
oTable.$('tr').keydown( function(event) {
if (event.which == 13 || event.which == 32) {
event.preventDefault(); // Desactivamos este efecto
}
});
This bunch of lines should replace the comment line of the first example. Now the table can be used from the keyboard, selecting with intro or space key. Remember to add a tabindex=0 to the elements inserted in the table, so we can navigate with the tab key.
http://editor.datatables.net/release/DataTables/extras/Editor/examples/index.html
This is similar to what you want.

DataTables add column dynamically to table

I'm using DataTables (datatables.net) to display data from an Ajax source and having trouble customizing it. One thing I would like to do is add a column so I can have for example an 'edit' button for each row.
The closest thing to that in the examples is here but I can't get that to work with an ajax source.
Currently, I'm using the following code to display my table:
fnServerObjectToArray = function ( aElements ){
return function ( sSource, aoData, fnCallback ) {
$.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": function (json) {
var a = [];
for ( var i=0, iLen=json.aaData.length ; i<iLen ; i++ ) {
var inner = [];
for ( var j=0, jLen=aElements.length ; j<jLen ; j++ ) {
inner.push( json.aaData[i][aElements[j]] );
}
a.push( inner );
}
json.aaData = a;
fnCallback(json);
}
} );
}
}
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"sAjaxSource": 'get_data.php',
"fnServerData": fnServerObjectToArray( [ 'username', 'email' ] )
} );
});
Why don't you use fnRenderFunction in the aoColumns? As an example:
aoColumns: [ { "bVisible": false} , null, null, null, null,
{ "sName": "ID",
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj) {
return "<a href='EditData.php?id=" + oObj.aData[0] + "'>Edit</a>";
}
}
]
You can use it to format the value from the server side.
See similar example on the http://jquery-datatables-editable.googlecode.com/svn/trunk/ajax-inlinebuttons.html (ignore specific settings for the editable plugin)
I've created columns with edit button and links and so on, but usually i do everything server side by custominzg the data i return and then show/hide them with the aoColumns option. I don't really understand what you are tring to achieve: display server side data as a link?
Had the same problem a few months back. This is what I did.
By no means an elegant slution, but this worked.
As you might already know, DataTables do have an overload to accept Javascript Arrays.
So I made by $.ajax call. got my json, parsed it to a javascript array and then while parsing I created an extra element (an anchor tag) with href="edit.php?email=passed_email" Then on the column headers and added a column called Edit. Those values were fed to "aaData" and "aoColumns". And then the table was populated.
And BTW, if you looking for inline editing, check the following link.
DataTables editing example - with jEditableplugin
i have some RND on this problem and get this hope this will help you out.

Why does 'add files' button in Plupload not fire in latest Chrome or FF on OS X?

This is the code that is used to trigger Plupload in my Rails App:
<% content_for :deferred_js do %>
$("#uploader").pluploadQueue({
runtimes : 'gears,html5,flash,browserplus,silverlight,html4',
url : '/uploads.js',
//browse_button : 'pickfiles',
max_file_size : '10mb',
chunk_size : '2mb',
unique_names : false,
container: 'uploader',
autostart: true,
//RoR - make sure form is multipart
//multipart: true,
// Specify what files to browse for
filters : [
{title : "Image files", extensions : "jpg,gif,png,bmp"}
],
// PreInit events, bound before any internal events
preinit : {
UploadFile: function(up, file) {
up.settings.multipart_params = {"upload[stage_id]" : compv.steps.selectedStage.getID(), "authenticity_token" : compv.tools.csrf_token()};
}
},
// Post init events, bound after the internal events
init : {
FilesAdded: function(up, files) {
// Called when files are added to queue
up.start();
},
FileUploaded: function(up, file, info) {
// Called when a file has finished uploading
console.log('[FileUploaded] File:', file, "Info:", info);
info.responseText = info.response;
compv.updateStepView('upload', info);
$('tr[data-upload] td.selectable-step').each(function(index){
compv.steps.selectedUpload.primeUploadDisplay($(this));
});
},
Error: function(up, args) {
// Called when an error has occured
up.stop();
compv.tools.clientError();
}
},
// Flash settings
flash_swf_url : '/plupload/js/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url : '/plupload/js/plupload.silverlight.xap'
});
compv.steps.selectedUpload.uploader = $('div#uploader').pluploadQueue();
//compv.steps.selectedUpload.uploader.init();
// Client side form validation
$('form#new_upload').submit(function(e) {
var uploader = $('#uploader').pluploadQueue();
// Validate number of uploaded files
if (uploader.total.uploaded == 0) {
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('UploadProgress', function() {
if (uploader.total.uploaded == uploader.files.length)
$('form').submit();
});
uploader.start();
} else
$('div#upload-empty-dialog').dialog("open");
e.preventDefault();
}
});
$('div#upload-empty-dialog').dialog({modal:true, autoOpen: false, minWidth: 325, buttons: { "Ok": function() { $(this).dialog("close"); } }});
$('div#upload-cancel-dialog').dialog({modal:true, autoOpen: false, minWidth: 325});
<% end %>
<div class="dialog" id="upload-empty-dialog" title="No Files">
<p>You must select files to upload first.</p>
</div>
<div class="dialog" id="upload-cancel-dialog" title="Cancel Uploading?">
<p>Do you want to stop uploading these images? Any images which have not been uploaded will be lost.</p>
</div>
Is there anything obvious that jumps out that could be causing this ?
Edit1: Btw, when I try this upload form - http://jsfiddle.net/Atpgu/1/ - the add files button fires for me on both Chrome & FF - so I suspect it has something to do with my JS, I just don't know what.
Edit2: This is what the definition of compv is. I know it's a bit verbose, and I was going to reduce it - but decided not to at the risk of removing something important.
var compv = {
exists: true,
tools: { exists: true,
csrf_param : null,
csrf_token : null},
comments: { exists: true,
updateView: null,
selectImage: null,
upvote:null,
downvote:null,
showVotes:null,
getUploadID: function(element){
return $(element).parents("li").attr("data-upload-id");
}},
steps: { exists: true,
selectFn:{},
selectedClass: "selected-step",
selectableClass: "selectable-step",
selectedClient: { element: null,
id: null,
stepType: "client",
ajaxSuccess: null },
selectedProject: { element: null,
id: null,
stepType: "project",
ajaxSuccess: null },
selectedStage: { element: null,
id: null,
stepType: "stage",
ajaxSuccess: null,
getID: function(){
return compv.steps.selectedStage.id;
},
displayCompare: function(){
window.open($(this).attr('data-url'), "_blank");
}},
selectedUpload: { element: null,
id: null,
stepType: "image",
primeUploadDisplay: null,
ajaxSuccess: null,
uploader: null,
noCloseDialog: false} }
};
Plupload is not rendering correctly for hidden elements, that is why it should be refreshed after shown.
In given example, after DIALOG is opened, there should be added few lines of code:
var uploader = $('#uploader').pluploadQueue();
uploader.refresh();
I noticed, that in chrome, it has problems to set z-index correctly for input container. To workaround that, just add another line after previous two:
$('#uploader > div.plupload').css('z-index','99999');
You can solve this problem with Chrome easier by setting the css of your browse_button (= Select Files Button) to a higher z-index (z-index:99999) !
Lucian
I know this is an old question but it seems that the z-index issue is still around in the later versions of plupload (1.5.2).
The problem is caused by code in plupload.html5.js which changes the z-index of the "Add Files" button specifically for Webkit browsers and in doing so breaks things:
zIndex = parseInt(plupload.getStyle(browseButton, 'z-index'), 10);
if (isNaN(zIndex)) {
zIndex = 0;
}
plupload.extend(browseButton.style, {
zIndex : zIndex
});
plupload.extend(inputContainer.style, {
zIndex : zIndex - 1
});
If you view the DOM you will see that style="z-index: 0;" is added to the #uploader_browser anchor element, and the div containing the "Add Files" button gets a z-index of -1 which effectively hides it behind the page (depending on your pages z-index of course).
To fix this I set the zIndex value in the file mentioned above to something higher than the page that the plupload div was being displayed on.
Deele's solution with css is good but little better is to do it this way:
$('#uploader > div.plupload input').css('z-index','99999');
That way hover of button will be not broken...

JEditable, how to handle a JSON response?

Right now, the server response I'm working with sends back a JSON response like this:
{"status":1}
After saving, jeditable places the actual response: {"status":1} on the page. Anyway to get around this issue?
A better solution is to post-process the returned json data before it hits the page.
Suppose your server returns the following json string:
{ "status": 1, "result": "value to be displayed", "other": "some other data" }
and you would like to process the "status" and "other" fields, and display the "result" field in the jeditable input field.
Add the following 2 lines to jquery.jeditable.js:
(around line 95):
var intercept = settings.intercept || function(s) {return s; };
(around line 350, right after " success : function(result, status) {"
result = intercept.apply(self,[result]);
Then, in your own code, do something like the following:
$(some_field).editable(
'/some_url_on_your_server',
{
indicator : "<img src='/images/spinner.gif'>",
tooltip: "Click to edit.",
indicator: "Saving...",
onblur: "submit",
intercept: function (jsondata) {
obj = jQuery.parseJSON(jsondata);
// do something with obj.status and obj.other
return(obj.result);
},
etc.
This allows you do cool stuff like having your server convert abbreviations to full strings etc.
Enjoy!
There's a simple way of doing this by using the callback. .editable() converts any response to a string, so the response has to be converted to a JSON variable. The values can then be retrieved and then written using a '.text()' method. Check the code:
$("#myField").editable("http://www.example.com/save.php", {
submit : 'Save',
cancel : 'Cancel',
onblur : "ignore",
name : "sentText",
callback : function(value, settings) {
var json = $.parseJSON(value);
$("#myField").text(json.sentText);
}
});
This is how I handled the json response.
First, set the datatype using ajaxoptions. Then, handle your data in the callback function. Therein, this.revert is your original value.
oTable.$('td:eq(3)').editable('/admin/products/add_quantity_used', {
"callback" : function(sValue, y) {
var aPos = oTable.fnGetPosition(this);
if($("#dialog-message").length != 0){
$("#dialog-message").remove();
}
if(!sValue.status){
$("body").append('<div id="dialog-message" style="display:none;">'+sValue.value+'</div>');
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
if(this.revert != '')
oTable.fnUpdate(this.revert, aPos[0], aPos[1]);
else
oTable.fnUpdate("click to edit", aPos[0], aPos[1]);
}else
if(sValue.status)
oTable.fnUpdate(sValue.value, aPos[0], aPos[1]);
},
"submitdata" : function(value, settings) {
return {
"data[users_to_products][users_to_products_id]" : this.parentNode.getAttribute('id'),
"column" : oTable.fnGetPosition(this)[2]
};
},
"height" : "30px",
"width" : "30px",
"maxlength" : "3",
"name" : "data[users_to_products][quantity_used]",
"ajaxoptions": {"dataType":"json"}
}).attr('align', 'center');
So the solution I came up with is similar to what madcapnmckay answered here.
var editableTextArea = $('.editable-textarea');
editableTextArea.editable(submitEditableTextArea, {
type : 'textarea',
cancel : 'Cancel',
submit : 'Save',
name : editableTextArea.attr('id'),
method : 'post',
data : function(value, settings) {
return $.fn.stripHTMLforAJAX(value);
},
event : "dblclick",
onsubmit : function(value, settings) {
//jquery bug: on callback reset display from block to inline
$('.btn-edit').show(0, function(){$(this).css('display','inline');});
},
onreset : function(value, settings) {
//jquery bug: on callback reset display from block to inline
$('.btn-edit').show(0, function(){$(this).css('display','inline');});
}
});
Then the url function is
function submitEditableTextArea(value, settings) {
var edits = new Object();
var result = $.fn.addHTMLfromAJAX(value);
edits[settings.name] = [value];
var returned = $.ajax({
type : "POST",
data : edits,
dataType : "json",
success : function(_data) {
var json = eval( _data );
if ( json.status == 1 ) {
console.log('success');
}
}
});
return(result);
}

Categories