Trying to add dynamic options to jtable (jQuery) - php

The basic syntax for adding a RadioButton to the AddRecord option is as follows
active: {
title: 'Activo',
width: '5%',
type: 'radiobutton',
options: { '0': 'No', '1': 'Si' }
},
Ive been trying to make the "options" come from the db but haven't figured a way yet (PHP).
The plugin works by using a $_REQUEST to "dbactions.php?action=", and returns a JSON Array
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
which i presume goes to the "./js/jtable/jquery.jtable.min.js" script.
As far AFAIK/have read i cannot insert php code inside a js script so i'm pretty lost as to how i could make it dynamic. All relevant examples i've found are for asap.net instead of php.
I actually wanted to use a combobox instead of a radiobutton.
So far i've been using a view to show the data, but when i insert new data i insert directly to the table (which has 3 fields instead of the 4 shown), so i need to show the name field as an option but insert the id (plus 2 dates) into one of the tables that conform the view.
Anyone have any ideas on how to accomplish this?

In main file
<?php include 'file.php'; ?>
<script type="text/javascript">
active: {
title: 'Activo',
width: '5%',
type: 'radiobutton',
options: <?php echo $options ; ?>
</script>
In php file.php
<?php
//Open database connection
include 'Connections/localhost.php';
$result = mysql_query("SELECT
id,
option
FROM
options;");
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[$row['id']] = $row['option'];
}
//Return result to jTable
$options = json_encode( $rows);
//Close database connection
mysql_close($localhost);
?>

Related

jQuery datatable large dataset delay

My jQuery datatable is taking a little too long to display some data.
The query is simple. In the database, running the same query returns the same results in microseconds, regardless of size.
Here is how the query looks in my PHP script:
<?php
$searchCommodity = $_POST['commodity'];
$select = "SELECT COMM_CODE, KEY_COMM, MOD_DATE, MOD_USER FROM keyTable WHERE KEY_COMM = '$searchCommodity'";
$query = mysqli_query($dbc, $select);
$out = array();
while($row = $query->fetch_assoc())
{
$out[] = $row;
}
echo json_encode($out);
?>
Most of the data returned is less than 1000 records. But there are a few that return more than 10K to 20K records.
This causes a delay in which if the user is using Firefox, they will receive the "A web page is slowing down your browser. What would you like to do?" error message where they have to select 'Stop' or 'Wait'.
Back in my jQuery, here is how I'm sending the parameter to the PHP script:
$('#commoditySelect').on('change', function()
{
var commodity = $('#commoditySelect').val();
$.post('api/searchKeyComms.php', {commodity:commodity}, function(data)
{
var table = $('#example1').DataTable();
table.clear();
table.search('').draw();
var obj = JSON.parse(data);
obj.forEach(function(item)
{
table.row.add([item.COMM_CODE, item.KEY_COMM, item.MOD_DATE, item.MOD_USER]);
});
table.draw();
});
});
On the main HTML page, near the bottom, I set the datatable like this:
$('#example1').DataTable({
"dataType": "json",
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 550,
"scrollX": true,
"bDestroy": true,
"stateSave": true
});
Is there anything that I can add/change to any of the code above that will improve the performance of the rendering of the datatable?
I found this page: https://datatables.net/forums/discussion/2651/alternative-server-side-php-script
But I am not doing any concatenations. As stated above, it's a simple query that I'm using, and in the database, the data is returned quickly.
I even found this page: rendering large server-side datasets in jquery datatables
But the only thing I got from that page is that datatables are not made for large datasets. 20K doesn't seem too large.
Why loop on your $out array since your $row is already an associative array.. No need to loop.. ^_^
<?php
$searchCommodity = $_POST['commodity'];
$select = "SELECT COMM_CODE, KEY_COMM, MOD_DATE, MOD_USER FROM keyTable WHERE KEY_COMM = '$searchCommodity'";
$query = mysqli_query($dbc, $select);
$row = $query->fetch_assoc()
echo json_encode($row);
?>

jQueryUI autocomplete JSON not returning expected data

Using jQueryUI autocomplete to search a MySQL database. When user presses enter in the search field, I want to populate a div with the result(s) returned from DB.
The code works and does return an autocomplete list of suggestions.
However, the JSON data returned in the select: function is not what I expected.
In the PHP code sample below, the query requests all fields from the database related to each title matched by the query. There should have been other fields, like author, bid, isbn, genre, etc. -- however, only the title field was returned.
Google Chrome's console looks like this:
Object {item: Object}
item: Object
label: "Much Obliged Jeeves"
value: "Much Obliged Jeeves"
__proto__: Object
Object {label: "Much Obliged Jeeves", value: "Much Obliged Jeeves"}
Where are the other fields?
My jQuery:
$('#srxbks').autocomplete({
source: "autocomplete_test.php",
minLength: 1,
select: function( event, ui ) {
console.log(ui);
console.log(ui.item);
console.log(ui.item.label);
//Not working:
var out = 'Title: ' + ui.item.title + '<br>';
out += 'Author: ' + ui.item.author + '<br>';
$('.booksTableDIV').val(out);
}
});
My PHP:
<?php
include 'connect.php';
$term = strip_tags($_GET['term']);//retrieve search term sent by autocomplete
$qstring = "SELECT * FROM `books` WHERE `title` LIKE '%" .$term. "%'";
$query = mysql_query($qstring) or die(mysql_error());
while ($row = mysql_fetch_array($query)) {
$row['title']=htmlentities(stripslashes($row['title']));
$row['bid']=(int)$row['bid'];
$row_set[] = $row['title'];
}
echo json_encode($row_set);
You just need to be sure all your variables are included in the returning array. Your PHP is the part having an issue, your are not transferring the variables to JSON correctly. Your jQuery is fine. The following is what you need to do for each extra variable you wish to send back to your jQuery.
// Initialize your variables here
$returns = array();
$i = 0;
while ($row = mysql_fetch_array($query)) {
// Format your variables here
$row['title']=htmlentities(stripslashes($row['title']));
$row['bid']=(int)$row['bid'];
// Enter results into JSON array here
$returns[$i]['title'] = $row['title'];
$returns[$i]['bid'] = $row['bid'];
$i++;
}
echo json_encode($returns);

Error with my dojo ajax php request

Im trying to use a dojo ajax function to call a PHP file that then returns the contents of a DB table in JSON format.
My function:
var _getWeatherInfo = function(){
dojo.xhrget({
url: "PHP/weather.php?ntown=" + _ntown,
handleAs: "json",
timeout: 5000,
load: function(responce, details) {
_updateWeathertData
},
error: function(error_msg, details) {
_handleError(error_msg);
}
});
}
My PHP:
<?php include('configHome.php'); ?>
<?php
$ntown = $_GET['ntown'];
$weather = array();
$query="SELECT * FROM `weather` WHERE `town` = '$ntown'";
$result=mysql_query($query);
while($row = mysql_fetch_row($result)) {
$weather[] = $row[0];
}
echo json_encode($weather);
mysql_close();
?>
When using this code I am getting an error message saying that "$ntown = $_GET['ntown'];" is an undefined index. I have tried removing the index all together and using an actual value in the select statement (i.e. SELECT * FROM weather WHERE town = 'Auckland') but all I get back is the value i enter ["Auckland"], and not the 3 other values that are meant to be returned, ["Auckland", "Sunny", "8", "14"].
Any ideas? I can try add more info if needed. Thanks!
There are some other issues with your code, but to get to the one you are asking the question about. You have this:
while($row = mysql_fetch_row($result)) {
$weather[] = $row[0];
}
What you are doing is just taking the first value of the row (of which there is probably only one, and just sending that back. This is what you need:
$weather = mysql_fetch_row($result);

jquery autocomplete sql query list based on another input value

I have two autocomplete fields in my form. I populate the first field's list by using the following code...
$result = mysql_query("SELECT * FROM exercise_strength");
$arr_autoCompleteExerciseStr=array();
$s=0;
while($row = mysql_fetch_array($result)){
$autoCompleteExerciseStr = "\"".ucfirst($row['exercise'])."\", ";
$arr_autoCompleteExerciseStr[$s] = $autoCompleteExerciseStr;
$s++;
}
and...
$(function() {
var availableTags = [
<?php for($k=0; $k<sizeof($arr_autoCompleteExerciseStr); $k++) {echo $arr_autoCompleteExerciseStr[$k]; } ?>
];
$( "#inputExercise" ).autocomplete({
source: availableTags,
minLength: 0
});
$( "#inputExercise" ).focus(function(){
$(this).autocomplete("search");
});
});
The same code with a different mysql_query is used for the other field. What I want to do is change the list of the second field based on what's typed in the first. For instance, if the user types Chest in the first field, a list of relevant Exercises is shown in the second field, selected from my sql database.
What is the best way to do this?
I would prefer if I wouldn't have to leave the page, cause then the user have to refill the rest of the form..
Please help! :)
-- UPDATE --
Based on your advice about JSON my code now looks like this.
Script:
$(document).ready(function(){
$.post('json_exercise.php', { /**/ }, showExercise, "text");
});
function showExercise(res){
var list = JSON.parse(res);
$("#inputExercise").autocomplete({
source: list,
minLength: 0
});
$( "#inputExercise" ).focus(function(){
$(this).autocomplete("search");
});
}
PHP file:
$con = mysql_connect(***);
if (!$con) {die('Could not connect: ' . mysql_error());}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM exercise_strength");
$i = 0;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
//add the row to the $chat array at specific index of $i
$exercise[$i] = $row['exercise'];
$i += 1;
}
echo json_encode($exercise);
Now I just need to change the php filed based on whats selected in the first autocomplete field.
If you want to autocomplete based on results from a SQL query without having to leave the page, you might want to look into AJAX and JSON.
Also, please use PDO instead of the mysql_* functions for interfacing with DBMS's with PHP.

Ajax Printing Database Records to Multiple Fields

I currently have code which will pull the first element from a database record and print it in an output box.
What is the easiest way to print the rest of the elements of that record to the other relevant output boxes?
My PHP file takes an 'id' specified by the user.
$id = $_POST['id'];
$query = "SELECT * FROM Customers WHERE ID = $id";
$result= mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
echo $row[1];
}
}
And this is the code in the HTML file
jQuery(document).ready(function(){
jQuery("input.myid").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
var search_val=jQuery("input.myid").val();
jQuery.post("find.php", {id : search_val}, function(data){
if (data.length>0){
jQuery("input.fname").val(data);
}
});
}
The code takes the id ('myid') and prints to a text box named 'fname'.
I find it easier to json_encode the whole thing (record I mean) and use something like jquery.populate which basically takes an object and fills a form with it (all fields it can find which names' match properties from the object).
I hope this makes sense.

Categories