How to retrieve data from mysql in html by calling a function? - javascript

I'm trying to retrieve data from MySQL and place it in HTML by calling a function, the PHP conf works fine when open in the browser. But when trying to call, nothing happens. I can't understand what's wrong, tried google it for solutions, but nothing actually works.
here is my PHP code
<?php
include("conn.php");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect: " . mysqli_connect_error();
}
mysqli_select_db($con, "users");
$result = mysqli_query($con, "SELECT * FROM drivers");
echo "<table border='1'>
<tr>
<th>id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['firstName'] . "</td>";
echo "<td>" . $row['lastName'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
and here is my ajax calling
<script type="text/javascript" src = "jquery-3.5.1.min.js">
$(document).ready(function (){
$("#show").click(function(){
$.ajax({
type: "POST",
url: "connection.php",
async: false,
dataType: "html",
success: function(response){
$("#container").html(response);
}
});
});
});</script>

Please try this:
$("#show").click(function(){
$.ajax({
type: "POST",
url: "connection.php",
async: false,
dataType: "html",
success: function(response){
$("#container").html(response);
}
});});

Related

How to send data and run a link with that data with one click

I want to send latitude and longitude data so I can search it up on Google Map. Those data has to be selected from a database but I can't figure how to do it in one click.
Here is my code.
<?php
$con = mysqli_connect("localhost","root","","project");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM table1");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Latitude</th>
<th>Longitude</th>
<th>Date</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['latitude'] . "</td>";
echo "<td>" . $row['longitude'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td><a href='./clicktest.php?id=".$row['id']."'>View Location</a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
And as you can see, it sends the id value of a row that I want to another page which is
<?php
$con=mysqli_connect("localhost","root","","project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_GET['id'])) {
$result = "SELECT * FROM table1 WHERE id='".$_GET['id']."'" ;
$show = mysqli_query($con, $result);
while($row = mysqli_fetch_array($show))
{
$latitude = $row['latitude'];
$longitude = $row['longitude'];
echo "<a href='http://www.google.com/maps/place/".$latitude.",".$longitude."'>click here</a>";
}
mysqli_close($con);
}
?>
And finally can run a link to Google Map on this page. But what I want is to click on the 'view location' on the first page and jump to the google map page with data on that row without having to go through another page and another click.
I did some research and maybe this is about AJAX? And are there any ways to do it without using AJAX?(since I never use it before)
Thanks
I think you need to directly link to google maps page and use "target=_blank" attribute on it. for example:
echo 'View Location';
You can add as many parameter to the anchor tag as you like, so add the lat and long like this for example
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['latitude'] . "</td>";
echo "<td>" . $row['longitude'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td><a href='./clicktest.php?id=".$row['id']
.'&lat=' . $row['latitude']
. '&long' . $row['longitude']"'>View Location</a></td>";
echo "</tr>";
}

Data table Server side Ajax Pagination

I Have A location Table with nearly 14 thousand records,
I need ajax pagination with server-side data.
I used the Below Code But not working.
<table class="table table-bordered table-striped table-hover dataTable js-exportable" id="htmltableID">
<thead>
<tr>
<th>SNO</th>
<th>Location</th>
<th>City</th>
<th>State</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach ($data as $row) {
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row->location . "</td>";
echo "<td>" . $row->city . "</td>";
echo "<td>" . $row->state . "</td>";
echo "</tr>";
$i++;
}
?>
</tbody>
</table>
<script>
var oTable = "";
$(document).ready(function () {
oTable = $('#htmltableID').dataTable({
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "location",
"sServerMethod": "POST",
"iDisplayLength": 5
});
});
</script>
By Using this Code I am getting error Msg "DataTables warning: table id=htmltableID - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3" and "DataTables warning: table id=htmltableID - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1"
You should have below type of code in main file. Let's say Maindata.php
<table class="table table-bordered table-striped table-hover dataTable js-exportable" id="htmltableID">
<thead>
<tr>
<th>SNO</th>
<th>Location</th>
<th>City</th>
<th>State</th>
</tr>
</thead>
</table>
<script>
var oTable = "";
$(document).ready(function () {
oTable = $('#htmltableID').dataTable({
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "location",
"sServerMethod": "POST",
"iDisplayLength": 5
});
});
</script>
And the data(json) needs to be fetch from other file, let's say loadrecords.php(In your case it was location/loadRecord)
<?php
// $data is the list of records fetched from database
// No need to print the data since we need to provide json data to dataTable, so Below code not required
/*
$i = 1;
foreach ($data as $row) {
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row->location . "</td>";
echo "<td>" . $row->city . "</td>";
echo "<td>" . $row->state . "</td>";
echo "</tr>";
$i++;
}
*/
// Data which you needs to send in 'location/loadRecord' should be like this (In my case it was `loadrecords.php`)
/*{
"data": [
["1","Location 1","City 1","State 1"],
["2","Location 2","City 2","State 2"],
.....
.....
["N","Location N","City N","State N"]
]
}*/
// Loop the data records fetched from database and prepare array in below format
$json_arr = array(
"data" => array(
array("1","Location 1","City 1","State 1"),
array("2","Location 2","City 2","State 2"),
...............
...............
array("N","Location N","City N","State N"),
)
);
echo json_encode($json_arr);
data will have N no.of rows with 4 columns since you want to display 4 columns in the table so related data needs to be provided in json

Using AJAX to pass variable from dynamic html table to php updating query

I want to add a value in the input text valor and assign this value to the row where it is, for this I need pass to the update query ID and the valor.
What am I doing wrong?
Table
<?php
$IDTipoEquipamento = $_POST['Car'];
$result = mysqli_query($conn,"SELECT tipocaracteristicas.IDTipoCaracteristicas,tipoequipamento.TipoEquipamento, caracteristicas.Caracteristica, Valor FROM `tipocaracteristicas` LEFT JOIN tipoequipamento on tipoequipamento.IDTipoEquipamento= tipocaracteristicas.IDTipoEquipamento LEFT JOIN caracteristicas on caracteristicas.IDCaracteristicas=tipocaracteristicas.IDCaraterisiticas WHERE tipocaracteristicas.IDTipoEquipamento= '$IDTipoEquipamento';");
echo "<table width='100% class='sortable' id='datatables-example'>
<tr>
</tr>
<tr>
<td class='pure-table'></td>
<td class='pure-table'><b>Tipo de Equipamento</b></td>
<td class='pure-table'><b>Caracteristica</b></td>
<td class='pure-table'><b>Valor</b></td>
<td class='pure-table'><b>Atribuir</b></td>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tbody data-link='row' class='rowlink'>";
echo "<tr>";
echo "<td><input type='text' name='IDTipoCaracteristicas' id='IDTipoCaracteristicas' value='". $row['IDTipoCaracteristicas'] . "'></td>";
echo "<td>" . $row['TipoEquipamento'] . "</td>";
echo "<td>" . $row['Caracteristica'] . "</td>";
echo "<td><input type='text' name='valor' id='valor' value=''></td>";
echo "<td><a href='' onclick='UpdateTable()'><img id='img' src='save_icon.gif'/></a></td>";
echo "</tr>";
echo "</tbody>";
}
echo"<br>";
echo "</table>";
mysqli_close($conn);
}
?>
Jquery + Ajax
<script type="text/javascript">
function UpdateTable() {
$("#valor").on('input', function() {
var valor = $(this).val();
$.ajax({
url: 'insertCharacteristicsEquipment.php',
type: "POST",
cache:false,
data:{valor:valor},
async: false,
dataType:'html',
success:function(data) {
$("#valor").html(data);
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
$("#IDTipoCaracteristicas").on('input', function(){
var IDTipoCaracteristicas = $(this).val();
$.ajax({
url: 'insertCharacteristicsEquipment.php',
type: "POST",
cache:false,
data:{IDTipoCaracteristicas:IDTipoCaracteristicas},
async: false,
dataType:'html',
success:function(data) {
$("#IDTipoCaracteristicas").html(data);
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
}
</script>
PHP UPDATE QUERY PAGE
<?php
include ('conetar.php');
if(isset($_POST['valor'], $_POST['IDTipoCaracteristicas'])){
$valor = $_POST['valor'];
$IDTipoCaracteristicas= $_POST['IDTipoCaracteristicas'];
$sql = "UPDATE `tipocaracteristicas` SET `Valor`='$valor' WHERE `IDTipoCaracteristicas`= '$IDTipoCaracteristicas'";
if(mysqli_query($conn,$sql)){
} else{
echo "ERROR: Could not able to execute $sql. ";
}
mysqli_close($conn)
}
?>
See the below two statements here,
echo "<td><input type='text' name='IDTipoCaracteristicas' id='IDTipoCaracteristicas' value='". $row['IDTipoCaracteristicas'] . "'></td>";
^^^^^^^^^^^^^^^^^^^^^^^^^
and
echo "<td><input type='text' name='valor' id='valor' value=''></td>";
^^^^^^^^^ ^^^^^^^^
You're assigning the same id for all of your table rows, use class instead. Assign class to each of your IDTipoCaracteristicas, Valor input elements as well as to the update table hyperlinks. Furthermore, you didn't assign any value in Valor input element. Also, make the anchor tags non-linkable using javascript:void(0);, otherwise you'll get redirected every time you click on a link. So your while() loop should be like this:
while($row = mysqli_fetch_array($result)) {
echo "<tbody data-link='row' class='rowlink'>";
echo "<tr>";
echo "<td><input type='text' name='IDTipoCaracteristicas' class='IDTipoCaracteristicas' value='". $row['IDTipoCaracteristicas'] . "'></td>";
echo "<td>" . $row['TipoEquipamento'] . "</td>";
echo "<td>" . $row['Caracteristica'] . "</td>";
echo "<td><input type='text' name='valor' class='valor' value='". $row['Valor'] ."'></td>";
echo "<td><a href='javascript:void(0);' class='updateTable'><img id='img' src='save_icon.gif'/></a></td>";
echo "</tr>";
echo "</tbody>";
}
Subsequently, your jQuery/AJAX code should be like this:
<script>
$(document).ready(function(){
$(document).on('click', '.updateTable', function(){
var IDTipoCaracteristicas = $(this).parents('tr').find('.IDTipoCaracteristicas').val();
var valor = $(this).parents('tr').find('.valor').val();
$.ajax({
url: 'insertCharacteristicsEquipment.php',
type: "POST",
cache:false,
data:{valor:valor, IDTipoCaracteristicas: IDTipoCaracteristicas},
async: false,
success:function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
</script>

Calling a POST variable in PHP-function

I have a PHP-file with multiple php functions in it.
I am sending a Javascript Variable with an AJAX-call, POST method to that PHP-file.`
Now the variable IS accessible in my PHP-file but not in that specific function where I want it...
$("#dropdown").change(function () {
var value = $("#dropdown").val();
console.log(value);
$.ajax({
type: "POST",
dataType: 'text',
url: "PhpFunctions.php",
data: {id:$("#dropdown").val()},
success: function (data) {
console.log(data);
$("div.geselecteerdVliegtuig").fadeIn("slow", function () {
console.log("Vliegtuigdetail faded in");
});
/*
$("div.vliegtuigenEnabled2").hide();
console.log("vliegtuigEnabled ID's hidden");
*/
},
error: function (err) {
alert('error: ' + err);
}
}); //END AJAX CALL`
//I CAN ACCESS DATABASE AND ID IS ACCESSIBLE HERE
//Connect to server
$connect = mysql_connect("localhost", "root", "root") or die(mysql_error());
//Connect to database
$select_db = mysql_select_db("Luchthaven") or die("Could not find database");
$id = $_POST['id'];
echo $id; //WORKS
//NEED TO ACCESS IS HERE
function GeselecteerdVliegtuig() {
makeConnection();
//Query the database
$id = $_POST['id'];
//$query = "SELECT * FROM vliegtuig WHERE vliegtuig_ID = 'PEG431';";
//echo "SELECT * FROM vliegtuig WHERE vliegtuig_ID = 'PEG431';<br/>";
$query = "SELECT * FROM vliegtuig WHERE vliegtuig_ID = '" . $id . "';";
echo "SELECT * FROM vliegtuig WHERE vliegtuig_ID = '" . $id . "';<br/>";
$fetch = mysql_query($query) or die("could not fetch data");
while ($row = mysql_fetch_assoc($fetch)) {
echo "<tr id=" . $row['vliegtuig_ID'] . ">";
echo "<td>" . $row['vliegtuig_ID'] . "</td>";
echo "<td>" . $row['maatschappij'] . "</td>";
echo "<td>" . $row['lengte'] . "</td>";
echo "<td>" . $row['breedte'] . "</td>";
echo "<td>" . $row['kilometerstand'] . "</td>";
echo "<td>" . $row['bouwjaar'] . "</td>";
echo "<td>" . $row['bereik'] . "</td>";
echo "<td>" . $row['aantalMotoren'] . "</td>";
echo "</tr>";
} // END WHILE
mysql_close(); //Make sure to close out the database connection
echo "<b>Connection closed<b><br/><br/>";
}
You can pass the $_POST['id'] variable to that function GeselecteerdVliegtuig($id) and call the function with GeselecteerdVliegtuig($_POST['id'])
Get rid of this line:
$id = $_POST['id'];
as you might want to use your functionality even if your value is not located in your $_POST["id"]. Modify your function header from
function GeselecteerdVliegtuig() {
to
function GeselecteerdVliegtuig($id) {
Call your function this way:
if (isset($_POST['id'])) {
GeselecteerdVliegtuig($_POST['id']);
}
and call your function from the page where you posted the value, make sure that the page where you posted exists, works and responds.
Finally, when everything is working change the way you are working with the database, because your current approach has a security leak due to SQL injection possibilities. What if I visit your page and execute the following in the console:
$("#dropdown").val("0'; delete from vliegtuig where '' = '");
and then trigger the post? It will remove every single record from your table unless you are making sure that these attempts fail.

Javascript not working in AJAX response

Below code is the AJAX response to another page. I have added onclick event to table row and written javascript code to handle it. But javascript code doesn't work.Is this wrong way of coding or there is any problem in code. Suggest me a simple solution
<?php
echo '<script type=\"text/javascript\">
function clicked(){
alert("I am an alert box!");
}
</script>';
$q = $_GET['q'];
include 'db_connect.php';
$sql="SELECT name,address,mobile,email,pan,tan FROM client WHERE name = '$q'";
$sql_bill="SELECT clientname,financialyear,receiptno,amount,ddate,type,chequeno,category FROM billing WHERE clientname = '$q'";
$sql_total="SELECT SUM(amount) AS TotalAmount FROM billing";
$result = mysql_query($sql);
$result_bill = mysql_query($sql_bill);
$result_total = mysql_query($sql_total);
$total= mysql_fetch_array($result_total);
echo "<h4><b>Client details</b></h4><table align='center' border='2'>
<tr>
<th>Name</th>
<th>Address</th>
<th>Mobile</th>
<th>Email</th>
<th>PAN</th>
<th>VAT TIN</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['mobile'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['pan'] . "</td>";
echo "<td>" . $row['tan'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<h4><b>Payment received details</b></h4><table align='center' border='2'>
<tr>
<th>Client Name</th>
<th>Financial Year</th>
<th>Receipt No</th>
<th>Date</th>
<th>Type</th>
<th>Chequeno</th>
<th>Category</th>
<th>Amount</th>
</tr>";
while($row = mysql_fetch_array($result_bill))
{
echo "<tr onclick=\"clicked()\">";
echo "<td>" . $row['clientname'] . "</td>";
echo "<td>" . $row['financialyear'] . "</td>";
echo "<td>" . $row['receiptno'] . "</td>";
echo "<td>" . $row['ddate'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row['chequeno'] . "</td>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['amount'] . "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<td colspan=7>Total</td>";
echo "<td>".$total['TotalAmount']. "</td>";
echo "</tr>";
echo "</table>";
?>
Try this instead of your script code:
echo <<<EOD
<script type="text/javascript">
function clicked(){
alert("I am an alert box!");
}
</script>
EOD;
Edit 1:
Look in the console (F12), What happens when you click on a tr?
The following fiddle replicates your code and works:
http://jsfiddle.net/Yaj44/
Edit 2:
I think it has something to do with the way you call the data.
Put the function in your main page,
then call the AJAX.
Set innerHTML of specific div with responseData.
If you do it in that order, it might work.
Your way to adding this functionality is very dirty..
If you use JQuery, you can add on the end:
$('tr').click(function() {
alert('Do something on click!');
});
mysql_fetch_array is outdated, use mysqli (or PDO) instead.
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();

Categories

Resources