Ajax call to alter MySQL SELECT query - javascript

I'm working on a web app to keep track of recent expenses. I'd like the user to be able to select 4 different time periods which displays different data. When a user first lands on the page, the "overall" data would show by default. When a range is selected by the user, i'd like to use an ajax call to take the data-range and alter the mysql query. My experience with ajax is low, and i'm curious as to how this would be done.
Here is my HTML (echoed in PHP):
echo "<section class='range-container'>" .
"<ul class='overview-range'>" .
"<li data-range='overall'>Overall</li>" .
"<li data-range='$currentYear'>Year</li>" .
"<li data-range='$currentMonth'>Month</li>" .
"<li data-range='$currentDay'>Day</li>" .
"</ul>" .
"</section>";
include $_SERVER['DOCUMENT_ROOT'] . '/ajax/overview.php';
The overview.php file: For this example I only have the DAY(date) option in the query.
<?php
if ($_POST['range']) {
$currentTime = $_POST['range'];
} else {
$currentTime = '0';
}
//Overview Query
$sqloverview = $db->prepare('SELECT SUM(amount), trans_type
FROM transactions
WHERE (amount > 0 AND DAY(date) = :currentTime) OR
amount > 0
GROUP BY trans_type
ORDER BY trans_type DESC');
$sqloverview->execute(array(':currentTime' => sanitizeString($currentTime)));
$overviewRows = $sqloverview->num_rows;
?>
And the jQuery file:
$('.overview-range li').click(function() {
var range = $(this).attr('data-range');
$.ajax({
type: 'POST',
url: '/ajax/overview.php',
data: { range: range },
error: function() { alert("Unable to process this request."); },
success: function() {
alert('It was successful');
}
});
});
Would this be the correct way to go about this process? Or is there a better way other than ajax? Any help would be greatly appreciated!

Related

Showing JSON results neatly in a webpage

I am trying to figure out how to get JSON results and show them in a template I have built.
I have a page that has checkboxes, when the check boxes are checked the script refines the search. So far I have a created a script that checks to see if a user has checked a box. A separate PHP script then runs a query on an SQL database - returning the results live.
I have so far managed to get this to return the results as JSON in the console and 'stringified' in the webpage.
How do I take the JSON results and show them neatly on the webpage? i.e
Name: 'name', Locale: 'locale'
Name: 'name', Locale: 'locale'
Name: 'name', Locale: 'locale'
This is my Ajax code at the moment:
var ajaxResult=[];
function updateEmployees(opts){
$.ajax({
type: "POST",
url: "search.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success:function(data) {
ajaxResult.push(data);
}
});
}
This is the javascript checkbox code:
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
console.log(ajaxResult)
var myJSON = JSON.stringify(ajaxResult);
document.getElementById("demo").innerHTML = myJSON;
});
updateEmployees();
Thanks for your help in advance. I've spent a couple of days trying to figure this out!
EDIT - PHP script I am using
<?php
$pdo = new PDO('mysql:host=localhost;dbname=myDB', '**', '**');
$select = 'SELECT name, locale, website';
$from = ' FROM theList';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
if (in_array("pub", $opts)){
$where .= " AND pub = 1";
}
if (in_array("bar", $opts)){
$where .= " AND bar = 1";
}
if (in_array("restaurant", $opts)){
$where .= " AND restaurant = 1";
}
if (in_array("club", $opts)){
$where .= " AND club = 1";
}
if (in_array("locale-a", $opts)){
$where .= " AND locale = 'south'";
}
if (in_array("locale-b", $opts)){
$where .= " AND locale = 'west'";
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
There are a couple of things going on here.
1. Your results set will grow every time a checkbox changes since you're pushing a new element to the results array. If you're fetching the full dataset every time, this is unnecessary.
2. AJAX performs asynchronously, your code is written with expectation that it's synchronous.
This...
console.log(ajaxResult)
var myJSON = JSON.stringify(ajaxResult);
document.getElementById("demo").innerHTML = myJSON;
});
updateEmployees();
...is expecting data that doesn't exist yet.
The process goes:
*user clicks checkbox*
submit selections to server to query database
wait for response
handle result when response received
However, the above code is already on step 4 before step 3 has completed. You need to tell the ajax call what to do when it's received the response:
// send selections to server
function updateEmployees(){
$.ajax({
type: "POST",
url: "search.php",
dataType : 'json',
cache: false,
// serialize checked boxes to a query string like "check1=on&check2=on"
data: $('input:checkbox').serialize(),
success: handleResults
});
}
// handle filtered results
function handleResults(data) {
// same as document.getElementById('demo').innerHTML
$('#demo').html(
JSON.stringify(data)
);
}
// add events to checkboxes
$('input:checkbox').change(updateEmployees);
try to use stringify method with these params:
var myJSON = JSON.stringify(ajaxResult, null, 2);

Page Scrolling Effect With Ajax How Data Is Loaded Into The Page

I am loading data from a mysql table into a html table. I am using AJAX php Jquery to accomplish this. I need to make sure that the way I built this will work regardless of how much data is in the table.
Right now I am working with a table that is 5000 rows long but there will eventually be 88000 rows in this table.
I know if I load all the data on page load this could end up bogging down the server and the load time of the page.
My question is the way my logic is now will it load all the results into the $results and only query the needed amount of rows because it is paginated. Or even though it is paginated is my webpage taking every row in the whole database for load time.
if the whole table is being loaded how can I change the query to only load the data when needed. It loads on page scroll.
Also I need to write a search function. Since the data is paginated would I search the data in $results or query the table with separate search functions? Which way would provide less load times which would cause a bad experience for my user?
The AjAX
<script type="text/javascript">
jQuery(document).ready(function($) {
var busy = true;
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
(function($) {
$(document).ready(function() {
if (busy == true) {
displayRecords(limit, offset);
busy = false;
}
});
})( jQuery );
(function($) {
$(document).ready(function() {
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#productResults").height() && !busy) {
offset = limit + offset;
displayRecords(limit, offset);
}
});
});
})( jQuery );
});
</script>
This is how I am querying the database
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 5;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
By transferring a JSON object from the server the limit, offset and html (and maybe others lime status_messsage, etc.) values could be transferred to the client at the same time.
On the client side I meant something like this:
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#productResults").append(json.html); // corr to $output['html']
$('#loader_image').hide();
if (json.html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
...and on the server side:
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
// Make sure to handle invalid offset values properly,
// as they are not validated from the last request.
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
$output['html'] .= $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
$output['html'] .= '<tr class="invent">';
$output['html'] .= '<td>' . $res['wuno_product'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_alternates'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_description'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_onhand'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_condition'] . '</td>';
$output['html'] .= '</tr>';
}
}
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);
I do this exact thing you want on my site http://www.flixnetforme.com/ where as you can see as you scroll to the bottom of the page the next set of records is loaded. I have over 150,000 records but it only loads 36 at a time when the user scrolls to the bottom of the page.
The way you want to do this is is by loading your first initial records through ajax and not hardcode them into the page.
index.php
$(document).ready(function(){
var last_id;
if (last_id === undefined) {
genres = $("#genres").val();
$.ajax({
type: "POST",
url: "includes/getmorefirst.php?",
data: "genres="+ genres,
success: function(data) {
$( ".append" ).append(data);
}
});
};
};
<html><div class="append"></div></html>
In this example when the user gets to the page and is loaded it calls getmorefirst.php and return the first records.
getmorefirst.php is a file that will load the first set amount of records you want to show when the user gets to the page. In my case I load 36 records at a time when a user scrolls to the bottom of my page.
getmorefirst.php
$sql = "SELECT * FROM table ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
The last_id div is important so that ajax will know the last record sent and which one to pick up after when it loads the next set of 36 records.
.append is the div where I am appending the data from ajax when the user its the bottom.
.last_id is your key to knowing how to load the next set of records. In whatever order you send the records back its important that ajax knows the last ID of the record loaded so it knows where to start loading the next time ajax calls for more records. In my case when the users scrolls to the bottom of the page.
when user scrolls to bottom of index.php
if($(window).scrollTop() === $(document).height() - $(window).height()) {
last_id = $(".last_id:last").attr("id");
$.ajax({
type: "POST",
url: "includes/getmore.php?",
data: "last_id="+ last_id,
success: function(data) {
$( ".append" ).append(data);
}
});
return false;
};
};
last_id = $(".last_id:last").attr("id"); will get the last ID sent.
data: "last_id="+ last_id, will send the last id to getmore.php so it knows the last id of the record sent.
getmore.php
$sql = "SELECT * FROM table WHERE ID > '$last_id' ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
As you can see getmore.php will return the next 36 records but AFTER the last_id sent.
Hope this make sense and gives you a start.
Here is a reduced example of the JSON / AJAX mechanism that I have tested:
HTML (file test.html)
<html>
<head>
<!-- THE NEXT LINE MUST BE MODIFIED -->
<script src="../jquery-1.4.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var limit = 5;
var offset = 0;
// THE NEXT LINE MUST BE MODIFIED
var assetPath = "http://www.example.com/stackoverflow/test.php"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
async: true,
cache: false,
beforeSend: function() {
$("#content").html("");
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#content").html(json.html);
window.busy = false;
}
});
}
</script>
</head>
<body>
<div id="content"></div>
<div onclick="displayRecords(limit,offset); return false;" style="cursor:pointer">Click to Call</div>
</body>
</html>
PHP (file test.php)
<?php
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
$output['html'] .= '<span style="color:red;">limit='.$output['lim'].', offset='.$output['offs'].'</span>';
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);
Result
1st time
2nd time
nth time

Accessing JSON results from jQuery Ajax

I'm working on a web application to maintain the administration for a restaurant kind of type. The idea is to make new orders, put order items in that, check finance overviews etc...
I've also got a function to see all the orders in a list, when you select one of them, the order data (such as the name, emailadress, location of the customer) shows up in a another element inside the document.
I'm doing that with this function, every tr inside the has been given a custom attribute; the order_id. When selecting that, a class is given, called selectedRow.
function select_order(order) {
var item = $(order);
if (!item.hasClass("selectedRow")) {
if (!selectedOrderInformation.is(":visible")) {
switchScreen(selectedOrderInformation, financeOverview);
}
item.parent().find(".selectedRow").removeClass("selectedRow");
item.addClass("selectedRow");
selectedOrderInformation.html("loading......");
$.ajax({
url: "includes/functions/select-order.php",
type: "get",
data: {order_id: item.attr("data-order-index")},
success: function (data) {
selectedOrderInformation.html(data);
$("#delete-order-btn").prop("disabled", false);
}
});
} else {
console.log("DEBUG: Row is already selected");
}
}
The usage of that function is by doing this:
$("#list tbody tr").click(function () {
select_order(this);
});
At the first place, i was deploying all the HTML data via PHP. This took a pretty long time, it could take from 500ms to about 1 second. In my opinion thats pretty long.
I was doing that like this (select-order.php):
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
while ($row = mysqli_fetch_array($order_data)) {
echo "<h1>Klant informatie</h1>";
echo "<p>Voornaam: " . $row['first_name'] . "</p>";
echo "<p>Achternaam: " . $row['last_name'] . "</p>";
echo "<p>Emailadres: " . $row['email_adress'] . "</p>";
echo "<p>Klant informatie: " . $row['customer_info'] . "</p>";
echo "<br>";
echo "<h1>Bestellingsinformatie</h1>";
echo "<p>Order informatie: " . $row['order_info'] . "</p>";
echo "<p>Locatie: " . $row['location'] . "</p>";
echo "<p>Gemaakt op: " . $row['created'] . "</p>";
}
echo "<br>";
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>Product naam</th>";
echo "<th>Hoeveelheid</th>";
echo "</tr>";
echo "</thead>";
while ($row = mysqli_fetch_array($order_items)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "</tr>";
}
echo "</table>";
exit;
}
This goes together with the Database class with all the functions:
class Database extends mysqli
{
// single instance of self shared among all instances
private static $instance = null;
private $databaseHost = "";
private $databaseUser = "";
private $databasePassword = "";
private $databaseName = "";
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}
function __construct() {
parent::__construct($this->databaseHost, $this->databaseUser, $this->databasePassword, $this->databaseName);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
parent::set_charset('utf-8');
}
function get_all_data_by_order_id($order_id) {
$query = "SELECT customers.first_name,
customers.last_name,
customers.email_adress,
customers.customer_info,
orders.order_info,
orders.total_price,
orders.location,
orders.created
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id
WHERE orders.id = {$order_id}";
return $this->query($query);
}
function get_order_items_by_order_id($order_id) {
$query = "SELECT `products`.`name`, `orders-items`.`quantity` FROM `orders-items`\n" . "INNER JOIN `products`ON `orders-items`.`products_id` = `products`.`id`\n" . "WHERE order_id=" . $order_id;
return $this->query($query);
}
}
Now someone told me i could better translate the data into json and return that, so i did this:
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
$rows = array();
while ($row = mysqli_fetch_array($order_data)) {
$rows[] = $row;
}
return json_encode($rows);
exit;
}
But as expected, nothing really happened. So i tried changing the javascript to this (trying it as a array because i'm returning it that way?), to deploy one piece of data:
$.ajax({
url: "includes/functions/select-order.php",
type: "get",
data: {order_id: item.attr("data-order-index")},
success: function (data) {
selectedOrderInformation.html(data['first_name']);
}
});
But that didn't work aswell.
Problems
The previous PHP code was to slow, so i had to find another way.
When trying to deploy HTML into the other screen, it doesnt do anything. It stays on the 'loading...' screen, so the success function was'nt reached.
Question
How can my piece of code be changed so it will actually deploy parts of the data from the mysql database?
In your $.ajax() call you should define what type your response data is expected to be, by adding the following parameter to the call:
dataType: 'json'
Also, you should try echo json_encode($rows); your data instead of returning it.
**Edit: you are receiving an array of arrays, so your original referencing in the success callback won't suffice. Having another look at your MySQL part, If you are only expecting one row to be returned by your query, then you can change your PHP to:
$row = mysqli_fetch_array($order_data);
echo json_encode($row); // instead of $rows
instead of the while loop. That way your selectedOrderInformation.html(data['first_name']); will most likely work.
To clean your query up a bit:
$query = "SELECT p.name, ot.quantity FROM orders-items AS ot
LEFT JOIN products AS p ON ot.products_id = p.id
WHERE ot.order_id = " . $order_id;
You could also switch your INNER JOIN to a LEFT JOIN in your "get order data" function. An inner join is absolutely useless here, as you'll have all your data paired based on the foreign keys anyways.
I would try secluding some of the codebase: try commenting out the Database::getInstance() calls, and supplementing some testdata into the processes. To put it short, fake a returned response, by declaring a $row = array('first_name' => 'Joe', 'order_date' => '2014-08-29 11:11:52', ...); and returning that. If its way faster, then your database server might be the bottleneck. If its still slow, then 500ms - 1000ms is actually argueably code related, it might be other hardware aspects that cause the problem. Or for example, do you have your jQuery library loaded from a CDN, or locally?
**Edit: As #Debflav pointed out (and I've also touched upon the matter), that your queries could benefit from not being executed as simple queries, but transforming them into prepared statements. For the full story you could start checking out PHP.net : Prepared Statements, or to keep it short:
Prepared statements look almost just like your everyday query, however variables are not just concatenated into the query string, rather bindings are used.
You use the database handler's prepare function instead of query - with this method, you are requesting the MySQL server to inspect your query and optimize it for later use (which will come handy if you're doing the same query over and over again, just with a few varying values).
For more detailed insights on the mechanics of prepared statements and how to get the hang of it for efficiently utilizing it in your projects I recommend you research the topic a bit, but as a quick conversion for your example at hand, it would look like this:
function get_all_data_by_order_id($order_id) {
$query = "SELECT c.first_name, c.last_name, c.email_adress, c.customer_info,
o.order_info, o.total_price, o.location, o.created
FROM customers AS c
LEFT JOIN orders AS o ON c.id = o.customer_id
WHERE o.id = :order_id";
$query_params = array(
':order_id' => $order_id
);
$preparedStatement = $this->prepare($query);
return $preparedStatement->execute($query_params);
}
and
function get_order_items_by_order_id($order_id) {
$query = "SELECT p.name, ot.quantity FROM orders-items AS ot
LEFT JOIN products AS p ON ot.products_id = p.id
WHERE ot.order_id = :order_id;";
$query_params = array(
':order_id' => $order_id
);
$preparedStatement = $this->prepare($query);
return $preparedStatement->execute($query_params);
}
And to reflect on how you would build up your JSON response with data including the order headers and the connected order-items would be:
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
$orderObject = array();
$orderObject['header'] = mysqli_fetch_array($order_data);
$orderObject['items'] = array();
while ($orderedItem = mysqli_fetch_array($order_items)){
$orderObject['items'][] = $orderedItem;
}
echo json_encode($orderObject);
}
This way your jQuery could look something as follows:
....
success: function (data) {
selectedOrderInformation.html('<h3>' + data['header']['first_name'] + '</h3><ul>');
$.each(data['items'], function(i, item) {
selectedOrderInformation.append('<li>' + item['name'] + ' x ' + item['quantity'] + '</li>');
});
selectedOrderInformation.append('</ul>');
}
....

PHP is not reloaded automatically after processing

Hi I have a PHP file with data. The value is passed on to another php file which process it successfully. But the first php file does not refresh to update the new result. It have to do it manually. Can any one tell me where I'm wrong or what needs to be done. Please find my code below.
PHP code (1st page, index.php)
function display_tasks_from_table() //Displayes existing tasks from table
{
$conn = open_database_connection();
$sql = 'SELECT id, name FROM todolist';
mysql_select_db('todolist'); //Choosing the db is paramount
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<form class='showexistingtasks' name='showexistingtasks' action='remove_task.php' method='post' >";
while($row = mysql_fetch_assoc($retval))
{
echo "<input class='checkbox' type='checkbox' name='checkboxes{$row['id']}' value='{$row['name']}' onclick='respToChkbox()' >{$row['name']} <img src='images/show_options.gif' /><br>";
}
echo "</form>";
echo "<label id='removeerrormsg'></label>";
close_database_connection($conn);
}
Javascript code which finds the selected value:
var selVal; //global variable
function respToChkbox()
{
var inputElements = document.getElementsByTagName('input'),
input_len = inputElements.length;
for (var i = 0; i<input_len; i++)
{
if (inputElements[i].checked === true)
{
selVal = inputElements[i].value;
}
}
}
jQuery code which passes value to another page (remove_Task.php):
$(document).ready(function() {
$(".checkbox").click(function(){
$.ajax({
type: "POST",
url: "remove_task.php", //This is the current doc
data: {sel:selVal, remsubmit:"1"},
success: function(data){
//alert(selVal);
//console.log(data);
}
});
});
});
PHP code (2nd page, remove_task.php);
session_start();
error_reporting(E_ALL);ini_set('display_errors', 'On');
$task_to_remove = $_POST['sel'];
function remove_from_list() //Removes a selected task from DB
{
$db_connection = open_database_connection();
global $task_to_remove;
mysql_select_db('todolist');
$sql = "DELETE FROM todolist WHERE name = "."'".$task_to_remove."'";
if($task_to_remove!='' || $task_to_remove!=null)
{
mysql_query($sql, $db_connection);
}
close_database_connection($db_connection);
header("Location: index.php");
}
if($task_to_remove != "") {
remove_from_list();
}
The selected value is getting deleted but the display on index.php is not updated automatically. I have to manually refresh to see the updated result. Any help would be appreciated.
By calling header("Location: index.php"); you don't redirect main page. You sent an ajax request - you can think about it as of opening a new page at the background, so this code redirects that page to index.php.
The better way to solve your task is to return status to your success function and remove items which were deleted from the database.
success: function(data){
if(data.success){
//remove deleted items
}
}

PHP populate drop box with jquery

I have a script which fetches options from a script php to populate a drop down list on the main page.
Here's the javascript
<script>
//# this script uses jquery and ajax it is used to set the values in
$(document).ready(function(){
//# the time field whenever a day is selected.
$("#day").change(function() {
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
dataType : 'json'
success: function(data) {
//# $("#time").html(data);
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.timing + '</option>';
});
$('#timing').html(option);
}
});
});
});
</script>
Here's the php script which gets data from a database.
<?php
$con = mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query = "SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
//$res = array();
echo "<select name='timing' id='timing'>";
//Initialize the variable which passes over the array key values
$i = 0;
//Fetches an associative array of the row
$row = mysqli_fetch_assoc($result);
// Fetches an array of keys for the row.
$index = array_keys($row);
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
//array_push($res, $index[$i]);
json_encode($index[$i]);
echo "<option value='" . $index[$i]."'>" . $index[$i] . "</option>";
}
$i++;
}
echo json_encode($res);
echo "</select>";
?>
It's not working. I get an error from console saying missing '}' in javasrcipt on line
$("#day").change(function(){
I can't seem to find an error either.
You need to add a comma on the line above the one triggering the error :
dataType : 'json',
It's because you don't have a comma on the line above it...
It's hard to say where is problem, because you mixed things together. On Javascript side you expect JSON but on PHP side you generate HTML.
Use JSON for sending data between server and browser. Ensure that you actually generate valid JSON and only JSON.
This line does nothing (function returns value, but not modifies it)
json_encode($index[$i]);
This line does not make sense - variable $res is not initialized;
echo json_encode($res);

Categories