Using jQuery on external loaded DataTable after AJAX refresh - javascript

So I have on my page a div with id="machine-content", which I use to display various info about my machines. Mainly, I display information in tables. I am trying to use DataTables (https://datatables.net/), but I have problem initializing the table. After click on action (i.e. "show me repairs", "show me workhours"), I load a table element from external html and fill it with data through AJAX according to chosen action.
So here's how my files look.
In index.php (jquery and datatables are loaded in head):
<script src="data.js"></script>
...
<div id="machine-content" class="col-md-9" style="float:right">
</div>
...
External html is super simple:
<h1 id="machine-content-h1"></h1>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%"></table>
I then have data.js that controls index.php. There, I handle clicks to actions and loading of table through AJAX. All the data is loaded correctly but when I want to initialize a DataTable (to get search field, paging, etc.) it doesnt work. As far as I know, I have to initialise it after the data is loaded, anyway I also tried initialising it before. Here is data.js:
//EXAMPLE of handling chosen action with button click
//I TRIED putting //I TRIED putting $.('#example').DataTable(); HERE
//wrapped in $(document).ready
$('#arentals').click(function(){
$( '#machine-content' ).load("/gui/machines/machines/templates/table.html", function() {
load_service_table("RENTALS");
});
});
function load_service_table(action){
var action_url;
switch(action) {
case 'REPAIRS':
action_url='/gui/machines/machines/show_services.php';
break;
case 'RENTALS':
action_url='/gui/machines/machines/show_rentals.php';
break;
case 'REVENUES':
action_url='/gui/machines/machines/show_revenues.php';
break;
default:
action_url='/gui/machines/machines/show_hours.php';
}
$.ajax({
url: action_url,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "html",
type: "POST",
success: function(data) {
//I TRIED putting $.('#example').DataTable(); HERE
$( '#machine-content-h1' ).text(action);
$( '#example' ).html(data);
//I ALSO TRIED putting $.('#example').DataTable(); HERE
}
});
//AND HERE
}
PHP functions are simple and in AJAX return only head and body elements of table, so I guess there is no problem.
So my question is: How can I initialize this thing? I mean, if I am able to set html to #example in AJAX success function, why can't I initialise the same element there? Any help would be deeply appreciated.
EDIT
I always get this error:
jquery.dataTables.min.js:65 Uncaught TypeError: Cannot read property 'aDataSort' of undefined
SOLUTION
I only added $('#machine-content').find('#example').DataTable(); to AJAX success function which now looks like this:
$.ajax({
url: action_url,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "html",
type: "POST",
success: function(data) {
$( '#machine-content-h1' ).text(action);
$( '#example' ).html(data);
$('#machine-content').find('#example').DataTable();
}
});

datatable has a build-in ajax method
$('#myTable').DataTable( {
ajax: '/api/myData'
} );
https://datatables.net/manual/ajax#Loading-data
or use:
$('#machine-content').find('.table').DataTable();

I know this post is older so probably of no help to you now but for anyone else who comes across this.
Something like the following should work:
var adminUsers = {
list: () => {
var action = 'list_users';
var url = base_url+'index.php/admin/users/io';
var data = { }
var response = ajaxRequest.post(action, url, data);
response.then(
function(obj){
var data = JSON.parse(obj);
console.log(data);
//console.log(data.data.result);
$.each(data.data, function(i,e){
var html = '';
html = html + '<tr>';
html = html + '<td>'+e.id+'</td>';
html = html + '<td>'+e.username+'</td>';
html = html + '<td>'+e.first_name+' '+e.last_name+'</td>';
html = html + '<td>'+e.status+'</td>';
html = html + '<td>'+e.locked+'</td>';
html = html + '<td>'+e.uuid+'</td>';
html = html + '</tr>';
$('#users-list tbody').append(html);
});
$('#users-list').DataTable(adminUsers.dataTable());
},
function(jqXHR, textStatus, errorThrown){
ajaxRequest.error(jqXHR, textStatus, errorThrown);
});
},
dataTable: () => {
var config = {
initComplete : function() {
$("#users-list_filter").detach().appendTo('#search');
$("#users-list_length").detach().appendTo('#display_length');
$("#users-list_length").attr('style', 'margin-right:10px;');
$("#users-list_filter input").addClass('form-control');
},
language: {
search: "",
searchPlaceholder: 'Search...'
}
}
return config;
}
};

Related

row().data to retrieve a specific column row using datatables.net plug-in

EDIT: Deleted my YouTube Video, here is simple solution:
$(document).on('click', '.edit_btn', function() {
var rowData = $('#example').DataTable().row($(this).parents('tr')).data();
});
"Working Code":
<script type="text/javascript">
$(document).on('click','.edit_btn',function (){
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row( id ).data();
var edit_id = edit_id[0];
$.ajax({
url: 'index.php',
datatype: "json",
data: { edit_id : edit_id },
async: false,
success: function(result) {
//alert(edit_id);
$("#edit_id").val(edit_id);
} //success func
}); //ajax
}); //end ready
</script>
What I tried
I tried many things as in the youTube video. I could not get the original example to work on the link.
Should I use Jquery like this??
var last_name = $('#example').DataTable().row( last_name ).data();
Or php like this?
$('#editLastName').val( <?php echo $row['first_name']; ?> );
Or something within the ajax file?
What you could try is to get the parent tr element, although I'm not sure if that's the best approach.
Simplified:
$(document).on('click', '.edit_btn', function() {
var rowData = $('#example').DataTable().row($(this).parents('tr')).data();
});
Basically you get the parent tr from the button element you click on and get the data from that row.
What I also noticed, your data-id from the button seems messed up. It looks like this: data-id='s-"0"'. I'm not sure how you generate this, but in case you fix that and it looks like data-id="0" you can select rows with $('#example').DataTable().row($(this).data('id')).data();.
As you can see, there are quite a few possibilities here.

Displaying the result of a GET request with JS and REST

I'm trying to get and display a field in a SharePoint list
using a Content Editor Web Part. This is just proof of concept, I want the CWP to display the Title (the currency) and the Currency Description. I think I just need a tweak and want to understand what I'm doing wrong. The var query URL displays the title fine.
Ultimately what I want to do is to store the returned value from the Exchange Rate column so that when a user selects a drop don in a separate list and an amount it will convert by the Exchange rate.
Any help is appreciated. Code below:
<script type="text/javascript">
DisplayExchangeRate();
function DisplayExchangeRate()
{
var listName = "Currency Exchange Rates";
var titleField = "Title";
var rateField = "Currency Description";
var query = "http://collaboration-dev.norgine.com/sites/it/Tools/IT- Contracts/_vti_bin/listdata.svc/CurrencyExchangeRates?
$select=Title,ExchangeRate&$filter=Title eq 'Dollars'";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function (i, result) {
$("#CurrencyExchangeRatesTitle").text(result.Title);
$("#CurrencyExchangeRatesCurrencyDescription").html
(result.CurrencyDescription);
});
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving Tips: " + jqXHR.responseText);
});
}
</script>
I don't believe you can put JavaScript directly in a Content Editor Web Part. Try using a Script Editor Web Part instead (housed in the same category of web parts as the CEWP), or pointing your CEWP to a local HTML page with the JavaScript.
http://info.summit7systems.com/blog/dont-script-in-the-wrong-web-part
Also, it looks like you're using JQuery. Do you have a reference to that library elsewhere that is loading successfully?
Below is my Working code , I have saved this code in a text file, and uploaded that file in "Site Assets" library and pointed my CEWP to this code file.
<script type="text/javascript" src="https://test.sharepoint.com/sites/devsite/SiteAssets/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var i,result;
$('#getEmployee').click(function () {
var dispalyResults="";
$.ajax({
url: "https://test.sharepoint.com/sites/devsite/_api/web/lists/getbytitle('Employee')/items",
method: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data) {
var jsondata = JSON.stringify(data);
result = JSON.parse(jsondata).d.results;
for (i = 0; i < result.length; i++) {
dispalyResults+="<p><h1>"+ result[i].ID + " " + result[i].Title +"</h1></p>";
}
$('#displayResults').html(dispalyResults);
},
fail: function () {
alert("Response fails");
}
})
})
})
</script>
<input type="button" value="GET" name="GET" id="getEmployee"/>
<div id="displayResults"></div>
I have created a button and a DIV tag. When i click the button , it will display the list item Title and ID inside the DIV tag.

send table created in one page to another page

I have created country and city as dependable menus. When I select all the dropdown values and click on the display button it should render created html table just below the display button which is illustrated in image below.
For table creation when I click on the display button it loads javascript code and sends ajax request to another php page. In this php page table is created. How can I render thus created html table in section just below the Display button.
My javascript code in index.php page is
<script type="text/javascript">
function tbl_display(){
var sel_countryid= $("sel_country").val();
var sel_cityid= $("#sel_city").val();
var dataString = 'sel_countryid='+ sel_countryid+ '&sel_cityid='+ sel_cityid;
alert(dataString);
if(sel_regionid=='' || sel_lbtype=='')
{
alert("Please enter Valid Data");
}
else
{
$.ajax({
type: "POST",
url: "tbl_create.php",
data: dataString,
cache: true,
success: function(html){
}
});
}
}
</script>
I have created table in tbl_create.php page.
How can I use thus created table to render below display button or How can I pass created html table to javascript code and render it to desired section ?
in your ajax function set the dataType to html and in it's success-function put the result out to a <div> below your form:
$.ajax({
type: "POST",
url: "tbl_create.php",
data: dataString,
dataType: "html",
cache: true,
success: function (html) {
$("#target").html(html);
}
});
html:
<!-- your form is here -->
<div id="target"></div>
you can append the return html table from tbl_create.php using the html() jquery function
so the return must be a string
$table = "<table><tr><td>THIS IS A TABLE</td><td>FIRST ROW</td></tr></table>";
return $table
if return won't work
try
echo $table
then in the success function
success: function(html){
$('#appendReturnTable').html(html);
}
that should do the trick hope it helps
Assuming that in your html page you have a div for your table like this :
<div class="myTable"></div>
Then in the success function of your ajax request try this :
//....
success: function(html){
$('.myTable').html(html)
}
//....

How to structure jquery ajax to be flexible to in and outputs?

I have a one-page structured website. I am trying to use Ajax to update my data on user demand.
I am trying to figure out how to structure my ajax code, so that it will be flexible to my in and outputs = I want to run different function depending on the clicked link, and I want to return the right output to the right div.
HTML links:
<a href="#page-a" class="dbLink" data-variable="funcA">
<a href="#page-b" class="dbLink" data-variable="funcB">
<div id="page-a">
<div id="a-result"></div>
</div>
<div id="page-b">
<div id="b-result"></div>
</div>
JS, ajax (I am passing a data-variable along the link to controle the action):
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
dataType: 'json',
success: function(resp){
if(resp.data){
$(resp.target).html(resp.data);
}
}
});
});
functions.php:
include 'dbconnect.php';
function funcA($mysqli){
$result = $mysqli->query("select * from database");
$row = mysqli_fetch_assoc($result);
echo $row['column'];
}
function funcB($mysqli){
$result = $mysqli->query("select * from database2");
$row = mysqli_fetch_assoc($result);
return $row['column'];
}
if (isset($_POST['action'])) {
$resp = null;
switch($_POST['action']) {
case "funcA":
$resp->data = funcA($mysqli);
$resp->target = "#page-a";
break;
case "funcB":
$resp->data = funcB($mysqli);
$resp->target = "#page-b";
break;
default:
break;
}
echo json_encode($resp);
}
add another data-* variable set to the id of the place you want to output the data. To control the format of the returned data provide the dataType option in the ajax options, and of course make sure the pointed to url actually outputs that type of data. dataType It will tell jQuery how to parse the incoming data.
var theContainer = $(this).attr("data-container");
...
dataType:"json" //or text, or xml etc etc
success: function(data){
//if data is upposed to be json
//and datType is set to json
//data will be an object, same with xml
//process data how you need to
$("#"+theContainer).html(whateverYouHaveDone);
}
If you need to control the target of the returned data within your php script then turn your returned data into json and send the selector for the target to it
$resp = new stdClass;
switch($_POST['action']) {
case "funcA":
$resp->data = funcA($mysqli);
$resp->target = "#someContainer";
break;
case "funcB":
$resp->data = funcB($mysqli);
$resp->target = "#someContainer";
break;
default:
break;
}
echo json_encode($resp);
Then in your ajax success
success: function(resp){
if(resp.data){
$(resp.target).html(resp.data);
}
}
And of course set dataType:"json"
To return just the mysql row, do the same thing as above but in the ajax success resp.data will be an object. So just access the properties of resp.data with the column names of the row
success: function(resp){
if(resp.data){
//if say you have a column named "username"
var username = resp.data.username;
}
}
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
var target = $(this).attr('href');
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
success: function(data){
$(target).html(data);
}
});
});
there are many ways to do this.
I see you have understood the custom data-* attributes. I would add one more attribute: data-target=""
<a href="#page-a" class="dbLink" data-variable="funcA" data-target="a-result">
<a href="#page-b" class="dbLink" data-variable="funcB" data-target="b-result">
<div id="page-a">
<div class="a-result"></div>
</div>
<div id="page-b">
<div class="b-result"></div>
</div>
Then inside your JQuery, you do like you do with your data-variable, only that you add the new data-* attribute:
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
var theTarget = $( this ).attr("data-target");
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
success: function(){
/* Here you have to change the data[] to match the JSON return from your PHP-script. You can of course do it without JSON, but I would use http://www.php.net/manual/en/function.json-encode.php on an array from PHP.*/
$("input[class="+ theTarget +"]").html( data["foo"][0]["bar"] );
}
});
});
If you want to play with a real life example, I made this fiddle for another guy on stack overflow a while back: http://jsfiddle.net/Olavxxx/Mu66h/
Put a number in the left box (like 5006), it's postal codes. The target then is the postal adress in the right input box. The concept is very much the same as you are after, with data-targets.

PHP $_POST not working with jquery

i am using this jquery code:
<script type="text/javascript">
$(document).ready(function () {
$("#message").hide();
$("#please_wait_box").hide();
$("#editcustomer").submit(function (e) {
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString = $("#editcustomer").serialize();
$.ajax({
type: "POST",
url: "editcustomer_go.php",
cache: false,
data: dataString,
success: function (res) {
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
if (res.indexOf("success") != -1) {
window.location.href = res.substr(8);
}
}
});
});
});
</script>
to submit forms without changing the page.
then the editcustomer_go.php echoed results display in:
<div id="message" class="messagebox"></div>
<div id="please_wait_box" class="messagebox">Please Wait...</div>
i am using tinymce for text editors - its working okay but when the data is posted in the PHP, its not seeing the changed data in the tinymce text editor - it has to be plain text.
how can i get round this?
To grab the data from TinyMCE you need to use their getContent() function.
So in your case it'd be
// Grab a reference to the editor
var ed = tinyMCE.get('tinymceeditorname');
// Get it's content
var editordata= ed.getContent();
... and then just pass editordata along with the rest of the form as the AJAX call data.

Categories

Resources