Combining HTML Form to Datatables ajax request - javascript

Hi I'm working with djangorestframework-datatables and datatables' JQuery plugin.
I'm loading a large table (about 15000 entries, paginated) with the serverSide option enabled. I enabled this option because client side processing was taking too long to load the table (even with deferLoading).
I want to retrieve data from the following URL:
/api/device_input/?format=datatables&device_id=something
// device_id can be 1, 2, 3 and so on.
The problem is, I can't figure out how I can dynamically change the device_id parameter. That parameter is definitely user input. Here's how I was previously doing it (with client side processing):
1) User enters device ID into a form. Form gets submitted.
2) Django view takes the POST request and returns the filtered queryset to the template.
3) The queryset populates the HTML table values and datatables handles the rest (pagination etc)
But now with server side processing, I don't need the django view to return any querysets. I can just get data through ajax. The behaviour I want is:
1) User opens page, an empty datatable is displayed, with a prompt to enter device ID.
2) User enters device ID, and the datatable is loaded with records for that device id.
But the datatables ajax request only gets invoked when someone messes with the datatable (such as change page or select page length). I want to invoke the ajax request when someone enters device_id into my form and dynamically tell ajax to create the right URL.
Here's what my javascript looks like:
<!-- Javascript function to initialize the datatable -->
<script>
var device_id = document.getElementById("id_input").value
$(document).ready(function() {
$("#device_inputs_table").DataTable({
"lengthMenu": [
[10, 20, 30, -1],
[10, 20, 30, "All"]
],
fixedHeader: {
headerOffset: 62
},
"order": [
[0, "desc"]
],
"serverSide": true,
"ajax": "/api/device_input/?format=datatables&device_id=" + device_id, // need to add a number at the end that user will input
"columns": [
// All my table columns
]
});
});
</script>
I'm sure this is simple to do, but my unfamiliarity with ajax and javascript has me scratching my head, any help is appreciated!
UPDATE: I tried adding a simple variable to get device_id from the form element, but it doesn't get added to my URL... how do I print my URL out on the dom? (I'm only checking through the network tab on chrome dev tools...) Of course my form doesn't even invoke the ajax request so that's another issue.

First you need to declare a variable to hold the DataTable and call it from your javascript.
Example:
var deviceInputsTable = $('#device_inputs_table').DataTable({
// Rest of the table declaration goes here.
})
Then, you create a function that triggers to load data in your deviceInputsTable, something like:
function loadDeviceInputsTableData(deviceID){
device_id = deviceID // (get this from the input)
// do the ajax call here and this is the important part:
success: function(data){
// This is just a rough scratch, but this is how you initially call the first data in the table, consequent calls will now be server-side since your device_id now has a value in the ajax call you showed above.
deviceInputsTable.clear().rows.add(data).draw()
}
}
I hope this helps.
EDIT, concerning your comment below:
You can use a normal jQuery ajax call. Something like this:
function loadDeviceInputsTableData(deviceID){
device_id = deviceID;
$.ajax({
type: 'GET',
url: `SomeURLhereAppendingthedeviceIDParameter`,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
// Transform the AJAX's response here and get the data to add to your data table below
deviceInputsTable.clear().rows.add(data).draw()
}
});
};
To trigger the ajax again on change of the input, you can call the on change function in jQuery.
$('#id_input').on("change",function(){
loadDeviceInputsTableData($('#id_input').val());
});

This issue was solved by using datatable's API, my question was about changing the ajax url dynamically upon user input. Here's what I did:
// Get device ID from wherever user inputs it, in my case it was a button with id: id_input
device_id = document.getElementById('id_input').value;
// Dynamically set your datatable's ajax URL to whatever you want. I concatenated the device id
// string with my url string. ajax.url("your URL") is enough to set the URL
// .load() is for getting data from the new URL you've just set.
$('#device_inputs_table').DataTable().ajax.url(
"/api/device_input/?format=datatables&device_id=" + device_id).load();
Doing this gave me the final URL: "/api/device_input/?format=datatables&device_id=1" (if user inputted 1) fixing my issue.

Related

Using jquery ajax load() to transfer multiple data fields

I have an HTML form that I am trying to convert to submitting using the Jquery load() function. I have it working for a single field, but I have spent hours trying to get it to work for multiple fields, including some checkboxes.
I have looked at many examples and there seems to be about three of four ways of approaching this:
Jquery .load()
jquery .ajax()
jquery .submit()
and some others. I am not sure what the merits of each approach is but the first example I was following used the .load(), so that is what I have persisted with. The overall object is to submit some search criterion and return the database search results.
What I have at present:
<code>
// react to click on Search Button
$("#SearchButt").click(function(e){
var Options = '\"'+$("#SearchText").val()+'\"' ;
var TitleChk = $("#TitleChk").prop('checked');
if (TitleChk) Options += ', \"TitleChk\": \"1\"';
// load returned data into results element
$("#results").load("search.php", {'SearchText': Options});
return false; //prevent going to href link
});
</code>
What I get is the second parameter appended to the first.
Is there a way to get each parameter sent as a separate POST item or do I have to pull it apart at the PHP end?
It would seem as if you're stumbling over the wrapper, let's go ahead and just use the raw $.ajax() and this will become more clear.
$("#SearchButt").click(function(e){
var Options = {};
Options.text = $('#SearchText').val();
Options.title = $('#Titlechk').prop('checked')) ? 1: 0; //ternary with a default of 0
$.ajax({
url: 'search.php',
type: 'POST',
data: Options
}).done(function(data){
$('#results').html(data); //inject the result container with the server response HTML.
});
return false;
});
Now in the server side, we know that the $_POST has been populated with 2 key value pairs, which are text and title respectively.

Updating total number on website with jQuery / Javascript?

This below is displaying Total racers on my website but its not updating live. I need to referesh the page to grab the new number from the database, so what's the simple way of updating it live with jquery/javascript without refreshing the page? Thanks a lot for taking the time to check my question and possibly answer.
<div id="stats">
<div id="racers">
<span><?=number_format($racers, 0, ' ', ' ')?></span>
RACERS
</div>
</div>
Jquery Ajax:
$.post('page.php', {
postVariable : value
}, function(data) {
//do something with data retrieved from php script
});
You set 'page.php' to a script that gets the data you want and echoes it.
You then retrieve what was echoed in the callback function(data);
So data will be the variable containing the value you need. You put this script in a
javascript function and call it when you need to make a request for information on the back-end.
If you have questions let me know. If you need more information on the ajax request you can find it here as well: api.jquery.com/jquery.post/
What you need to do this is the following:
1. Have an action in a controller that outputs the total number of racers
For example:
class Data extends CI_Controller {
public function GetTotalRacers() {
// This is dummy data. You need to replace this code with the correct
// number of racers retrieved from the database
echo 14;
}
}
Take note of where this action is. I'm assuming codeigniter will make the path something like /Data/GetTotalRacers in this case (that depends on how your route rules are configured).
2. Use JavaScript to ask the server for the data and display the result on the page
I recommend you have a method that runs every X number of seconds to refresh the total number of racers. To achieve this, you can use setInterval. Within the setInterval's function have an ajax call to your action. Finally, display the value that's returned from the server:
setInterval(function() {
$.ajax({
// Replace the url value with the correct url to access your action
url: '/Data/GetTotalRacers',
cache: false
})
.done(function( totalRacers ) {
$("#racers span").text(totalRacers);
});
}, 60000); // ex. Update every 60000ms
Note: I've never used codeigniter, but hopefully this description will help set you on the right path.

Return result to a PHP variable from AJAX in a jQuery function

So this is the hardest thing I've ever tried to do, I cannot find any answers after 1 day of searching. Note that I am using some custom jQuery API and will explain what it does.
The setup is a php page that contains a jQuery function. That jQuery function calls the API to return a result based on a row I clicked (it is jQgrid, basically looks like an online excel sheet). That works fine, but the objective is to get that result OUT of the jQuery function and store it in a PHP variable. I am just clueless......
Main PHP Page:
$getUnitID = <<<getUnitID //This is the jQuery function. It is stored in a php variable for use in other functions of the API
function(rowid, selected)
{
var selr= null;
if(rowid != null){
selr = jQuery('#grid').jqGrid('getGridParam','selrow'); //This will give ma a number result based on the row I selected. Works fine.
$.ajax({ // I believe I need to use AJAX so here is my attempt
type: "POST",
url: "getId.php", //This is another PHP page for the reuslt. See below
dataType: "json",
data: {selr:selr},
success: function(data) {
alert (data); // This will successfully show me the row number I chose as an alert. But I don't want an alert, I want it stored as a php variable in my main document to use elsewhere.
}
});
}
}
getUnitID; //End of the function
$grid->setGridEvent('onSelectRow',$getUnitID); //Just an event that calls the function upon clicking the row
$rowResult = ??????? //I need this variable to store the result of that AJAX call or that function call
getId.php
<?php
$rId = $_POST["selr"];
echo $rId;
?>
Essentially, I have no idea why I am using AJAX, because my result is still stuck inside the main jQuery function. How in God's name do I get it OUTSIDE that function?!?!?!?!?!?!?! Do I need to $_GET the 'selr' that I POSTed to getId.php ? If so, how?
Thank you, I love you all.
By the time you get that AJAX request sent out and response received, PHP has already gone to sleep. You cant give the data back to your same page's PHP code. Your jQuery starts executing on client computer long after PHP has already finished its work on your server.
It doesn't matter whether your JavaScript function is stored in a PHP variable. PHP will not get its output back. Only way you can do so is to launch another new request to that code and send value to it. but on the same very request on the same very page, its a no no.
Example of how you can send that data to another PHP page
//Your existing jQuery
success: function(data) {
// alert (data);
var result=data;
$.ajax({
type: "POST",
url: "anotherpage.php",
data: { data: result }
});
}

Datatables submit form serverside data

For those of you that use the Datatables js plugin, how can I create this example with server side data?
The example uses data that is hardcoded in the HTML.
You would basically do the following:
Serialize the form data (using jquery serialize as the example shows)
Submit said data to your form handling scrip (php etc)
They already provide the jquery serialize code so I won't show that, however the jQuery AJAX function will be needed (at the least):
$.ajax({
type: "POST",
url: "some.php",
data: YOUR-SERIALIZED-DATA-HERE,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
And on your Server side PHP file you just grab the correct form array and parse your values ($_POST).
I had the same problem and didn't want to do an ajax save, so I did this:
var table = $("#mytable").datatable();
$("#myform").submit(function () {
var hiddenArea = $("<div></div").hide().appendTo("#myform");
table.$('input:hidden').detach().appendTo(hiddenArea);
// Prevent original submit and resubmit, so the newly added controls are
// taken into account
this.submit();
return false;
});
The idea is that I take all the inputs that are currently not in the dom and move them inside a hidden container.

How to Make a Feed From User Submitted Posts

I'm trying to figure out how to use AJAX to create a Twitter-like feed that displays user's posts on the same page immediately after they push the submit button. It would be an infinite-feed site that would have a "more" button at the bottom.
All I'm trying to make is a simple page containing a textarea box with a submit button and to have user submissions appear below the box as they are submitted.
If possible, a walk through or discussion of the script needed to do this would be great.
Thanks so much
All you need is a server-side script with an SQL query that would return newer posts.
have your javascript store a variable of the date or of the last post id (used PHP for clarification):
result = mysql_query("SELECT ID,POST FROM POSTS WHERE DATE>" . $_GET['date']); //or use WHERE ID> $_GET['id']
while(rows[] = mysq_fetch_array(query));
print json_encode(rows);
now you have a server-side script that will return new posts, so all you have to do is write javascript function for the more button:
updatePosts = function () {
$.ajax({
url: 'serversiderUrl?lastId=' + last_id, //last_id is global variable for the id of the last post on the page
success: function(data){
data = JSON.parse(data);
for(i in data){
$('#posts_container').append(data[i].post); //do your appending functions here
last_id = data[i].id;
}
}
}
now for posting new entries create a server-side script of your favorite language that handles new posts:
result = mysql_query("INSERT INTO POSTS VALUES(''," . urldecode($_POST['POST']) . ")");
now for the client side:
submit_post = function(){
$.ajax({
type: 'POST',
url:'yourposturl',
data: "post=" + encodeURIComponent($('#textArea').text()),
success: function(){
updatePosts(); // call the function that update the posts so the new entry is now added to the page
}
});
}
Now bind the functions to the appropriate buttons when the document is fully loaded:
$(document).ready(function (){
$('#moreButtonId').click(updatePosts);
$('#submitButtonId').click(submitPost);
});
There are many ways such as the submit button kept sending it to the database while we'd append text to a container underneath. Or we can update the container underneath to create a container (page) that are similar, after the ajax response is successful then we append the data to the container beneath
$.post(url,function(data){
//Here you can append the data responsed by the ajax request to the container underneath
});
But you have to have a exactly same view with a conatiner (feed container) existing in the currently page

Categories