Change slickgrid cell data after edit - javascript

I'm using Slickgrids with alot of success. I have ajax edits all working - but I'm trying to add a piece of functionality;
Below is my code which allows me to update cells - it works as intended - but I want to be able to change the cell after it has been editted with the returned value from the json data. See my code below - I have put in capitals where I need a command to update the editted cell with the new returned data
grid.onCellChange.subscribe(function(e, args) {
var dataString = "col="+grid.getColumns()[args.cell].name+"&row="+args.item.new_training_calendar_id+"&value="+data[args.row][grid.getColumns()[args.cell].field];
$.ajax({
type: "POST",
url: "mydomain/update_cell",
data: dataString, dataType: "json",
success: function(a) {
if(a.status != "ok") {
alert(a.msg);
undo();
} else {
alert(a.msg);
**CHANGE_CELL_HERE TO (a.newdata);**
}
return false;
} }); });

If you are using DataView in your grid, you can use:
grid.invalidateRow(args.row);
var row = dataView.getItem(args.row);
row[grid.getColumns()[args.cell].field] = a.msg;
dataView.updateItem(args.item.id, row);
grid.render();
If you are using a plain grid instead, you can use:
grid.invalidateRow(args.row);
data[args.row][grid.getColumns()[args.cell].field] = a.msg;
grid.render();
Hope that helps!

Related

How to property update bootstrap autocomplete source after Ajax call

I am currently implementing the autocomplete bootstrap control from here. I only want to populate the source when characters are more than 2. I'm wondering how do I populate my type ahead source after a successful ajax call.
https://github.com/bassjobsen/Bootstrap-3-Typeahead.
var $input = $(".typeahead");
$input.keyup(function () {
var count = $input[0].value.length;
if (count >= 3) {
$.ajax({
type: "GET",
url: '/Home/GetProducts',
data: {
characters: $input[0].value
},
success: function (response) {
$input.typeahead({
source: response,
autoSelect: true
});
}
});
}
});
When I put a breakpoint at response, this is the result
So my ajax query works, but the type ahead doesn't populate with the results and aren't searchable.

How can I refresh a PHP file with itself using Ajax?

Alright guys I'm trying to make a filter system for posts using ajax and a select box. I am able to get the value from the select box no problem. But my issue is that when I try to include the selected value in my PHP file it doesn't do anything. I have a file called public_wall.php. This file contains PHP, Javascript, and HTML. How can I refresh this div whenever a user selects a different filter option? Basically I need the selected value to be passed onto my public_wall.php file and then I want to plug it into the PHP function that fetches the posts thats's in the same file and then I want to refresh that same file to display the filtered results. Here is my Javascript code.
$("#postRatings").on("click", function(e) {
selectedRatingFilter = $("#postRatings option:selected").val();
var dataString = "timeFilter="+selectedRatingFilter;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response){
hideSpinner();
jQuery('#postsPagingDiv').remove();
jQuery('#wsc_midbox').html(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
jQuery('#paging_in_process').val(0);
}
});
});
When the dataType is set to "json" nothing happens. But when it is set to html it prints some javascript code. Please help. The PHP file is too large to include here, but it basically contains PHP, HTML, and Javascript and some PHP functions that do sql queries. What is the best way to achieve a filter mechanism for my setup?
And on the public_wall.php file I want to get the value like so:
$ratingFilter = isset($_REQUEST['timeFilter']) ? intval($_REQUEST['timeFilter']) : 0;
And then plug it into the PHP function that fetches the posts which is in the public_wall.php file also so that I can filter the posts based on the selected value. And then finally I want to refresh the public_wall.php file with the new results. I hope that makes sense. Please help.
This is the output when I set my dataType to "html"
<script>
function refreshPosts() {/* only posts comments likes and count updated. */
var posts = jQuery("#all_post_id").val();
var arrays = posts.split(',');
var dataString = "postids="+posts;
jQuery.ajax({
type: "POST",
url: site_url+"includes/update_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
var x = response;
//############ skip posts whose comments are being read by users
var ExemptedPostsIDs = jQuery("#exemptedPostsID").val();
var ExemptedArray = ExemptedPostsIDs.split(',');
ExemptedArray = ExemptedArray.sort();
//////////////
for (i=0; i<arrays.length; i++) {
var val = 'row'+arrays[i];
if(x[val]) {
if(!inArray(arrays[i], ExemptedArray))
jQuery("#ajax_wall_"+arrays[i]).html(x[val]);
} else {
jQuery('#PostBoxID'+arrays[i]).parent().fadeOut(500);
}
}
}
});
}
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
function refreshWall() {/* loads new posts real time */
var posts = jQuery("#all_post_id").val();
var pageUsing = jQuery('#pageUsing').val();
var dataString = "update_posts=1&postids="+posts+'&pagex='+pageUsing;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
if(response.all_post_id) {
jQuery('#wsc_midbox').prepend(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
}
}
});
}
</script>
I suggest you keep the form with select element and any JavaScript on the outer frame.
Via ajax, only load the results to a seperate DIVision below that.
When you put an Ajax response to a div, any JavaScript inside it will not be executed.
For the best throughput with Ajax, you should consider loading a json response via Ajax and create HTML elements on the client side. That way it becomes much easier to pull additional variables to front-end JS from server side along with the same request/response.
But that becomes bit difficult when you have a template engine in the back-end. You can still send the HTML content in a json value, so you can easily pass the "all_post_id" as well..

I need to get a variable between jQuery function and AJAX

I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.

More than one value at a time?

Is there a method to include more than one value at a time. Firstly, here is the script:
$(document).ready(function() {
$('.edit_link').click(function() {
$('.text_wrapper').hide();
var data=$('.text_wrapper').html();
$('.edit').show();
$('.editbox').html(data);
$('.editbox').focus();
});
$(".editbox").mouseup(function() {
return false
});
$(".editbox").change(function() {
$('.edit').hide();
var boxval = $(".editbox").val();
var dataString = 'data=' + boxval;
$.ajax({
type: "POST",
url: "update_profile_ajax.php",
data: dataString,
cache: false,
success: function(html) {
$('.text_wrapper').html(boxval);
$('.text_wrapper').show();
}
});
});
$(document).mouseup(function() {
$('.edit').hide();
$('.text_wrapper').show();
});
});
I want to have more than one field. I want to edit more than one entry at a time, instead of simply re-writing the code for each different value. Is there a way I can include them in the code? I tried this but had no luck:
$('.edit_link','.edit_link2','.edit_link3').click(function() {
$('.text_wrapper','.text_wrapper2','.text_wrapper3').hide();
var data=$('.text_wrapper','.text_wrapper2','.text_wrapper3').html();
Hopefully you get what I mean by this, I want to include more values but cannot achieve this, does anyone have some advice or a simply way to do this?
Put all in one string, for example:
$('.text_wrapper, .text_wrapper2, .text_wrapper3').hide();
But you can't read out the values with html() on multiple elements at the same time.
So for example use:
data = $('.text_wrapper').html();
data += $('.text_wrapper2').html();
data += $('.text_wrapper3').html();
But this depends on how you wanna have your data in the end.

Automatically create listview items with an anchor tag in it

I am making a webapp with Jquery Mobile. I got my data back from a webservice function.
Now to get this data in my web page I am using a ajax call.
$('[data-role=page]').live('pageshow', function () {
var userId = $("#userId").val();
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getNieuwtjes",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'userId':'" + userId + "'}",
success: function (response) {
var nieuwtjes = response.d;
if (nieuwtjes.length > 0) {
$.each(nieuwtjes, function (i, entity) {
$('#nieuwtjesList').append(
//Here come's the data from web function
});
}
}
});
});
Now in #nieuwtjesList should come all the data that I get back from the server. These data is a newsTopic. And it should show it like this.
<li>~ITEM.ONDERWERP~ </li>
My question is, how can I create the line above for every record I got back from my webservice function.
Kind Regards.
Stef
You can use this code to create the HTML to append for each line
$("<li/>").append($("<a/>")
.attr("href", <HREF FROM YOUR DATA>)
.text(<TEXT FROM YOUR DATA>)
);
You can use jQuery.tmpl to easily implement this.
var nieuwtjes = response.d;
if (nieuwtjes.length > 0) {
var html ='';
$.each(nieuwtjes, function (i, entity) {
html += '<li>'+ i.ONODERWERP+'</li>';
});
$('#nieuwtjesList').append($(html));
}

Categories

Resources