I have a site where I can update my Database. In the same page I also have a tabel with the most importent information in the database. This tabel is generated by a php while loop, and at the end of each row I have a Edit-button and a Delete-button. But I want to have a confirmation to the deletebutton. But I dont knopw how..
This is my code:
mysql_connect("localhost","user","pass") or die (mysql_error());
mysql_select_db("kalender") or die(mysql_error());
$data = mysql_query("SELECT * FROM event where datum > now() ORDER BY `pub` DESC LIMIT 0, 40") or die(mysql_error());
echo '<table>';
echo '<tr>';
echo '<th>Nr</th> <th>V.</th> <th>Tid</th><th>Dag</th><th>Datum</th><th>Ă„ndra</th><th>Ta bort</th>';
echo '</tr><tr>';
while($info = mysql_fetch_array( $data))
{
$eventTime=$info['datum'];
$tid= strtotime($eventTime);
echo '<td width="20px">' .$info['id'] . '</td>';
echo '<td width="20px">' .$info['vecka'] . '</td>';
echo '<td width="40px">' .date("H:i", $tid) . '</td>';
echo '<td width="40px">'.$info['dag'] . '</td>';
echo '<td width="50px">' .date("j M", $tid) . '</td>';
echo '<td width="70px"><button id="checkoutbutton" type="button"><Edit</button></td>';
echo '<td width="70px"><button id="checkoutbutton" type="button">Delete</button></td></tr>';
}
echo '</table>';
Please help me!
You try this.
In PHP Script:
Update this in while loop
...
...
$tempId = $info['id'];
echo "<td width='70px'><a href='javascript:;' onClick='go_edit($tempId);'><input type='button' value='Edit'/></a></td>";
echo "<td width='70px'><a href='javascript:;' onClick='go_del($tempId);'><input type='button' value='Delete'/></a></td>";
...
...
In Javascript:
Add these functions in under php script
<script>
function go_edit(id) {
window.location.href = "http://kalend.mizgalski.se/update.php?id="+id;
}
function go_del(id) {
var choice = confirm('Are you sure want to delete?');
if(choice) {
window.location.href = "http://kalend.mizgalski.se/delete?id="+id;
}
}
</script>
You can do confirmation using javascript on the client side before sending data to the server
Related
I have a problem when I'm trying to get the contents of a JavaScript Array and pass its value to a PHP Array Variable.
What I'm doing is that, when a user clicks a button, the value of the item clicked will be added to the javascript array and every time the javascript array updates, the PHP variable will also update and so the contents of the div displaying the contents of the PHP array. I'm not using forms for this matter but buttons
However, when I try to use the json_decode function to get the values of a JavaScript array, it's giving me a Message: undefined index: data error
I'm a beginner in JavaScript, jQuery and AJAX so please bear with me
This is my code:
<script>
// ARRAY VARIABLE WHERE ITEM VALUES WILL BE STORED
var food_item = new Array();
// FUNCTION TO BE TRIGGERED WHEN USER CLICKED THE BUTTON, GET THE ITEM'S VALUE AND ADD IT TO ARRAY
function addToTray(data){
food_item.push(document.getElementById(data).value);
dataString = food_item; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "main",
data: {data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
}
</script>
<body>
...
// LINE OF CODE RESPONSIBLE FOR FETCHING JAVASCRIPT ARRAY VALUES
$this->session->userdata['food_tray'] = json_decode($_POST['data']);
// DIV TO BE UPDATED
<div class="col-md-3 food-tray" id="food-items" style="margin-top: 7%">
<!--FOOD TRAY-->
<div class="panel-heading">
<h3 class="ft-header">Food Tray</h3>
</div>
<div class="panel-body">
<?php
$count_fi = count($this->session->userdata('food_tray'));
echo "<p>Your Items (" . $count_fi . ")</p>";
if($count_fi == 0){
echo "<p class='no-avail-list'>NO ITEMS ADDED IN FOOD TRAY</p>";
}else{
echo "<table class='table borderless'>";
for($i = 0; $i < $count_fi; $i++){
echo "<tr>";
echo "<td>" . $this->session->userdata['food_tray'][$i] . "</td>";
echo "<td>P 200.00</td>";
echo "<td><form method='post'><input type='number' name='qty' min='1' max='100' value='1'/></form></td>";
echo "</tr>";
}
echo "</table>";
echo "<a href='' class='btn btn-success' data-toggle='modal' data-target='#myModal'>
Add Friend</a>";
echo "<a href='".base_url()."index.php/CheckOut' class='btn btn-warning'>Proceed to Checkout</a>";
}
?>
</div>
</div>
...
<?php
foreach($query->result() as $row){
echo "<div class='col-lg-7'>";
echo "<div class='thumbnail'>";
$file_name = strtolower(preg_replace('/[^A-Za-z0-9\-.]/', '', $row->name));
/*if(file_exists(FCPATH . '/assets/images/main/food/' . $file_name . '.jpg')){
echo "<img src='".base_url()."/assets/images/main/food/".$file_name.".jpg' alt='' width='320px' height='100px'>";
}else{
echo "<img src='http://placehold.it/320x150' alt=''>";
}*/
echo "<img src='http://placehold.it/320x150' alt=''>";
echo "<div class='caption'>";
echo "<h5 class='pull-right'>₱ " . $row->price . "</h5>";
echo "<h5><a href='#'>" . $row->name . "</a></h5>";
echo "<h5>Calorie Count : " . ($row->calorie_count == NULL ? "Not Available" : $row->calorie_count) . "</h5>";
// BUTTON FOR `addToTray()` FUNCTION
echo "<button class='btn btn-primary' id='".$row->id."' value='".$row->name."' style='width:100%' onclick='addToTray(".$row->id.")'>Add to Tray</button>";
// var_dump($row->name);
echo "</div>";
echo "</div>";
echo "</div>";
}
?>
</body>
Anyone who knows how to solve this problem? Any help would be appreciated.
create your session as
$array = array ('food_tray' => json_decode($javascriptarray));
$this->session->set_userdata($array);
check if your javascript libraries are loaded in sources tab.
I have an AJAX function that calls a php function to search a mysql database. The script fires off on keyup and the problem is on the first key press the html content is updated but it will not update after the initial keyup event
How do I make the page continuously update the html content with the new data that is coming in after every keyup.
My AJAX function,
var searchPath = "<?php echo $searchPath ?>";
$("#itemID").keyup(function (){
var itemID = $(this).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
});
And this is the php behind it all,
<?php
require_once ('Dbconfig.php');
$sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";
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>';
}
}
?>
I have a selector wich gets information from the database. But when my database table is empty, the selector still shows up like this:
However, when my database is empty. I don't want to show the selector. but a message that says something like: Database is empty! Add something.
My code for the selector:
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
The function:
function selector() {
$sql = "SELECT train_name, train_id FROM train_information ORDER BY train_name";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Got this now:
$results = $database->Selector();
if(count($results) > 0) {
//Form etc here//
}else echo "nope";
It is working now! :D
I am trying to have an onClick event to open each instance of the edit link that links to the specific ID in my database so that you can just click to open a new window edit what you have to and not have to browse away from the main page.
I can get get the link to work in a regular href and a target blank, but with the onclick event it doesn't appear to work properly and I need to set the parameters for the window. I have searched around and tried many solutions to other similar problems but I just can't figure out a solution. Is this even possible?
Here is the snippet of code I'm working with.
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['lname'] . '</td>';
echo '<td>' . $row['fname'] . '</td>';
echo '<td>' . $row['activity'] . '</td>';
echo '<td>' . $row['guests'] . '</td>';
echo '<td>' . $row['room'] . '</td>';
echo '<td>Edit</td>';
echo '<td><a href="delete.php?id=' . $row['id'] . '" >Delete</a></td>';
echo "</tr>";
Any assistance on this would be amazing, thanks in advance.
Try this:
echo "<td>Edit</td>";
echo "<td><a href='delete.php?id={$row['id']}' >Delete</a></td>";
Hello fellow programmers!
I'm working on a personal project (mainly to learn php/javascript) and have ran into an issue with redirection when clicking on a link. I have a bit of a strange situation on a tabbed page I've created and I think that may be what is causing my problem.
I'm trying to allow the user to click the (which due to css has made it look different than normal ) to redirect them to a new page with more details. I THINK that the second tag on my page is what is throwing me off because I have a form in it.
I have tried tons of different things like window.location.href="", location.href="", document.location="", etc... But the same thing always occurs. I am able to get both alert messages, so I know I am getting into my JavaScript (even when I put it into it's own .js file).
Anyway advice/help would be very helpful. Also, if anyone has a suggestion on cleaning this code up a bit, that would also be truly helpful.
Below is basically what I have.
Thanks in advance for your help!
<html>
<head>
<title>test site</title>
<link rel="stylesheet" href="test.css" type="text/css" media="screen" />
<script src="test.js" type="text/javascript"></script>
<script type="text/javascript">
function viewDetails(modelId){
alert(modelId);
window.location.href="new url?ModelID=" + modelId;
alert('redirecting would be way awesome...');
}
</script>
</head>
<body onload="load()">
<div id="tabbed_box_1" class="tabbed_box">
<h4>Navigation Tabs<small>Select a tab</small></h4>
<div class="tabbed_area">
<?php
mysql_connect('host','user','password');
mysql_select_db("database");
echo "<ul class='tabs'>";
echo "<li><a href='javascript:tabSwitch(1, 2);' id='tab_1' class='active'>Inventory</a></li>";
echo "<li><a href='javascript:tabSwitch(2, 2);' id='tab_2' >Add Project</a></li>";
echo "</ul>";
echo "<div id='content_1' class='content'>";
echo "<ul>";
$modelsSQL = "SELECT * FROM Model ORDER BY Name";
$modelsResult = mysql_query($modelsSQL);
while ($modelRow = mysql_fetch_array($modelsResult)){
$modelID = $modelRow[0];
$sqlAvailCount = "SELECT * FROM Project WHERE ModelID = " . $modelID . " AND Sold = 0";
$sqlSoldCount = "SELECT * FROM Project WHERE ModelID = " . $modelID . " AND Sold = 1";
$resultAvailCount = mysql_query($sqlAvailCount);
$resultSoldCount = mysql_query($sqlSoldCount);
$rowAvailCount = mysql_num_rows($resultAvailCount);
$rowSoldCount = mysql_num_rows($resultSoldCount);
echo "<li><a href='' onclick='javascript:viewDetails($modelID);'>" . $modelRow[1] . "<small>in stock: <value>"
. $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
}
echo "</ul>";
echo "</div>";
echo "<div id='content_2' class='content'>";
echo "<form action='project_insert.php' method='post' name='projectAddForm'>";
echo "<table cellpadding='5'>";
// Project Model Selection
echo "<tr><td>";
echo "<label for='model'>Model</label>";
echo "</td><td>";
echo "<select name='model' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$modelListSQL = "SELECT * FROM Model ORDER BY Name";
$modelListResult = mysql_query($modelListSQL);
while ($modelListRow = mysql_fetch_array($modelListResult)){
echo "<option value='" . $modelListRow['ID'] . "'>" . $modelListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Material Selection
echo "<tr><td>";
echo "<label for='material'>material</label>";
echo "</td><td>";
echo "<select name='material' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$materialListSQL = "SELECT * FROM Material ORDER BY Name";
$materialListResult = mysql_query($materialListSQL);
while ($materialListRow = mysql_fetch_array($materialListResult)){
echo "<option value='" . $materialListRow['ID'] . "'>" . $materialListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Finish Selection
echo "<tr><td>";
echo "<label for='finish'>finish</label>";
echo "</td><td>";
echo "<select name='finish' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$finishListSQL = "SELECT * FROM Finish ORDER BY Name";
$finishListResult = mysql_query($finishListSQL);
while ($finishListRow = mysql_fetch_array($finishListResult))
{
echo "<option value='" . $finishListRow['ID'] . "'>" . $finishListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Craftsman Selection
echo "<tr><td>";
echo "<label for='craftsman'>craftsman</label>";
echo "</td><td>";
echo "<select name='craftsman' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$craftsmanListSQL = "SELECT * FROM Craftsman ORDER BY FirstName";
$craftsmanListResult = mysql_query($craftsmanListSQL);
while ($craftsmanListRow = mysql_fetch_array($craftsmanListResult)){
echo "<option value='" . $craftsmanListRow['ID'] . "'>" . $craftsmanListRow['FirstName'] . " " . $craftsmanListRow['LastName'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
//Project Description
echo "<tr><td>";
echo "<label for='description'>Description</label>";
echo "</td><td>";
echo "<input type='text' name='description' id='textArea' style='width:250px'>";
echo "</td></tr>";
// Project Selling Price
echo "<tr><td>";
echo "<label for='price'>Price</label>";
echo "</td><td>";
echo "<input id='price' name='price' type='number' style='width:150px'>";
echo "</td></tr>";
// Project Completion Date
echo "<tr><td>";
echo "<label for='date'>Finish Date</label>";
echo "</td><td>";
$dateArray = getdate();
$month = $dateArray[mon];
$day = $dateArray[mday];
if ($month < 10){
$month = '0' . $dateArray[mon];
}
if ($day < 10){
$day = '0' . $dateArray[mday];
}
$todaysDate = $dateArray[year] . '-' . $month . '-' . $day;
echo "<input type='date' name='date' value='" . $todaysDate . "' style='width:150px'>";
echo "</td></tr>";
// Buttons
echo "<tr><td align='center'>";
echo "<input type='button' name='Save' value='Save' onclick='javascript:validateAndSubmit(this.form);' style='width:100px'>";
echo "</td><td align='center'>";
echo "<input type='button' name='Cancel' value='Cancel' onclick='javascript:cancelEntry();' style='width:100px'>";
echo "</td></tr>";
echo "</table>";
echo "</form>";
echo "</div>";
?>
</div>
</div>
</body>
window.location.href may not trigger reload in some browsers and cases..
You should add a reload after
like this:
window.location.href = '/foo/bar/';
window.locaton.reload(true)
But, some browsers delay milliseconds to perform location.href set. In this cases the window.location.reload(true) may complete before this.
Therefore, add a timeout in reload:
window.location.href = '/foo/bar/';
setTimeout('window.locaton.reload(true)', 500);
works in all browsers for me
Good morning! I found the cause of my problem this morning and have been able to resolve the issue. The problem I was causing is because I am using the tag (stylized by css) to display the information, with an onclick event to call my JS code to redirect. Within the tag I had the href='', thinking that the JS would override that functionality, it doesn't!
Removing the href='' from the tag resolved the issue and allowed me to redirect to the new page. A second solution is to use my php code to dynamically create the href link within the tag.
echo "<li><a onclick='viewDetails($modelID);'>" . $modelRow[1] . "<small>in stock: <value>" . $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
OR
echo "<li><a href='inventorydetails.php?ModelID=" . $modelID . "'>" . $modelRow[1] . "<small>in stock: <value>" . $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
I think I will go with the second example for two reasons. First, it provides the link icon when hovering (which I know I can add through css, but this is easier. Second, less JS code.
I thank you for all your help in resolving this!