Wordpress Custom Table Ajax Receiver - ajax

I'm fairly new to using WordPress AND AJAX for that matter. I need to have a Table in my admin area which is populated with enquiries to my site.
I have set up a custom table in the admin panel which is populated by an external database. This works fine. Once this has been populated I want to be able to change a select box to keep track of the status of certain enquiries.
I have inserted the select boxes and all seems well. At this point however, I want to use AJAX to post the changed state (in particular the index no. of the new selected option) back to my database to be populated.
I have found a number of examples to do with this and have spent a wee while trying to get my head around it but once the AJAX post is sent, I am not sure how OR where to deal with the receipt of this and have it update the database.
At the moment the url which the AJAX post points towards is the .php file in which my custom table is stored.
Could someone please explain what each aspect of the following code does, and what steps I seem to missing:
jQuery(function( $ ) {
$(".select-status").on( 'change', function() {
var $currentSelect = $(this);
var currentId = $currentSelect.attr('id');
var url = "/wp-content/plugins/custom-list-table-example/list-table-example.php"; // the script where you handle the form input.
console.log(currentId['value']);
$.ajax({
type: 'POST',
url: url,
data: $currentSelect.serialize(),
success: function(data) {
alert(data);
},
error: function() {
alert('There was an error: Failed to update database');
}
})
});
});
Where select-status is the class given to each select box.
Any help would be massively appreciated.
This site gave me hope but I can't see if this is relevant or where I would implement the different parts within WordPress.

Related

Datatable destroy not working properly

After using table.destroy() method my table rows are still displayed, only the search box and other borders of datatable are not displayed.
I want to delete all the rows in the datatable, basically i want to delete the whole datatable so that i can reinitialize it.
Thank you
When you use the destroy() method you are effectively returning the table back to its original state. The HTML for the table is still present on the page hence why you can still see the table rows, without the added DataTables functionality.
If you want to remove the data rows from your DataTable, you may want to look at the clear() method, for example:
table.clear();
I have set up a jsfiddle which demonstrates these options.
If you can provide your code I should be able to give you a more accurate answer.
In case someone else finds this thread, I had the same issue when trying to replace a datatable with an ajax call. Calling destroy and then reinitializing the datatable after the ajax response worked for me with no errors. documentation
$('#myTrigger').click(function(e){
e.preventDefault();
table.destroy();
$.ajax({
type: 'post',
url: 'processor.php',
data: $('#myform').serialize(),
success: function (response) {
var table = $('#myTable').DataTable({
"pageLength": 25
});
}
});
});

Update mysql table with a click of dropdownlist in the view

Can someone please help me i want to update a database record by using the dropdownlistbox,
so when i select an option from the dropdown the database is updated with that value for that record, without having to click a submit button using codeigniter.
I know the best way to go about this is with AJAX
Yeah AJAX can make it work, and doing it with jQuery can make it a lot easier. You can add an event listener to your dropdown list, listening to a change in its value:
$("#the-dropdown-list").change(function() {
var value = $(this).attr("value");
$.ajax({
url: "path/to/controller/action/",
type: "POST",
data: {value: value},
success: function() {
// whatever you want to do after
}
});
});
This will detect a change in the dropdown list value, and then send it to the controller action given in url in $.ajax object. After that you can just update the database record like you would usually do. In the controller, the new value can be obtained using $_POST['value'], since we defined type to be POST and the different values to be passed to controller action are in the data.

Proper way to page jqGrid

I need to display a number of "dynamic" grids using jqGrid. By dynamic I mean that both definition and data of the grid are retrieved from a database. There are many grids on the page, so I am trying to minimize the number of server trips, and there is a lot of data, so server-side paging is a must.
My workflow is
On initialization of each grid, retrieve grid definition and first
page of data in one server call.
If a user sorts/pages, then retrieve a page of data from the server
Because I want to retrieve the grid definition and first page of data in one call, I cannot use datatype: 'json', url: '###' approach; instead I do:
grid.jqGrid({
mtype: 'post',
...
datatype: function (postdata) {
if (!init.data) {
var request = {
screenId: settings.screenId,
pageNumber: postdata.page,
pageSize: postdata.rows,
sortColumn: postdata.sidx,
sortDirection: postdata.sortd,
date: settings.date
};
site.callWs("/MyService", request, function (pageResponse) {
//WHAT TO CALL HERE TO SET A PAGE OF DATA?
});
} else {
//WHAT TO CALL HERE TO SET A PAGE OF DATA?
init.data = null;
}
}
});
My data object (pageResponse or init.data) looks like this
I am not sure what method to call on jqGrid once a page of data is returned. I considered addJSONData, but it seems so inefficient to convert JSON back to string, then use EVAL(). Also, considered addRowData or setting the data property, but I am confused how to instruct jqGrid that I am doing server-side paging -- if I set the data property to one page of records, what do I need to do to tell jqGrid that there is a total of 50 records and this is page 1 out of 10.
Thanks for your help.
It was a user error (mine :). I had some show/hide logic in loadComplete of jqGrid, but this event does not fire when addJSONData is called.
addJSONData works just fine when provided with a properly-structured JavaScript object.

How to properly clear the content of an Ember.Enumerable?

I was looking at Emberjs recently and found this useful article written by one of its main contributors: Advice on & Instruction in the Use Of Ember.js
It walked me through an example which fetch a list of user data from a server and render them on screen. I'll briefly explain how it worked:
The app contacts the server to fetch a list of user data though ajax
call.
At the end of the ajax call an empty enumerable is returned
immediately, which is later used as a property of a controller.
Once the ajax call is completed, it populates the enum with data which
in turns update the controller's property, and finally triggers an
automatic re-rendering.
This works fine as long as the list is not revisited. As a user revisit the list, say he/she navigates to another state and then comes back, the logic will be triggered again, fetching the data from server and populates the list. However, the list this time is not empty! Thus we have a list of duplicated data. I would like to resolve this by clearing the content of the list when the ajax call is successful. Below is the code for the ajax call:
allAwesomebergs: [],
fetch: function(){
$.ajax({
url: 'https://api.github.com/repos/emberjs/ember.js/contributors',
dataType: 'jsonp',
context: this,
success: function(response) {
response.data.forEach(function(awesomeberg){
this.allAwesomebergs.addObject(App.Awesomeberg.create(awesomeberg))
}, this);
}
});
return this.allAwesomebergs;
},
The above code does not clear the content of the list. I tried adding a line "allAwesomebergs = []" at the beginning of the success function, but what I got was just a blank screen. I thought I may not be doing this correctly, but I looked at the document from Ember and didn't see anything about clearing the content of an Enumerable.
Thus the question is: what is the easiest way to resolve this duplicate loading issue? Clearing the content before hand seems the most obvious but I can't make it work.
You can call clear() before you start adding the new objects. See this documentation.
New code would be:
allAwesomebergs: [],
fetch: function(){
$.ajax({
url: 'https://api.github.com/repos/emberjs/ember.js/contributors',
dataType: 'jsonp',
context: this,
success: function(response) {
this.allAwesomebergs.clear();
response.data.forEach(function(awesomeberg){
this.allAwesomebergs.addObject(App.Awesomeberg.create(awesomeberg))
}, this);
}
});
return this.allAwesomebergs;
},
I think your approach was ok, but it should have been:
this.allAwesomebergs = []
It is all about the this in front of it. So clear is not needed here.

Loading dynamic "chosen" select elements

I am using the jQuery plugin chosen (by Harvest). It is working fine on (document).ready, but I have a button that, when clicked, uses ajax to dynamically create more select objects that I want to use the "chosen" feature. However, only the original select elements have the "chosen" features, and the new (dynamically created) do not work. I am using jQuery.get to append the new elements. Here is a sample of the code:
jQuery(".select").chosen();//this one loads correctly
jQuery("#add-stage").click(function() {
jQuery.get('/myurl',{},function(response) {
//response contains html with 2 more select elements with 'select' class
jQuery('#stages').append(response);
jQuery(".select").chosen();//this one doesn't seem to do anything :-(
});
});
I was thinking that I need a .live() function somewhere, but I haven't been able to figure that out yet. Any help is much appreciated!
Note - I am not trying to dynamically load new options, as specified in the documentation using trigger("liszt:updated");
Ensure that the response elements have the select class.
console.log( response ); // to verify
May also be a good idea to only apply the plugin to the new element(s).
jQuery(".select").chosen();
jQuery("#add-stage").click(function() {
jQuery.get('/myurl',{},function(response) {
console.log( response ); // verify the response
var $response = $(response); // create the elements
$response.filter('.select').chosen(); // apply to top level elems
$response.find('.select').chosen(); // apply to nested elems
$response.appendTo('#stages');
});
});
Also, if /myurl is returning an entire HTML document, you may get unpredictable results.
after you code (fill the select) .write this
$(".select").trigger("chosen:updated");
I had a similar problem with Chosen. I was trying to dynamically add a new select after the user clicks on a link. I cloned the previous select and then added the clone, but Chosen options would not work. The solution was to strip the Chosen class and added elements, put the clone in the DOM and then run chosen again:
clonedSelect.find('select').removeClass('chzndone').css({'display':'block'}).removeAttr('id').next('div').remove();
mySelect.after(clonedSelect);
clonedSelect.find('select').chosen();
one way you can use chosen with ajax:
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
cache: false,
data: search
}).done(function(data){
$.each(data, function(){
$('<option />', {value: this.value, text: this.text}).appendTo(selectObj);
});
chosenObj.trigger('liszt:updated');
});
where selectObj is particular select object
But ...
Chosen is implemented very bad.
It has several visual bugs, like: select some option, then start searching new one, then remove selected and the keep typing - you will get 'Select some options' extended like 'Select some options search value'.
It doesn't support JQuery chaining.
If you will try to implement AJAX you will notice, that when you loose focus of chosen, entered text disappears, now when you will click again it will show some values.
You could try to remove those values, but it will be a hard time, because you cannot use 'blur' event, because it fires as well when selecting some values.
I suggest not using chosen at all, especially with AJAX.
1.- Download Livequery plugin and call it from your page.
2.- Release the Kraken: $(".select").livequery(function() { $(this).chosen({}); });
This is an example of Chosen dynamically loading new options form database using ajax every time Chosen is clicked.
$('.my_chonsen_active').chosen({
search_contains:true
});
$('.my_chonsen_active').on('chosen:showing_dropdown', function(evt, params){
id_tosend=$(this).attr("id").toString();
$.get("ajax/correspondance/file.php",function(data){
$('#'+id_tosend).empty();
$('#'+id_tosend).append(data);
$('#'+id_tosend).trigger("chosen:updated");
});
});

Resources