how to reload javascript function without reloading the whole page - javascript

Previously i found the solution for div here Stackoverflow link
this page talks about reloading a div but my problem is different
here is my index page
<?php
$message = "";
$minutes = "";
$limit = 2;
$effect = "";
$start = "";
$end = "";
require_once('db.php');
$query = mysql_query("SELECT message FROM kioskmessage where recNo = 1");
$row = mysql_fetch_assoc($query);
$message = $row['message'];
?>
<?php
$query = mysql_query("SELECT effect FROM kioskmessage where recNo = 1");
$row = mysql_fetch_assoc($query);
$effect = $row['effect'];
if($effect == "blink")
{
$start = '<p class="blink_text">';
$end = "</p>";
}
elseif($effect == "scrolling")
{
$start = "<marquee>";
$end = "</marquee>";
}
else
{
$start = '<p class="normalmessage">';
$end = "</p>";
}
?>
<?php
$query = mysql_query("select minutes from getminutes where id = 1");
$row = mysql_fetch_assoc($query);
$minutes = $row['minutes'];
?>
<html>
<header>
<div class="img"> <img src="images/logo.png">
</div>
<div class="container" id="nav">
<p id="time"></p>
</div>
</header>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TT</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="style/style.css" rel="stylesheet" type="text/css">
<script>
document.body.style.zoom="95%"
</script>
<script>
function ins()
{
nextDepartures(<?=$minutes?>, <?=$limit?>);
nextDeparturesTrains(120);
nextDeparturesTrams(60);
startTime();
}
</script>
<script>
$(document).ready(
function() {
setInterval(ins(), 5000);
});
</script>
<script src="data.js"></script>
<script src="sprintf.js"></script>
<script type="text/javascript" src="2.0.0-crypto-sha1.js"></script>
<script type="text/javascript" src="2.0.0-hmac-min.js"></script>
</head>
<body onload="ins()">
<table class="table table-bordered table-stripped table-hover" id="depart" style="float:left; border: 1px solid black; width:30%;">
<thead>
<tr>
<td colspan="4" class="danger" style="text-align: center; font-weight: bold;">Buses Departing from this Stop</td>
<tr>
<tr>
<th>Bus No. & Name</th>
<th>Time</th>
<th>Remaining Mins</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- This table for train information-->
<table class="table table-bordered table-stripped table-hover" id="departTrains" style="float:left; border: 1px solid black; width:30%;">
<thead>
<tr>
<td colspan="4" class="danger" style="text-align: center; font-weight: bold;">Trains Departing from varios stations</td>
<tr>
<tr>
<th>Station</th>
<th>Destination</th>
<th>Time</th>
<th>Remaining Mins</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- This table for tram information-->
<table class="table table-bordered table-stripped table-hover" id="departTrams" style="float:left; border: 1px solid black; width:30%;">
<thead>
<tr>
<td colspan="4" class="danger" style="text-align: center; font-weight: bold;">Tram Departing from plenty road</td>
<tr>
<tr>
<th>Tram Name</th>
<th>Time</th>
<th>Remaining Mins</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<footer id="footer">
<?=$start?><?=$message?><?$end?>
</footer>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.js"></script>
</body>
</html>
Now i have a javascript function ins() which further have stored functions in it which sends data to the tables defined in the page with relevant information.
Also, i have a script defined in the page which i think could be the possible solution, but its not working
here is that script
<script>
$(document).ready(
function() {
setInterval(ins(), 5000);
});
</script>
this is the sample data which function ins() is pushing into tables on load the page

If you want to load the JavaScript function without reloading the Entire page you can follow up the AJAX structure and you can make the changes as per the requirement you need.
Since loading up of the JavaScript without reloading the page will perform good only if it is done in AJAX. If the process is done in AJAX it will load the particular div where you want to display the JS output as required.
You can use the ins() function in Ajax and you can reload the page as the success function so that it will load the content under the DIV what you have provided as the success div.

Related

How do i put a link in a table

I have a table on my website, which gets data from a database, in the table I have delete buttons on a row, I have just made the table searchable with jQuery, but now I can't figure out how to keep the delete buttons.
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta charset="utf-8">
<meta name="description" content="Inventar">
<meta name="author" content="Martin Eide Bjørndal">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="/src/css/style.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<button class="back" onclick="window.location='../'">
<img src="/src/icons/back.png">
</button> <!-- Tilbake knapp -->
<button class="ny_inventar" onclick="window.location='/admin/brukere/ny'">
<img src="/src/icons/add.png">
</button> <!-- Ny Bruker knapp -->
<div class="container-fluid" id="utskjekkcontainer">
<div class="row justify-content-center">
<div class="col-mv-10 bg-light mt-5 rounded p-3">
<h1 class="text-primary p-2">Brukere</h1>
<hr>
<div class="form-inline">
<label for="search" class="font-weight-bold lead text-dark">Søk</label>
<input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">
</div>
<hr>
<?php
include "../../src/fn/init.php";
$stmt=$conn->prepare("SELECT * FROM brukere");
$stmt->execute();
$result=$stmt->get_result();
?>
<table class="table table-hover table-light table-striped" id="table_data">
<thead>
<tr>
<th>#</th>
<th>Fornavn</th>
<th>Etternavn</th>
<th>Utskjekket</th>
<th>Admin</th>
<th>Slett</th>
</tr>
</thead>
<tbody>
<?php while($row=$result->fetch_assoc()){ ?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["fornavn"]; ?></td>
<td><?php echo $row["etternavn"]; ?></td>
<td><?php echo $row["utskjekket"]; ?></td>
<td><?php echo $row["is_admin"]; ?></td>
<td>Slett</td>
</tr>
<?php }
$conn->close();
?>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#search_text').keyup(function(){
var search = $(this).val();
$.ajax({
url:'action.php',
method:'post',
data:{query:search},
success:function(response){
$('#table_data').html(response);
}
});
});
});
</script>
</body>
</html>
action.php:
<?php
include "../../src/fn/init.php";
$output = "";
if(isset($_POST["query"])){
$search = $_POST["query"];
$stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
$stmt->bind_param("sss",$search, $search, $search);
} else {
$stmt=$conn->prepare("SELECT * FROM brukere");
};
$stmt->execute();
$result=$stmt->get_result();
if($result->num_rows>0){
$output = "<thead>
<tr>
<th>#</th>
<th>Fornavn</th>
<th>Etternavn</th>
<th>Utskjekket</th>
<th>Admin</th>
<th>Slett</th>
</tr>
</thead>
<tbody>";
while($row=$result->fetch_assoc()){
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td>".Slett."</td>
</tr>";
};
$output .= "</tbody>";
echo $output;
} else {
echo "<h3>No match found!</h3>";
};
?>
This is the search script, the problem is in the while loop where the link is added, I can't figure out how to make it work.
The a tag is not added as a plain-text to the output string, you need to rewrite that line, concatenate strings parts to variables parts correctly.
Try replacing:
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td>".Slett."</td>
</tr>";
with:
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td><a href='delete.php?id=".urlencode($row['id'])."' onclick='return confirm('Er du sikker?');'>Slett</a></td>
</tr>";
To allow PHP to echo the id from the table result you need to just simply do a php echo
Slett
You don't have to url encode at this stage as you are just simply building the href of an a:link
You can use it
<?php
include "../../src/fn/init.php";
$output = "";
if(isset($_POST["query"])){
$search = $_POST["query"];
$stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
$stmt->bind_param("sss",$search, $search, $search);
} else {
$stmt=$conn->prepare("SELECT * FROM brukere");
};
$stmt->execute();
$result=$stmt->get_result();
if($result->num_rows>0){
$output = "<thead>
<tr>
<th>#</th>
<th>Fornavn</th>
<th>Etternavn</th>
<th>Utskjekket</th>
<th>Admin</th>
<th>Slett</th>
</tr>
</thead>
<tbody>";
while($row=$result->fetch_assoc()){
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td>Slett </td>
</tr>";
};
$output .= "</tbody>";
echo $output;
} else {
echo "<h3>No match found!</h3>";
};

how to call functions broadcast_js file

i already have a php script. when I will call its function, the function is not running. how to call the function ? and this is the script
...........
<table class="table table-hover" width="100%">
<thead style="position: sticky;top: 0;">
<tr>
<th style="position: sticky;left:-5px;background-color: white">Level</th>
<th>Area</th>
<?php
while($row=mysql_fetch_array($max_date))
{ echo '<th>'.$row['date'].'</th>'; }
?>
<th>MOM</th>
<th>YOY</th>
<th>YTD</th>
<th>Con Check</th>
<th>Target</th>
<th>Achievement</th>
</tr>
</thead>
<tbody id="table-payload"></tbody>
</table>............
<?php
$modul_js = array();
$modul_js = [
"page/broadcast/broadcast_js.js"
];
?>
UPDATE
this is my js file for call query from mysql
$.getJSON("page/broadcast/query_broadcast.php?case=payload",function(data){
$.each(data.item, function(i, v) {
$('#table-payload').append(
'<tr class="pointer">'+
'<td>'+v.level+'</td>'+
'<td>'+v.area+'</td>'+
'<td>'+v.mtd+'</td>'+
'<td>'+v.mom+'%</td>'+
'<td>'+v.yoy+'%</td>'+
'<td>'+v.ytd+'%</td>'+
'<td>'+v.dev+'</td>'+
'<td>'+v.pt+'</td>'+
'<td>'+v.achiev+'%</td>'+
'</tr>'
);
})
});
replace
<?php
$modul_js = array();
$modul_js = [
"page/broadcast/broadcast_js.js"
];
?>
with
<script type="text/javascript" src="page/broadcast/broadcast_js.js"></script>

Smoothy update PHP table when new data is entered into SQL table

So, I think I may be in over my head. I've looked around on here for a quite some time but have not been able to find something that will help me.
I am trying to build a display order from, similar to what you would see in a restaurant or fast food, that automatically and smoothly updates when a new entry has been entered into the MySQL table.
I tryed using AJAX but I could not get it to work
Main PHP page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
<scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/fulfillment.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
</head>
<body>
<div class="container">
<h1>Orders</h1>
<p>Area that displays all of the active and past orders.</p>
<div align="right">
<input id="toggle-event" type="checkbox" checked data-toggle="toggle" data-on="Active" data-off="Past">
</div>
<!-- Active Orders -->
<?php
include '../connect.php';
//get information form tblOrder
$sql = "SELECT * FROM tblOrder WHERE Filled=0";
$result = $db->query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
<!-- Build the table -->
<h2>Active</h2>
<table ID = "myTable" class="table table-striped">
<thead>
<tr>
<th>Order Number</th>
<th>User ID</th> <!-- will turn to user name later down the road -->
<th>Food</th>
<th>Pick Up Time</th>
<th>Filled</th>
</tr>
</thead>
<tbody>
<?php
// run though tblOrders
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//assign all of the values
$OrderNumber = $row["Order_Number"];
$FoodID = $row["F_ID"];
$DrinkID = $row["D_ID"];
$UserID = $row["User_ID"];
$Filled = $row["Filled"];
$RequestTime = $row["Request_Time"];?>
<!-- out put each line of the value -->
<tr>
<td><?php echo $OrderNumber; ?></td>
<td><?php echo $UserID; ?></td> <!-- switch to name once it is avalible ->
<td><!-- put food order here --></td>
<td><?php echo $RequestTime; ?></td>
<td><input type="button" class="btn btn-default" value="Complete"onclick="toPast(this, <?php echo $OrderNumber?>)"/></td>
</tr>
<?php
}
}
//close the data connection
$db->close();
?>
</tbody>
</table>
JavaScript
function toPast(btn, ONum) {
var dataString = 'OrderNumber=' + ONum + '&UpdateNumber=' + '1';
$.ajax({
type: "POST",
url: "update_sucess.php",
data: dataString,
cache: false,
success: function(html) {
//alert(html);
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
}
Could anyone point me in the right direction or know someplace has a "how-to" on how to do this that I could read?

Dynamic append and remove table rows not working

I work in wordpress with WPMVC.
I am adding table rows dynamically in the form to add a record to the table.
Code:
views/admin/edit.php
<h2>Edit Geozone</h2>
<?php echo $this->form->create($model->name); ?>
<?php echo $this->form->input('geozone_name'); ?>
<?php echo $this->form->input('state'); ?>
<?php echo $this->form->input('ordering'); ?>
<?php echo $this->form->end('Update'); ?>
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap#3.2.0" data-semver="3.2.0" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.css" />
<script data-require="bootstrap#3.2.0" data-semver="3.2.0" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js" data-semver="2.1.1" data-require="jquery#2.1.1"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<table class="table table-striped" id="geozoneRule">
<thead>
<tr>
<th colspan="3">
<input type="button" class="btn btn-success" value="Add Rule" onclick="addGeozoneRule();" />
</th>
</tr>
<tr>
<th>Country</th>
<th>Zone</th>
<th>Remove</th>
</tr>
</thead>
</table>
</body>
</html>
<script>
var count = 0;
function addGeozoneRule() {
var html = '';
html += '<tr>';
html += '<td><select name="rule[' + count + '][country_id]"><option value="99">India</option><option value="100">Indonesia</option></select></td>';
html += '<td><select name="rule[' + count + '][zone_id]"><option value="299">Chennai</option><option value="1100">some</option></select></td>';
html += '<td><span class="btn btn-danger" onclick="removeTr(this)">Remove <i class="icon icon-remove"></i></span></td>';
html += '</tr>';
jQuery("#geozoneRule").append(html);
count++;
}
function removeTr(element) {
if (count > 1) {
jQuery(element).closest('tr').remove();
count--;
} else {
alert('Keep one row');
}
</script>
I tested the code with plnkr.co and it was successful. But here in my application, it is not even entering the script. What could be the flaw in this code?
Solved the issue by removing the html start and end tags for:
'html' 'head' and 'body'
It works fine now.
Thanks all.

Multiple dynamic textfields into mysql db

Can someone fix my problem here pls. im trying to insert into database from these form below but I cant get it to work
heres the complete form sir:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<script type='text/javascript' src="jquery/jquery-1.8.3.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"> </script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
.dynatable {
border: solid 1px #000;
border-collapse: collapse;
}
.dynatable th,
.dynatable td {
border: solid 1px #000;
padding: 2px 10px;
width: 170px;
text-align: center;
}
.dynatable .prototype {
display: none;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(function(){
$(document).ready(function () {
var id = 0;
// Add button functionality
$("table.dynatable button.add").click(function () {
id++;
var master = $(this).closest("table.dynatable");
// Get a new row based on the prototype row
var prot = master.find("tr.prototype").clone();
prot.attr("class", "")
prot.find(".id").attr("value", id);
master.find("tbody").append(prot);
});
// Remove button functionality
$("table.dynatable button.remove").live("click", function () {
$(this).parents("tr").remove();
});
$("table.dynatable button.addColumn").click(function () {
var $this = $(this), $table = $this.closest('table')
var columnName = window.prompt("Enter Column name", "");
$('<th>' + columnName +'</th>').insertBefore($table.find('tr').first().find('th:last'))
var idx = $(this).closest('td').index() + 1;
$('<td><input type="text" name="col' + idx + '[]" value="" /</td>').insertBefore($table.find('tr:gt(0)').find('td:last'))
});
});
});//]]>
</script>
</head>
<body>
<table class="dynatable">
<thead>
<tr>
<th><button class="add">Add</button></th>
<form method="post" action="blah.php">
<th>Career Service/RA 1080(BOARD/BAR)</br>
Under Special Laws/CES/CSEE</th>
<th>Rating</th>
<th>Date of Examination/</br>
Conferment</th>
<th>Place of Examination/ Conferment</th>
</tr>
</thead>
<tbody>
<tr class="prototype">
<td><button class="remove">Remove</button></td>
<td><input type="text" name="name[]" value="" /></td>
<td><input type="text" name="rating[]" value="" /></td>
<td><input type="date" name="date[]" value="" /></td>
<td><input type="text" name="place[]" value="" /></td>
</tr>
</tbody>
</table>
<table width="972">
<tr align="center" >
<td width="71" colspan="5"><input type="submit" name="submit"/></td>
</tr>
</form>
</table>
</body>
</html>
Here's my php code it doesn't seem to work correctly. It inserts a blank data except for the id which has the value but the rest is blank data.
PHP CODE:
<?php
$host = 'Localhost';
$username= 'root';
$password= '';
$db_name = 'bfp';
$con = mysql_connect($host,$username,$password) or die ("Cant Connect");
mysql_select_db($db_name) or die ("Cant Select DataBase");
$k=2;//this is for the id value
$name = $_POST['name'];
foreach($name as $names) :
$values=mysql_real_escape_string($names);
$sql="INSERT INTO bfp_personnel_eligibility (id, eligibility_name, rating, doe, poe) VALUES ('{$k}','{$values}', '{$_POST['rating']}', '{$_POST['date']}', '{$_POST['place']}')";
if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
endforeach;
?>
try this code:
$i = 0;
foreach($name as $names) :
$values=mysql_real_escape_string($names);
$sql="INSERT INTO bfp_personnel_eligibility (id, eligibility_name, rating, doe, poe) VALUES ('{$k}','{$values}', '{$_POST['rating'][$i]}', '{$_POST['date'][$i]}', '{$_POST['place'][$i]}')";
$i++;
if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
endforeach;
Note: you have to apply mysql_real_escape_string for all values you are passing to query.
Edit:
place your form like this
<body>
<form method="post" action="blah.php">
<table class="dynatable">
.
.
.
.
</table>
</form>
</body>

Categories