Can't make DataTables work by using jQuery .post() - javascript

I am working on a form where a uses chooses a date range in order to display information by using DataTables.
When the user clicks on the button, the dates are sent through jQuery .post() function and it retrieves the info as expected.
Here is the piece of the code related to it:
//Sending the dates range
$.post(url_route, datos, function(data,status){
if(status=='success'){
var response = jQuery.parseJSON(data);
//checking if data were found
if(response.list_events.length === 0){
console.log('No data available');
}
else{
//Let us display the info with DataTables inside div #list_events and
//table #table_id
$('#list_events').html('<table class="table table-striped table-hover" id="table_id"></table>');
$('#list_events table').append('<thead><tr><th>Event</th><th>Type</th><th>Attendance</th><th>Coordinators</th><th>Participants</th><th>Institutes</th><th>Talks</th></tr></thead><tbody></tbody>');
//retrieving the info for each row and append it to the table:
$.each(response.list_events,function(i,item)
{
$('#list_events').find('tbody').append('<tr>');
$('#list_events').find('tbody').append('<td>'+item.Event+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Type+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Attendance+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Coordinator+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Participant+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Institute+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Talk+'</td>');
});//end of each
//initializing DataTables
var table = $('#table_id').DataTable();
}//end of else (info found)
}//end of if success
}//end of post()
So far, the info is displayed in the DataTables but it is not totally working, since only the information is displayed. The DataTables search, next, and previous buttons, as well as the number of results dropdown menu are not shown.
In the console.log I get the following error:
Uncaught TypeError: Cannot read property 'length' of undefined
Any ideas? Can anyone shed some light on this?
Solved
The problem was with the append function.
If I type just one append with only the <tr> like this:
$('#list_events').find('tbody').append('<tr>');
The result in HTML is <tr></tr> That is to say, the tag is closed automatically ... no matter what. So, the solution was to put all the appends in one line like the following:
$('#list_events').find('tbody').append('<tr><td>'+item.Event+'</td><td>'+item.Type+'</td><td>'+item.Attendance+'</td><td>'+item.Coordinator+'</td><td>'+item.Participant+'</td><td>'+item.Institute+'</td><td>'+item.Talk+'</td></tr>');
And that was it ☺

My first thought is that perhaps "response.list_events" is undefined. Certainly your error:
"Uncaught TypeError: Cannot read property 'length' of undefined"
seems to imply that.
My second thought is that I have recently done something similar where I had trouble with the .post method, and found success with the .ajax method.
Try something along these lines:
$.ajax({
type: "POST",
url: url_route,
data: datos,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(returned_from_server){
// your function here
}
});
My third thought is that I don't see where you put your closing row tags.
$.each(response.list_events,function(i,item)
{
$('#list_events').find('tbody').append('<tr>');
$('#list_events').find('tbody').append('<td>'+item.Event+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Type+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Attendance+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Coordinator+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Participant+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Institute+'</td>');
$('#list_events').find('tbody').append('<td>'+item.Talk+'</td>');
$('#list_events').find('tbody').append('</tr>'); // <--- I believe you might be missing this!!
});//end of each
Hopefully this was some help.

If you are using a remote source for your data, it is far more elegant and efficient to let DataTables itself render the data for you.
In your example, you fetch the data, build the table, and then turn it into a "DataTable". If it meets the requirements and gets the job done, you've written perfectly fine code and you should read this answer no more!
But DataTables itself is awfully smart about rendering data detached from the DOM and then slotting it all in place. You get the benefit of more efficient updates while simultaneously having cleaner code.
Here's a basic example. Without testing it in your environment, I can't say for sure it will do your job, but I think it should:
var myTable = $('#table_id').DataTable( {
"ajax": {
"url": url_route,
"data": function(customData) {
customData.datos = datos // need some way to have access to datos
}
}
});
And then on click, if you want to retrieve newer data based on whatever has changed (the date range?) you just have to redraw.
myTable.draw();
I can imagine a few ways to get datos in there-- wrap it up in a function that accepts and uses datos. Declare a namespaced or otherwise quasi-global (or actually global if you're that guy!) variable that myTable would have access to at any given point in time... or even just destroy the current table and call the whole DataTable() on it again.

Related

issue using $.ajax with php effectively

I'm having trouble understanding what I'm missing or not doing here (obviously something), and maybe someone can help.
I have a database site that displays a table generated from a SQL database on the client side. When the table is initialized, this code is executed and pulls the data needed for the dropdown in question (comments added by me for this post):
$selectOwner = "SELECT DISTINCT [Contacts].[Alias], [Contacts].[Last Name], [Contacts].[ID] FROM [TechInv].[dbo].[Contacts]";
//this is the file that contains the above query variable
require('custom/Connection.php');
$owner_arr = array();
//$conn is our connection string
$response = sqlsrv_query($conn, $selectOwner);
while ($row = sqlsrv_fetch_array($response)){
array_push($owner_arr, $row['Alias'] . " " . $row['Last Name']);
}
This generates a list of name records pulled from the database in a Alias(first name) Last Name format.
Here's where I'm having trouble
Another function of the site is a menu that allows users of a certain priveledge level to add additional contacts to the table. Everything works fine with that except nowhere in the code is the above array updated when a contact is added, which forces the user to reload the page, ew.
I know i need to use $.ajax for this, so I took a stab at it, and put the following code into the click handler for the 'add contact' submit button:
$.ajax({
type: 'POST',
data: 'listRefresh();',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function() {
alert("this succeeded?");
}
});
The data: 'listRefresh();' line refers to a function I created that is the same as the first block of code, in an attempt to just refresh the variables with new data. That's obviously where I've gone wrong, (try not to laugh) but I am out of ideas here. Can anyone shed some light?
Your ajax call is wrong. The 'data' value is what you send to the server.
Try this:
$.ajax({
type: 'POST',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function(data) {
listRefresh(data);
alert("this succeeded?");
}
});
The data variable is what the server gives you back, so you can pass that data to the listRefresh() function and re-render the upated list.
In alternative, you could just reload the page putting location.reload(); into success function

How to send javascript object to php via ajax?

I looked at some other questions such as this and this, but it does not me help me solve my problem. When I console-log my data, I get this:
Object["row_LM#00000010", "row_LM#00000002", "row_LM#00000009", "row_LM#00000008"]
How can I get this in php as a key value pair like row_ : LM#00000010, row_LM#00000002, row_LM#00000009,LM#00000008, so that I can loop each value? I tried JSON.stringify(), I got TypeError: cyclic object value
Here's what I have tried:
$.ajax({
type:'POST',
url:'delinvoices.php',
data:{del_id:JSON.stringify(deleteInvoice)},
success: function(data){
//other codes
}
});
The console.log of deleteInvoice gave me:
Object["row_LM#00000010", "row_LM#00000002", "row_LM#00000009", "row_LM#00000008"]
The base data comes from datatable
var deleteInvoice = dt.rows( { selected: true } ).ids();
Please help.
According to this page (https://datatables.net/forums/discussion/30848/trying-to-get-get-the-row-ids-using-rows-ids), you are getting a dataTables object instance. To get an array, you'd do this:
table.rows( { selected: true } ).ids().toArray();
It might help to simplify what you're working with, the dataTables object might be what's going cyclic on you.

Calling ajax from within js file on users browser

I have a bookmarklet which a user adds to their own browser bookmarks toolbar which collects images from a page they are looking at.
I want to log each time a user is clicking on any site and store the data in a mysql table. So i'm using an ajax call to post to a php file which processes the data sent to it.
However, this sometimes works and sometimes does not. Meaning, it works on some sites and not others.
What I'm trying is this:
(function()
{ // declare variables e.g. div.ids, div content etc then display it
......
//log the click
var dataString = '&url=' + encodeURIComponent(window.location.href) + '&page_title=' + encodeURIComponent(document.title);
$.ajax({
type: "POST", // form method
url: "http://myurl.com/includes/log_clicks.php",// destination
data: dataString,
cache: false
});
//END log the click
})();
When it doesn't work and i use Firebug to find out why, i sometimes get the error: TypeError: $ is undefined $.ajax({
Sometimes it still posts to the php file but with no data
Is there a better way to call ajax from within a js file on a user's browser?
As per suggestions, I've tried loading jquery by simply amending one of the variables like so:
div.innerHTML = '<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script><div class=....';
But that made no difference
You need jQuery present on the page in order to perform this. You will need to load jQuery if not present. A great approach is outlined here using the jQuerify code which actually just loads a portion of jQuery functionality that is needed.

jquery - update jquery.sparkline after async data fetch

Background
i'm using jquery.sparkline to produce Pie Charts. The data for the Pie Chart is contained in an array.
When the page is first loaded a web-service is called (using .ajax) to get the data, the callback specified there takes the received data and updates the array associated with the pie chart.
That same update process is invoked when a dropdown on the screen changes value.
Situation
If I set the .ajax call to asynch=false this all works fine.
If I set the .ajax call to asynch=true the results shown in the pie are always 'one refresh behind'. By this I mean there's no pie initially and then when the dropdown is changed the pie is rendered as it should have been initially.
Code
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: requestURL,
async: true ,
success: function (data) { successCallback(data); },
error: function (data) { failureCallback(data); }
});
Help?
Anyone out there recognise this problem ?
Options
I've been looking at variations on the Observer pattern to monitor a change to the array and the (not sure how) persuade the jquery.sparkline object to redraw itself but this seems crazy and I'm sure I must be overlooking something much more straightforward.
Thanks to Gareth and his sample code I was able to see what I was doing wrong (which wasn't anything to do with jquery.sparkline.
I had some functions like this :
function RefreshPieChart(){
//First call managePieDataFetch()
//to kick off the web-service request
managePieDataFetch();
//now reinitialise the jquery.sparkline
//pie charts on the basis that the
//array variable initialised in
//pieDataFetchCallBack() has the newest
//data in it.
//
//.... It hasn't !
}
function managePieDataFetch(){
//invoke the .ajax call and
//provide function pieDataFetchCallBack() as
//a call back function
}
function pieDataFetchCallBack(){
//post process the data
//returned from a successful
//ajax call. Place the results
//into an array variable at
//script scope
}
I'd need to see a more complete example to determine where the problem is, but using async: true works fine for me.
Here's a link to a very simple working example: http://omnipotent.net/jquery.sparkline/ajaxtest.html
The source for the ajax side is here:
http://omnipotent.net/jquery.sparkline/ajax.phps
If your chart is hidden (ie. display: none) at the time .sparkline() is actually called then you may need to call $.sparkline_display_visible() at the point the chart is made visible to force it to be rendered at that point.

variables showing as undefined in firebug when they are defined

here is my site http://iadprint.com/products?product=Business%20Card
when i select a value for quantity a price is supposed to show in the pricing div on the top right.
this used to work but for some reason today in firebug under dom i can see that a few variables show undefined. when i do the ajax call iadprint.com/ajax.php?id=1 the data shows correctly and the variables in the js are all defined. what can be wrong? here are the variables that i am seeing undefined.
woCoating_price
woColor_price
woDesign_price
woJob_Name_price
woPDF_Proof_price
woQuantity_price
woRound_Corners_price
woTurnaround_price
I replaced your $.get() call with a full $.ajax() call that includes an error: callback.
The result is that you're getting a parse error because your JSON response is invalid.
"parsererror" "Invalid JSON: {"price":"15.00"}<br/>"
You need to get rid of that <br/> tag.
If this isn't it, then you'll need to provide specific detail on how to reproduce the problem, and in which part of your code you expect to see a defined value.
EDIT: Here's the change handler I used after removing yours:
$("#Quantity").change(function () {
hash = $("#Quantity").val();
console.log('hash',hash);
$.ajax({
url:"ajax.php",
data: { id: hash },
dataType:'json',
success:function (out,b,c) {
woQuantity_price = out.price;
displayPrice();
console.log(out,woQuantity_price,b,c);
},
error:function(a,b,c){
console.log('error:',a,b,c);
}
});
});

Categories

Resources