pass the value to database - javascript

I want to pass the value from the Ajax code to the database as this program is to show the details of the user, but there is an error in the code in passing the value. What can I do now?
function showUser() {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
var id = document.getElementById("id").value;
httpRequest.onreadystatechange = alertContents;
httpRequest.open("GET", "http://localhost/cart/guser.php?id=" + id + "&rand=" + , true);
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
document.getElementById("txtHint").innerHTML = httpRequest.responseText;
}
}
var id = document.getElementById('id').value;
}
<form>
enter digit :
<input type="text" id="id" name="id" />
<br />
<input type='button' onclick='showUser(this.value)' value='select' />
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b>
</div>
below code is for guser.php
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cart";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db('cart',$con);
$sql="SELECT * FROM user_details WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>email</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>

Try this as your code have lots of problems
code of new html file
<!DOCTYPE html>
<html>
<body>
<form>
enter digit :
<input type="text" id="id" name="id" onkeyup='showUser(this.value)'/>
<br />
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b>
</div>
<script>
function showUser(id) {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
else
{
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
document.getElementById("txtHint").innerHTML = httpRequest.responseText;
}
};
httpRequest.open("GET", "localhost/cart/guser.php?id=" + id, true);
httpRequest.send();
}
}
</script>
</body>
</html>
and code of new guser.php file
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$id = intval($_GET['id']);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cart";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db('cart',$con);
$sql="SELECT * FROM user_details WHERE id = '".$id."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>email</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
Hope this helps!!..Comment for further queries

Try This:
Add in head:<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
you have to type person id in inputbox and user info in texthint div:
you will get id in guser.php of user from post and run query.and echo user info into guser.php file
<script type="text/javascript">
function showUser($id){
$("#email").keyup(function(){
$.ajax({
type: "POST",
url: "http://localhost/cart/guser.php",
data:'keyword='$id,
success: function(data){
$("#txtHint").html(data);
}
});
});
}
</script>

Either you should remove the , from httpRequest.open("GET", "http://localhost/cart/guser.php?id="+id+"&rand="+,true); jsut before true to make rand=true
or remove the + from the url just after &rand="

Related

Changing css depending on SQL value

I'm new to both php and jquery, and i'm trying to create a webpage which shows players and it's status based on data from my Mysql server.
The base code works, although the code scraped together from multiple youtube tutorials :)
I would like to change the opacity of a player's row when it's status is, or becomes 0 (dead).
This is the code i have so far :
pagetest.php:
<!DOCTYPE html>
<html>
<head>
<title>pagetest</title>
</head>
<body>
<table id="show">
<tr>
<td>player</td>
<td>status</td>
</tr>
</table>
<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
$('#show').load('test.php')
}, 3000);
});
</script>
</body>
</html>
test.php :
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
$conn = mysqli_connect("myserver", "myuser", "mypass", "mydb");
if ($conn-> connect_error) {
die("Connection failed:". $conn->connect_error);
}
$sql = "SELECT player, status FROM mytable";
$result = $conn->query($sql);
if ($result-> num_rows > 0) {
while ($row = $result->fetch_assoc()){
echo "<tr><td>" . $row["player"] . "</td><td>" . $row["status"] . "</td></tr>";
}
echo "</table>";
}
else {
echo "No game data available";
}
?>
</body>
</html>
I'd really appreciate your help :)
Is there any reason for using jQuery with it? If no, then you can use this code:
<body>
<?php
$conn = mysqli_connect("host", "user", "password", "database");
if ($conn-> connect_error) {
die("Connection failed:". $conn->connect_error);
}
$sql = "SELECT player, status FROM mytable";
$result = $conn->query($sql);
if ($result-> num_rows > 0) {
echo '<table id="show">
<tr>
<td>player</td>
<td>status</td>
</tr>';
while ($row = $result->fetch_assoc()){
$status = $row["status"];
$player = $row["player"];
echo "<tr style='" . ($status == 0 ? 'opacity: 0;' : '') . "'><td>" . $player . "</td><td>" . $status . "</td></tr>";
}
echo '</table>';
}
else {
echo "No game data available";
}
?>
</body>
You can do something like that:
echo '<tr class="player-status-'.$row["status"].'"><td>'. $row["player"] .'</td><td>' . $row["status"] . '</td></tr>';
Add a class to your line tr based in the $row["status"] so rendered you'll have something like this: <tr class="player-status-0"><td>cristiano ronaldo</td><td>0</td></tr>
this way you can create a style to this class with css
.player-status-0 {
opacity:
}
By the way, have thought about using ajax and return a json with the data?

Insert dynamically in the placeholders after writing in the text box

I want to insert data onto placeholders after I write in a text box. I found an alternative solution with Drop-down select:
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
Php file:
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
How to modify it if I want to use with Form::text('foo') and start to start search from mysql table immidiately?
You can replace the <select> with a text input and remove intval() and replaced with a prepared statement, since you don't want to be victim to an SQL injection.
Rererences:
https://en.wikipedia.org/wiki/Prepared_statement
https://en.wikipedia.org/wiki/SQL_injection
You can also use a case insensitive search method/function, and there are a few ways to go about this.
Using MySQL's LIKE function:
https://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html
Or a pattern match:
https://dev.mysql.com/doc/refman/5.7/en/pattern-matching.html
Or a WHERE clause:
https://dev.mysql.com/doc/refman/5.7/en/where-optimization.html
Depending on the search criteria.

AJAX: Display value from table in datase with <select> tag (incomplete submit)

I have a problem with my code.. when I'm submitting value of the in getinv.php it is submitting incomplete value for example, when I click '2016-08-27' it only returning '2016'..
My question is, How do I submit this with exact value I want..?
Pls. Help!
Here's my code:
index.php
<!DOCTYPE html>
<html>
<head>
<script>
function showProd(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getinv.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="date" onchange="showProd(this.value)">
<option value="">Select date here:</option>
<?php
$con = mysqli_connect('localhost','root','admin','posinventory');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT DATE FROM inventory WHERE DATE != DATE(NOW()) GROUP BY DATE DESC;";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<option value='".$row[0]."'>".$row[0]."</option>";
}
mysqli_close($con);
?>
</select>
</form>
<br>
<div id="txtHint"></div>
</body>
</html>
getinv.php
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
echo $q;
$con = mysqli_connect('localhost','root','admin','posinventory');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM inventory WHERE DATE = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>tran_num</th>
<th>date</th>
<th>item_num</th>
<th>inv_quan</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[3] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
This is my table
It seems that the date is being submitted correctly. Inside getinv.php, you are using intval, which returns the integer value from date and since date starts with a digit, it returns all digits up to but excluding the first dash, so '2016-08-27' becomes '2016'.
Replace
$q = intval($_GET['q']);
with
$q = $_GET['q'];

how can I select all the data from mysqltable and display them on html

Hello I am a new programmer with html and php and mysql. In fact I'd like to select all the data from a unique table in mysql and display them on html5 page.
I created a sms.html and when I run it with Chrome this is what I saw Normally I need to display a table with 5 th means 5 rows
Here is my code
<body>
<?php
echo "<table style='border: solid 1px black; border-collapse: collapse;
th, td {
padding: 5px;
text-align: left;
}'>";
echo "<tr>
<th>date/th>
<th>Etat de TX1</th>
<th>Etat de TX2</th>
<th>Sur antenne</th>
<th>ALARME</th> </tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width: 150px; border: 1px solid black;'>" .
parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "OACA";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM etat");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
</body>
Could you not do something like this?
<?php
`$result = null;
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "OACA";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM etat");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$count = $stmt -> rowCount();
$all = $stmt->fetchALL();
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
<div>
<table style='border: solid 1px black; border-collapse: collapse;
th, td {
padding: 5px;
text-align: left;
}'>
<thead>
<tr>
<th>date/th>
<th>Etat de TX1</th>
<th>Etat de TX2</th>
<th>Sur antenne</th>
<th>ALARME</th>
</tr>
</thead>
<tbody>
<?php
if($count > 0) {
//For each row echo <tr></tr>
foreach ($all as $item) {
echo"<tr>";
//For each column in the row echo each value in a <td></td>
foreach ($item as $key => $value) {
echo "<td>" . $value ."</td>";
}
"</tr>";
}
}
?>
</tbody>
</table>
</div>

Information is not returned while fetching it from MySQL using AJAX

I am following the this tutorial from W3 schools. While mostly everything works fine, it doesn't seem to be returning any of the actual information from the MySQL database I made, called exercises in the exercisedb database.
Below is the code for index.php
<head>
<title>
Database Fetch Demo
</title>
<script>
function showExercise(str) {
if (str == "") {
document.getElementById("txtPlaceholder").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtPlaceholder").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getexercise.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="exercises" onchange="showExercise(this.value)">
<option value="">Choose an Exercise</option>
<option value="1">Bench Press</option>
<option value="2">Deadlift</option>
<option value="3">Barbell Squat</option>
</select>
</form>
<br>
<div id="txtPlaceholder">
<b>No exercise selected.</b>
</div>
<body>
</html>
And below is the code for getexercise.php
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table td, td{
border: 1px solid black;
padding: 5px;
}
th {text-align: left};
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$connect = mysqli_connect('localhost','root','root','exercisedb');
if(!$connect){
die('Could not connect ' . mysqli_error($connect));
}
mysqli_select_db($connect, "exercisedb");
$sql = "SELECT * FROM exercises WHERE id = '".q."'";
$result = mysqli_query($connect, $sql);
echo "<table>
<tr>
<th>Exercise Name</th>
<th>Difficulty</th>
<th>Target Areas</th>
<th>Description</th>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['difficulty'] . "</td>";
echo "<td>" . $row['targetareas'] . "</td>";
echo "<td>" . $row['description'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($connect);
?>
</body>
</html>
You should not send a
<!DOCTYPE html>
<head>
<body>
in your ajax answer only the content of the div you expect.

Categories