Calling JavaScript from within PHP logic error - php

I am printing out a number of rows from my database. Each row contains one td which contains which id is the respective row number(row numbers start at 1).
As each row is echoed, I update the rows with addresses using javascript .appendChild(), addresses whose co-ordinates have been called from the db.
The first 5 rows co-ordinates have been correctly converted into addresses, and the remaining rows have the correct co-ordinates called from the db(I know because I checked the source) however the address being entered in the row is always the value of the last row on the db.
Please note that the co-ordinates are being converted to addresses using google maps api.
if ( mysql_num_rows( $result ) > 0 ){
$i = 1;
while($row = mysql_fetch_array($result)){
echo "<tr>";
?>
<script>
initialize();
var counter = 1;
function initialize() {
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(<?php echo $row['latitude'] ?>,<?php echo $row['longitude'] ?>);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var txt = results[0].formatted_address;
var newtext = document.createTextNode(txt);
document.getElementById("address" + counter).appendChild(newtext);
counter++;
} else {
alert('No results found');
}
} else {
//alert('Geocoder failed due to: ' + status);
}
});
}
setInterval(convert, 2);
function convert() {
initialize();
}
</script>
<?php
echo "<td id='address" . $i . "'></td>";
$i++;
}
Solution
After a bit of thinking, and a lot of googling, I solved it! Entire code below for anyone else that might stumble on this!
<?php
// security check
$account_type = $_COOKIE["account_type"];
if($account_type != "canvass_leader" && $account_type != "leader" && $account_type != "canvasser"){
header("location:login.php");
}
$username_cookie2 = $_COOKIE["username_cookie"];
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles/style.css"/>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<title>Canvassing Data</title>
<style type="text/css">
#header #welcome #para{
margin-top: -84px;
}
</style>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script>
function setUp() {
window.counter = 1;
setInterval(initialize, 700);
}
function initialize() {
var geocoder;
geocoder = new google.maps.Geocoder();
var lat = document.getElementById("lat" + counter);
var lng = document.getElementById("lng" + counter);
//alert(lat.innerHTML);
//alert(lng.innerHTML);
var latlng = new google.maps.LatLng(lat.innerHTML,lng.innerHTML);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var txt = results[0].formatted_address;
var addressValue = document.createTextNode(txt);
$('#lat' + counter).remove();
$('#lng' + counter).remove();
var element = "#address" + counter;
$(element).append(addressValue)
counter++;
} else {
alert('No results found');
}
} else {
//alert('Geocoder failed due to: ' + status);
}
});
}
</script>
</head>
<body onload="setUp()" >
<div id="wrapper">
<?php
include('header.php');
// connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get party cookie
$party = $_COOKIE["party"];
// set table name
$tbl_name = "checklist_" . $party;
?>
<div id='info_bubble'>From this page you can view, search and export all collected canvassing data.</div>
<?php if($account_type == "canvass_leader") { ?>
<div style="text-align: center;">
<form id="" method="post" action="" style="margin: 20px 0 30px 0;">
<h3>Search Canvassing Data</h3>
<fieldset id="inputs" >
<input style="width: 270px;" name="search_name" type="text" placeholder="Search by canvasser name.." >
<input style="width: 270px;" name="search_reception" type="text" placeholder="Search by reception at door.." >
</fieldset>
<fieldset id="actions" class="button button-blue">
<span><input type="submit" id="submit" name="search" value="Search Data"></span>
</fieldset>
</form>
</div>
<?php } ?>
<?php
if(isset($_POST['search'])) {
$search_name = $_POST['search_name'];
$search_reception = $_POST['search_reception'];
if(strlen($search_name)) {
$sql = "SELECT * FROM $tbl_name WHERE canvasser = '$search_name'";
$result = mysql_query($sql);
}
if(strlen($search_reception)) {
$sql = "SELECT * FROM $tbl_name WHERE reception_at_door = '$search_reception'";
$result = mysql_query($sql);
}
}
else{
if($account_type == "canvass_leader") {
$sql = "SELECT * FROM $tbl_name WHERE creator = '$username_cookie2'";
$result = mysql_query($sql);
}
else { // account_type = Leader
$sql = "SELECT * FROM $tbl_name";
$result = mysql_query($sql);
}
}
// display table data
echo "<div id='content'>
<table class='bordered' border='1'>
<tr>
<th>Address</th>
<th>House Number</th>
<th>Registered to Vote</th>
<th>Visited by Candidate</th>
<th>Leafleted</th>
<th>Canvassed</th>
<th>Reception at Door</th>
<th>Canvasser</th>
</tr>";
if ( mysql_num_rows( $result ) > 0 ){
//$num_rows = mysql_num_rows($result);
//echo "$num_rows Rows\n";
$i = 1;
while($row = mysql_fetch_array($result)){
echo "<tr>";
?>
<?php
//echo "<td id='address" . $i . "'></td>";
//echo "<td id='address" . $i . "'>" . $row['latitude'] . " ## " . $row['longitude'] . "</td>";
//echo "<td id='address" . $i . "'>" . $row['latitude'] . " ## " . $row['longitude'] . "</td>";
echo "<td id='address" . $i . "'><p id='lat" . $i . "'>" . $row['latitude'] . "</p><p id='lng" . $i . "'>" . $row['longitude'] . "</p></td>";
// only set co-ordiantes first, then convert them to address by getElementById and appendChild when dom is ready in js in head of page
echo "<td>" . $row['house_number'] . "</td>";
echo "<td>" . $row['registered_to_vote'] . "</td>";
echo "<td>" . $row['visited_by_candidate'] . "</td>";
echo "<td>" . $row['leafleted'] . "</td>";
echo "<td>" . $row['canvassed'] . "</td>";
echo "<td>" . $row['reception_at_door'] . "</td>";
echo "<td>" . $row['canvasser'] . "</td>";
echo "</tr>";
$i++;
}
}
echo "</table>";
if( $account_type == "canvass_leader" || $account_type == "leader"){
echo '<form style="margin-top: 10px;" action="dash_data_canvassing_export.php">';
echo '<fieldset id="actions" class="button button-blue"><span><input type="submit" value="Export Data" id="submit" name="submit"></span></fieldset>';
echo '</form></div>';
}
include('footer.php');
?>
</div>
</body>
</html>

Related

Php show users data from mysql with dropdown list

i want to display users data in a table with the dropdown list , the first option shows all the users but when i click a name it still shows all users, i think i have some trouble in my ajax script because it deosn't seem to work
this is the page where i display data :
<?php
//load_data_select.php
$connect = mysqli_connect("localhost", "root", "ntr-ktb123", "absence");
function fill_emp($connect)
{
$output = '';
$sql = "SELECT * FROM employés";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output = $output."'<option value="'.$row["IdEmp"].'">'.$row["NomEmp"].'</option>'";
}
return $output;
}
function fill_Abs($connect)
{
$output = '';
$sql = "SELECT NomEmp,PrénomEmp,DateD,DateF,CauseAbs,justifié
FROM absence.absences
WHERE
MONTH(DateF) = MONTH(NOW())
AND
YEAR(DateF) = YEAR(NOW());";
$result = mysqli_query($connect, $sql);
echo "<table>
<tr>
<th>NomEmp</th>
<th>PrénomEmp</th>
<th>DateD</th>
<th>DateF</th>
<th>CauseAbs</th>
<th>justifié<th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['NomEmp'] . "</td>";
echo "<td>" . $row['PrénomEmp'] . "</td>";
echo "<td>" . $row['DateD'] . "</td>";
echo "<td>" . $row['DateF'] . "</td>";
echo "<td>" . $row['CauseAbs'] . "</td>";
echo "<td>" . $row['justifié'] . "</td>";
echo "</tr>";
}
$output="</table>";
return $output;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Multiple Image Upload</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
/>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js">
</script>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
<script>
$(document).ready(function(){
$('#nom').change(function(){
var NomEmp = $(this).val();
$.ajax({
url:"usr.php",
method:"POST",
data:{NomEmp:NomEmp},
success:function(data){
$('#show_Abs').html(data);
}
});
});
});
</script>
</head>
<body>
<br /><br />
<div class="container">
<h3>
<label for="nom">Selectionnez le nom de l'employé </label>
</br></br>
<select name="nom" id="nom">
<option value="">Tout les employés</option>
<?php echo fill_emp($connect); ?>
</select>
<br /><br /> <br />
<div class="row" id="show_Abs">
<?php echo fill_Abs($connect);?>
</div>
</h3>
</div>
</body>
</html>
and this is the usr.php :
<?php
//load_data.php
$connect = mysqli_connect("localhost", "root", "ntr-ktb123", "absence");
$output = '';
if(isset($_POST["NomEmp"]))
{
if($_POST["NomEmp"] != '')
{
$sql = "SELECT NomEmp,PrénomEmp,DateD,DateF,CauseAbs,justifié
FROM absence.absences
WHERE
MONTH(DateF) = MONTH(NOW())
AND
YEAR(DateF) = YEAR(NOW()) WHERE NomEmp = '".$_POST["NomEmp"]."'";
}
else
{
$sql = "SELECT NomEmp,PrénomEmp,DateD,DateF,CauseAbs,justifié
FROM absence.absences
WHERE
MONTH(DateF) = MONTH(NOW())
AND
YEAR(DateF) = YEAR(NOW());";
}
$result = mysqli_query($connect, $sql);
$output="<table>
<tr>
<th>NomEmp</th>
<th>PrénomEmp</th>
<th>DateD</th>
<th>DateF</th>
<th>CauseAbs</th>
<th>justifié<th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['NomEmp'] . "</td>";
echo "<td>" . $row['PrénomEmp'] . "</td>";
echo "<td>" . $row['DateD'] . "</td>";
echo "<td>" . $row['DateF'] . "</td>";
echo "<td>" . $row['CauseAbs'] . "</td>";
echo "<td>" . $row['justifié'] . "</td>";
echo "</tr>";
}
echo $output;
}
?>
can anyone help me to find the problem in this ? any help would be appreciated.
Thanks.
We could use a little more info to help with this, but I'll try to get the ball rolling.
I would guess that $_POST["NomEmp"] in usr.php is === "" so the else is running, which shows the entire table again.
I can't tell what you are setting the "value" attribute to in the fill_emp function. What is the value of $row[1] in that function?
Just change the ajax call like mentioned below :
$(document).ready(function(){
NomEmp = "";
$.ajax({
url:"usr.php",
method:"POST",
data:{NomEmp:NomEmp},
success:function(data){
$('#show_Abs').html(data);
}
});
$('#nom').change(function(){
NomEmp = $(this).val();
$.ajax({
url:"usr.php",
method:"POST",
data:{NomEmp:NomEmp},
success:function(data){
$('#show_Abs').html(data);
}
});
});
});
Also in your html cannot able to find a tag having id show_Abs. So just modify the div into
<div class="row" id="show_Abs">
</div>
Now I think the php function <?php echo fill_Abs($connect);?> is not necessary.
When page loads the first time, ajax call will be generated and on changing the select tag call will be generated with passing the selected parameters getting appropriate results.

php search script in mysql database dosen't work

I am trying to develop a program that search in mysql database and return the search results but in when I hit the submit it displays all the results I don't know why this is happening, so any help will be appreciated
<?php
include('connect2.php');
?>
<?php
echo "<center>";
echo "<table border = '3'>";
echo "<thead>";
echo "<tr>";
echo "<th><u>id</u></th>";
echo "<th><u>name</u></th>";
echo "<th><u>countrycode</u></th>";
echo "<th><u>district</u></th>";
echo "<th><u>population</u></th>";
echo "</center>";
echo "</tr>";
echo "</thead>";
$name = isset($_POST['search']) ? $_POST['search'] : '';
$result = mysqli_query($conn, "SELECT id, name, district, population, countrycode FROM city WHERE concat(id, name, district, population, countrycode) LIKE '%$name%' ");
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['name'] . "</td><td>" . $row['countrycode'] . "</td><td>" . $row['district'] . "</td><td>" . $row['population'] . "</td></th>";
}
}
else {
header( "Location:error page.html" ); die;
}
echo "</table>";
mysqli_close($conm);
?>
the search page search.php
<?php
include('connect2.php') ;
?>
<!DOCTYPE html>
<head>
<title>city results</title>
<link href="style-table.css" rel="stylesheet">
<link href="animate.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script>
function validateform() {
var x = document.forms["myform"]["input"].value;
if (x == "") {
alert("input must be filled out");
return false;
}
}
</script>
</head>
<body>
<form method="POST" action="display-results-city.php" name="myform" onsubmit="return validateform()">
<input type="text" name="input" placeholder="search.........">
<button name="submit" type="submit">go</button>
</form>
<?php
echo '<div class="animated fadeInUp">';
echo '<i class="fa fa-arrow-left fa-lg" aria-hidden="true" ></i>';
echo "<div id='records'>";
echo "<table border = '0'>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>name</th>";
echo "<th>countrycode</th>";
echo "<th>district</th>";
echo "<th>population</th>";
echo "</tr>";
echo "</div>";
echo '</div>';
$sql = "select * from city limit 50";
$result = $conn->query($sql);
if( $result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['ID']. "</td><td>" . $row['Name']. "</td><td>" . $row['CountryCode'] . "</td><td>" . $row['District'] . "</td><td>" . $row['Population'] . "</td></tr>";
}
} else {
echo " 0 results";
}
echo '</table>';
$conn->close();
?>
</body>
</html>
Try running this query..
$result = mysqli_query($conn, "SELECT id, name, district, population, countrycode FROM city WHERE UPPER(concat(id, name, district, population, countrycode)) LIKE UPPER('%$name%') ");
It will match both "Name" and "name".

New fetched row overwriting the previous row while writing to a table

<?php
session_start();
?>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.css">
<script>
function submit() {
document.getElementById("myform").submit();
}
window.onload = function() {
document.getElementById("textbox").focus();
};
</script>
</head>
<body>
<form id="myform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1> AWB_NO</h1>
<input type=text id="textbox" name="excel" onchange="submit()">
</br>
</form>
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$vars = $_COOKIE['var1'];
if(!isset($_SESSION['items'])) {
$_SESSION['items'] = array();
}
if(!isset($_SESSION['arr2'])) {
$_SESSION['arr2'] = array();
}
$var='';
if(isset($_POST['excel']))
{
$host="localhost";
$user="root";
$password="";
$db="greenmobiles";
$table="manifest";
$var=$_POST['excel'];
$con=mysqli_connect("$host","$user","$password") or die("Cannot Connect");
mysqli_select_db($con,"$db") or die("Cannot select DB!");
if (in_array($var,$_SESSION['items']))
{
echo"The new value has been scanned!</br>";
echo "<hr>";
echo "The tracking id's of the currently scanned items are given below<br><hr>";
foreach ($_SESSION['items'] as $x => $value)
{
echo "$value";
echo "<br>";
}
echo "<script>alert('oops! This item has already been scanned!')</script>";
}
else
{
$sql = "SELECT * FROM manifest WHERE awb_no = '$var'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result) > 0)
{
echo "tracking id present in the manifest</br>";
}
else
{
echo "<script>alert('Tracking id is not present in the manifest!')</script>";
}
$sqli = "SELECT * FROM manifest WHERE (awb_no = '$var') AND (document_no='$vars')";
$result1 = mysqli_query($con,$sqli);
if (mysqli_num_rows($result1))
{
echo "The tracking id matches with the document no.";
}
else
{
echo "<script>alert('Tracking id does not belong to the document number entered.')</script>";
exit(0);
}
while ($row = mysqli_fetch_assoc($result))
{
$_SESSION['data'][] = $row['awb_no'];
$_SESSION['items'] = $_SESSION['data'];
}
mysqli_free_result($result);
echo"The new value has been scanned!</br>";
echo "<hr>";
echo "The tracking id's of the currently scanned items are given below<br><hr>";
echo '<div class="col-lg-10 col-lg-offset-1 panel">'."<table class='table'>
<tr>
<th>Document No</th>
<th>AWB NO</th>
<th>Order Id</th>
<th>Forms</th>
<th>Extras</th>
</tr>";
echo "<tr>";
$sqlq= "SELECT * FROM manifest WHERE awb_no = '$var'";
$result2 = mysqli_query($con,$sqlq);
if ($result2)
{
while ($row=mysqli_fetch_row($result2))
{
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[3] . "</td>";
echo "<td>" . $row[4] . "</td>";
echo "</tr>";
}
echo "</table></div>";
}
}
}
else
{
session_destroy();
}
?>
</body>
</html>
Hello, i am new to php and html. I am giving an input to a text box whose value is '$var' and retrieving data one row at a time and trying to print it in a html table via php. But each time i enter a value the previous row gets overwritten by the new row and i am not able to keep the previous rows and append the new ones to my table. Can someone please tell me where i am going wrong.

how to select rows from a database and display them with checkboxes?

have a database with an id question and choiecs and an answer(multiple choice) i want to display the all of it which is in the database with a checkbox to the left of it. at the end i will have a submit button and all the questions checked i want to display under the table. My attempt. there has to be a more simple way. Thanks!
$result = mysqli_query($con,"SELECT id,question,choiceA,choiceB,choiceC,choiceD,answer FROM q_and_a ");
echo "<table border='1'>
<tr>
<th>Add</th>
<th>#</th>
<th>Question</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>Answer</th>
</tr>";
echo '<form method="POST" action="makeTest.php">';
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo '<td><input type="checkbox" name="questions[]" value="yes"></td>';
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['question'] . "</td>";
echo "<td>" . $row['choiceA'] . "</td>";
echo "<td>" . $row['choiceB'] . "</td>";
echo "<td>" . $row['choiceC'] . "</td>";
echo "<td>" . $row['choiceD'] . "</td>";
echo "<td>" . $row['answer'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
I'd suggest throwing jQuery into the mix.
Keep HTML out of your PHP code and just use it to query the database.
Then use AJAX/JSON to update the DOM.
UPDATE - This has been tested (verified working), and a few bugs were fixed along the way.
ajax.php:
<?php
$action = $_POST["action"];
if ($action == "getQuestions") {
echo getQuestions();
}
function getQuestions() {
try {
$db = new PDO("mysql:host=localhost;charset=utf8", "root", "root");
$cmd = $db->prepare("
SELECT id, question , choiceA ,choiceB ,choiceC ,choiceD , answer
FROM pl2.questions;
");
$cmd->execute();
$rows = array();
while($r = $cmd->fetch(PDO::FETCH_ASSOC)) { $rows[] = $r; }
$json = json_encode($rows);
return($json);
} catch (PDOException $e) { echo $e->getMessage(); return; }
}
?>
questions.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script language="javascript">
var questionsJson = '';
$(document).ready(function() {
getQuestions();
});
function getQuestions() {
$.post('ajax.php', { action: 'getQuestions' }, function(data) {
questionsJson = data;
displayQuestions();
},'json');
}
function displayQuestions() {
var colAry = ['id', 'question', 'choiceA', 'choiceB', 'choiceC', 'choiceD', 'answer'];
for (var i = 0; i < questionsJson.length; i++) {
var q = questionsJson[i];
var row = '<tr><td><input type="checkbox" name="questions[]" value="yes"></td>';
for (var j = 0; j < colAry.length; j++) {
row += '<td>' + q[colAry[j]] + '</td>';
}
$('#mainTable').append(row + '</tr>');
}
}
</script>
</head>
<body>
<table id="mainTable" border="1">
<tr>
<th>Add</th>
<th>#</th>
<th>Question</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>Answer</th>
</tr>
</table>
</body>
</html>

click row to fill textboxes in php - array vs ajax

I have a table coded in php which pulls in data from mysql database and displays it in a html table . Now when i click on a row I need certain textboxes to be filled.
What is the best approach for this: is it using an array or ajax,html and php,
<?php
$default = "<img src='http://localhost/on.png' width='24' height='24'/>";
$default1 = "<img src='http://localhost/of.png' width='24' height='24'/>";
$con = mysql_connect("*****","******","******");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db ("*****",$con);
$sql= "select act.*
from audit_activity as act
inner join (
select user_id, max(timestamp) as max_ts
from activity
group by user_id) as a on act.user_id=a.user_id and act.timestamp=a.max_ts";
$mydata = mysql_query($sql,$con);
echo "<table id='tfhover',table border=0>
<tr>
<th>Users</th>
<th>Status<th>
</tr>";
while($record = mysql_fetch_array($mydata)){
echo "<tr>";
echo "<td>" . $record['user_id'] . "</td>";
if (strtolower(trim($record['activity']))!=strtolower('LOGIN')){
echo "<td>" . $default1 . "</td>";
}else{
echo "<td>" . $default . "</td>";
}
echo "</tr>";
}
echo "</table>";
;
mysql_close($con);
?>
<html>
<script type="text/javascript">
window.onload=function(){
var tfrow = document.getElementById('tfhover').rows.length;
var tbRow=[];
for (var i=1;i<tfrow;i++) {
tbRow[i]=document.getElementById('tfhover').rows[i];
tbRow[i].onmouseover = function(){
this.style.backgroundColor = '#ffffff';
};
tbRow[i].onmouseout = function() {
this.style.backgroundColor = '#d4e3e5';
};
}
};
</script>
<head>
</head>
<body>
Total exams taken : <br>
<input type="text" name="fname"/>
</body>
</html>

Categories