JEditable, how to handle a JSON response? - javascript

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

Related

Jquery UI autocomplete works fine but getting blank result

I have used Jquery autocomplete example from http://jqueryui.com/autocomplete/#remote-jsonp. I have included all the specific code from the reference site but that doesn't work in my local.
I want only company name to be search in it.
Here i am attaching image to get the exact idea what i am getting
<script>
$( function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#company_name" ).autocomplete({
source: "http://localhost:5050/api/v1/web-customer-list",
type: "GET",
minLength: 1,
autoSelect: true,
autoFocus: true,
dataType : "json",
response: function( event, ui ) {
var responseObj = ui.content[0];
var companyNameList = [] ;
for(var i = 0 ; i<= 6 ; i ++){
companyNameList.push(responseObj[i].company.company_name) ;
}
},
select: function( event, ui ) {
console.log(event);
console.log(ui);
log( "Selected: " + ui.item.company.company_name + " aka " + ui.item.id );
}
});
} );
</script>
I have forked over the example and made some adjustments to fit what you appear to be doing.
Working Example: https://jsfiddle.net/Twisty/0Lajrcfv/
HTML
<div class="ui-widget">
<label for="companyName">Company Name: </label>
<input id="companyName">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
jQuery
$(function() {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#companyName").autocomplete({
source: function(req, resp) {
var companyNameList = [];
$.ajax({
//url: "http://localhost:5050/api/v1/web-customer-list",
//type: "GET",
url: "/echo/json/",
type: "POST",
data: {
json: JSON.stringify({
company: {
company_name: [
"Apple",
"Google",
"IBM",
"HP",
"Yahoo!",
"AltaVista",
"Yelp",
"2600"
]
}
})
},
dataType: "json",
success: function(respObj) {
for (var i = 0; i <= 6; i++) {
companyNameList.push({
id: i,
value: respObj.company.company_name[i]
});
}
resp(companyNameList);
}
});
},
minLength: 1,
autoSelect: true,
autoFocus: true,
select: function(event, ui) {
log("Selected: " + ui.item.value + " aka " + ui.item.id);
}
});
});
So, as you can see from the example, the source option can accept the response from a string or callback function. The callback function is passed two parameters, request and response.
The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
Based on your code, it looks like you are not going to filter clientside, you're just going to accept the top 6 from whatever your GET request returns. So we just ignore req.term in my example. We're then only really concerned about collecting the results, formatting them properly, and returning them to resp().
For my working example, we POST the data so it can be echo'd back as a response. Based on your example, you're expecting an object of some type, roughly similar to:
[{
company: {
company_name
}
}]
If you want your version to work, where you call the URL via GET, the data returned should be:
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
For example:
[{
label: "Apple",
value: 1
},
{
label: "Google",
value: 2
}];
I hope this helps a bit.

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
};
}
}
},

Call one jquery plugin in the callback of another plugin

I'm trying to use these two jquery plugins together a type watch (https://github.com/dennyferra/TypeWatch) and toaster (http://www.jqueryscript.net/other/jQuery-Bootstrap-Based-Toast-Notification-Plugin-toaster.html).
Howerver when I exchange the line
callback: function (value) { alert('TypeWatch callback: (' + this.type + ') ' + value); }
by
callback: function (value) {
$.toaster({ priority : 'success', title : 'Saved', message : '' }); }
it shows nothing. How can I integrate these two plugins?
Here is the whole script:
<script type="text/javascript">
var options = {
callback: function (value) {
$.toaster({ priority : 'success', title : 'Saved', message : '' }); },
wait: 750,
highlight: true,
captureLength: 2
}
$("#content").typeWatch( options );
</script>
Thanks in advanced.
Alex

CKEditor Plugin: Setting a default value based on a selection

I created a custom CKEditor Plugin that takes a text value and inserts it into some HTML. Everything works fine, but I don't know how to populate the field with a default value. I would like the default value to be blank if it is a new element. But i would like the default value to be the value of the selected item while editing it. Otherwise I am unable to edit the value inside of the HTML without going into Source mode, or completely deleting everything and starting over again.
CKEDITOR.dialog.add( 'videoLinkDialog', function( editor )
{
return {
title : 'Video Properties',
minWidth : 400,
minHeight : 200,
contents :
[
{
id : 'general',
label : 'Settings',
elements :
[
{
type : 'html',
html : 'This dialog window lets you embed Vimeo videos on your website.'
},
{
type : 'text',
id : 'url',
label : 'Video ID',
validate : CKEDITOR.dialog.validate.notEmpty( 'This field cannot be empty.' ),
required : true,
commit : function( data )
{
data.text = this.getValue();
}
},
]
}
],
onOk : function()
{
val = this.getContentElement('general', 'url').getInputElement().getValue();
var text = '<a class="colorbox-inline" href="http://player.vimeo.com/video/' + val + '?width=915&height=515&iframe=true&autoplay=1"><img class="vid-thumbnail" src="http://placehold.it/350x150" data-vimeo-id="' + val + '" /></a>';
this.getParentEditor().insertHtml(text)
},
};
} );
There are several ways,
The simplest way being to add setup to each of your dialog elements as demonstrated in the CK Editor Plugin Tutorial like so:
{
type : 'text',
id : 'url',
label: 'Video ID',
validate : CKEDITOR.dialog.validate.notEmpty( 'This field cannot be empty.' ),
required : true,
setup : function ( data ) {
this.setValue(data.getAttribute('url'));
}
commit : function( data ) {
data.text = this.getValue();
}
}
Alternatively, you could also use this event handler that will fire before the dialog is rendered:
onShow: function () {
// your code here
// eg. this.setValue(*ELEMENT_ID*, *ELEMENT_VALUE*);
}
here you can view the element that called the event and get or set any values you may need to populate your dialog.
You should also add a click listener like the following to your plugin.js file to show the dialog from a selected element like so:
editor.on('doubleclick', function (e) {
var el = e.data.element;
if (el == *YOUR_CUSTOM_ELEMENT*)
e.data.dialog = *DIALOG_NAME*;
});

jqGrid inline edit using successfunc

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);

Categories