So I am trying to have a website update state and city lists from a server.
My code for states seems to work fine, the problem I have is with updating the city list. I adapted an answer from here earlier, and it doesn't seem to work, although that is most likely my fault.
here is the state php code.
<?php
$con= mysqli_connect($host, $user, $pass, $database);
if($debug){
echo $host,$user,$pass,$database;
}
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$states = '';
$resultState = mysqli_query($con,"SELECT DISTINCT State FROM CitiesStates");
while($row = mysqli_fetch_array($resultState))
{
if($debug){
echo $row['State'];
}
$states .="<option>" . $row['State'] . "</option>";
}
$statesDrop="
<p><label>States</label></p>
<select name='States' id='States' onchange='getCity(this.value))'>
" . $states . "
</select>";
echo $statesDrop;
mysqli_close($con);
?>
so on selection it should call this function.
<script type="text/javascript">
function getCity(stateId)
{
var strURL="findCity.php?state="+stateId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) // only if "OK"
{
if (req.status == 200)
{
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
which calls this php file.
$stateId=intval($_GET['state']);
$con= mysqli_connect($host, $user, $pass, $database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Cities = '';
$resultCity = mysqli_query($con,"SELECT City FROM CitiesStates WHERE State='$stateId'");
while($row = mysqli_fetch_array($resultCity))
{
if($debug){
echo $row['City'];
}
$Cities .="<option>" . $row['City'] . "</option>";
}
$citiesDrop="
<p><label>Cities</label></p>
<select name='Cities' id='Cities' onchange=''>
" . $Cities . "
</select>";
echo $citiesDrop;
mysqli_close($con);
?>
Additionally my getXMLhttp() function, since this seems to be the problem
function getXMLHTTP() {
var x = false;
try {
x = new XMLHttpRequest();
}catch(e) {
try {
x = new ActiveXObject("Microsoft.XMLHTTP");
}catch(ex) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1) {
x = false;
}
}
}
return x;
}
I think it is due to this in findCity.php
$citiesDrop="
<p><label>States</label></p>
<select name='States' id='States' onchange='getCity(this.value))'>
" . $states . "
</select>";
It looks like you copied it from your state php code, but did not update it correctly. You php page is probably sending a req.status of 500, as $states is not defined. Try updating to -
$citiesDrop="
<p><label>Cities</label></p>
<select name='Cities' id='Cities'>
" . $Cities . "
</select>";
Related
I am beginner in the PhP and Jquery. So, may be the solution to this question will be easy. I am successfully updating table using ajax and PhP. The issue is that table is updated by removing the all the data, and then populating new data.
I am looking for any other approach. After getting new data through PhP, compare new data with old data,...if there is some issue in hardware, then change the status..also keep the time from which the hardware stopped working. I ask question before Put data from Postgresql database to table using Ajax and PhP, in which #Mcsky suggested me a solution, but I did not get his approach. So, How to update table data only?, instead of complete refresh of table, which feels like page refresh. here is my client code: estat_hardware.php
<!DOCTYPE html>
<html>
<head>
<style> <?php include './../css/estat_hardware.css'; ?> </style>
</head>
<body>
<div class="maindiv">
<div id="tagsDiv">
<h3>Estat Tags</h3>
<?php
echo '<table id="tags_table">';
echo "<thead>";
echo "<tr>";
echo '<th>' . "TAG" . '</th>';
echo '<th>' . "BATERIA" . '</th>';
echo '<th>' . " VIST ĂšLTIMA COP " . '</th>';
echo '<th>' . "ESTAT" . '</th>';
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "</tbody>";
echo '</table>';
?>
</div>
</div>
<script src='http://code.jquery.com/jquery-3.1.1.min.js'></script>
<script>
$(document).ready(function(){
UpdateHTMLTable();
setInterval(function() {
UpdateHTMLTable();
}, 5000); // 5000 millisecond(5 second)
function UpdateHTMLTable(){
/* $('#tags_table tbody').empty(); */
$('#tags_table tbody').html("");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
for (i = 0; i < data.length; i++) {
console.log(data[i]);
var row = $("<tr />");
$("<td />").text(data[i].mac).appendTo(row);
$("<td />").text(data[i].battery).appendTo(row);
$("<td />").text(data[i].ts).appendTo(row);
$battery_beacon=data[i].battery;
if($battery_beacon<15)
{
$status="Canvi Batteria";
}
else{
$status="Correcte ";
}
$("<td />").text($status).appendTo(row);
row.appendTo('#tags_table');
}
}
};
xmlhttp.open("GET", "pages/estat_hardware_server.php", true);
xmlhttp.send();
}
});
</script>
</body>
</html>
Server code is:
<?php
header("Content-Type: application/json; charset=UTF-8");
$host = ip";
$port ="portNumber";
$user = "abc";
$pass = "....";
$db = "name";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "query string for database";
$result = pg_query($con, $query) or die("Cannot execute query: $query\n");
if(pg_num_rows($result))
{
$data=array();
while($row=pg_fetch_array($result))
{
$data[] = array(
'mac'=>$row['mac'],
'ts' =>$row['ts'],
'battery'=>$row['battery']
);
}
echo json_encode($data);
pg_free_result($result);
pg_close($con);
}
?>
So I have an SQL database and table, and a php file calls the 10 results from it like this.
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$password = "";
$database = "c9";
$dbport = 3306;
$con = mysqli_connect($servername, $username, $password, $database, $dbport);
if (!$con) {
die("Error! Check your internet connection and try again!");
}
mysqli_select_db($con, "users");
$query = "SELECT * FROM users LIMIT 10";
$result = mysqli_query($con, $query);
echo "<table>
<tr>
<th>ID</th>
<th>Village</th>
<th>Power</th>
<th>Influence</th>
<th>Economy</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['village'] . "</td>";
echo "<td>" . $row['power'] . "</td>";
echo "<td>" . $row['influence'] . "</td>";
echo "<td>" . $row['economy'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
This is an JQuery ajax script I made but it doesn't seem to work
$(document).ready(function(){
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//document.getElementById("divTable").innerHTML=xmlhttp.responseText;
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "/server.php", true);
xmlhttp.send(null);
});
return false;
What would be the best way to display this table from the php file on a separate index.html file. AJAX, JQuery AJAX, and XML are all options but I don't know how I would do this.
I ideally would want to display the result from the PHP file with document.getElementById('leaderboard').innerHTML because it would take all the html code, including the table.
Any help is greatly appreciated.
Use it!
In Ajax code:
var dataString = 'ajax=true';
$.ajax({
type: "GET",
url: "/server.php",
data: dataString,
dataType:'json',
success: function(data){
alert(data);
}
});
In PHP code:
$query = "SELECT * FROM users LIMIT 10";
$result = mysqli_query($con, $query);
echo json_encode($result); exit();
Basically I am trying to use a $gen variable to match a user query to a string stored in a database describing a genre of music. My problem is that if the genre is Indie/Pop and the user selects Indie as a search query the event will display. If they select Pop the event does not display.
Here is how i am querying the database.
$sql="SELECT * FROM $tab WHERE genre LIKE '$gen%'AND dateForm = '$datepicker'";
Any help appreciated as ever
php script to get info
<?php
$con = mysqli_connect('localhost','root','','python');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax");
$gen = $_GET['gen'];
$gen = mysql_real_escape_string($gen);
$tab = $_GET['tab'];
$tab = mysql_real_escape_string($tab);
$datepicker = $_GET['datepicker'];
$sql="SELECT * FROM $tab WHERE genre LIKE '%$gen%' AND dateForm = '$datepicker'";
$result = mysqli_query($con,$sql);
echo "<table class='table table-hover'><thead>
<tr>
<th><h3>Artist</th>
<th><h3>Location</th>
<th><h3>Date</th>
<th><h3>Genre</th>
<th><h3>Preview</th>
</tr></thead>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['artist'] . "</td>";
echo "<td> <b>Venue: </b>" . $row['venue'] . "<p><b>Location: </b>" . $row['location'] . "</td>";
echo "<td>" . $row['datez'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
echo "<td>" . '<iframe width="100%" height="100" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/' . $row['link'] . '&color=000000&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false"></iframe>' . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
The gen variable is made using AJAX
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var gen = document.getElementById('gen').value;
var datepicker = document.getElementById('datepicker').value;
var tab = document.getElementById('tab').value;
//var datepicker = document.getElementById('datepicker').value;
var queryString = "?gen=" + gen ;
queryString += "&datepicker=" + datepicker +"&tab=" + tab;
ajaxRequest.open("GET", "getuser.php" +
queryString, true);
ajaxRequest.send(null);
}
Okay, some security lessons in here. Bind the parameters $gen (with the wildcards added) and $datepicker in the prepared query. Since you can't bind column or table names, I'd run something like I did below with $tab and the allowed $tables array. This allows you to set a predefined list of tables that the query is allowed to run against and will throw an exception if the table provided is not in the list.
I don't like mysqli or procedural code so I don't use it much but I'm pretty sure everything is in order.
mysqli_select_db($con,"ajax");
// Add wildcards here
$gen = '%'.$_GET['gen'].'%';
$tab = $_GET['tab'];
$datepicker = $_GET['datepicker'];
// Check if $tab is in allowed tables (array $tables)
$tables = ['valid_table1', 'valid_table2', 'valid_table3'];
if (!in_array($tab, $tables)) {
throw new Exception('Hey, get outta here!');
}
$sql="SELECT * FROM $tab WHERE genre LIKE ? AND dateForm = ?";
// Prepare, bind, and execute
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt, 'ss', $gen, $datepicker);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result)) {
...
}
Try adding a % at the beginning of the search value
$sql="SELECT * FROM $tab WHERE genre LIKE '%$gen%'AND dateForm = '$datepicker'";
I am trying to send a value for an item in a MySQL table and increment its "availability" column by one.
A press of a button executes the following onclick function:
function updateStuff() {
// Data validation for string variable val
// coordinating to one of the items in the SQL table
var xmlHttp = false;
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
xmlHttp = new XMLHttpRequest();
}
if(!xmlHttp)
alert("Error : Cannot create xmlHttp object");
else{
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4){
xmlHttp.open("GET","update.php?val=" + val, true);
xmlHttp.send();
}
else{
setTimeout(updateStuff,1000);
}
}
}
update.php looks like this:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$item = $_GET['val'];
echo 'You selected ' . $item;
$server = "localhost";
$user = "root";
$pass = "";
$datab = "checkout";
// Connect to database
$db = mysqli_connect($server, $user, $pass, $datab);
// Check connection
if (mysqli_connect_errno()){
echo "Could not connect to database: " . mysqli_connect_error();
}
$results = mysqli_query($db,"SELECT * FROM inventory WHERE item = " . $item);
$available = $results['available'] + 1;
$result = mysqli_query($db, "UPDATE inventory SET available = " . $available . " WHERE item = " + $item);
// Close connection
mysqli_close($db);
echo '</response>';
?>
I think this is generally correct, unfortunately I'm not getting a table update when I execute the code. I am 100% confident in the validation for the variable val, and fairly confident with updateStuff(), but I'm less sure if I'm handling the server-side stuff corecctly with putting $_GET inside of response tags.
EDIT: I have made the syntax correction given by asparatu, but the problem persists.
The update query is wrong.
$result = mysqli_query($db, "UPDATE inventory SET available = available + 1 WHERE item = " + $item);
Where are you getting the current number for available?
you need a select statement that queries the current item and get current available amount then you can add one to it.
$results = mysqli_query($db,"SELECT * FROM inventory WHERE item = " . $item);
$available = $results['available'] + 1;
$result = mysqli_query($db, "UPDATE inventory SET available = " . $available . " WHERE item = " . $item);
That should work..
try this to update query:
$result = "UPDATE inventory SET available = "' .$available. '" WHERE item = "' .$item. '"";
if (mysqli_query($db, $result)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($db);
}
Hi i am using the html dropdown's onchange event using ajax
In the code i am using, should get the address column value when i change the
drop down.
but it is not working.What may have gone wrong?
here is the code
<html>
<head>
<script>
function showUser( 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", "getuser.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<?php
mysql_connect('localhost', 'tiger', 'tiger');
mysql_select_db('theaterdb');
$sql = "select theater_name from theater;";
$result = mysql_query($sql);
echo "<select name='theater_name' id='course' onchange='showUser(this.value);'>";
while ( $row = mysql_fetch_array( $result ) ) {
echo "<option value='" . $row['theater_name'] ."'>" . $row['theater_name']. "</option>";
}
echo "</select>";
?>
</form>
<br>
<div id="txtHint"><b>Info</b></div>
</body>
</html>
Code for getuser.php
<?php
$q = $_GET["q"];
$con = mysqli_connect("localhost", "tiger", "tiger", "theaterdb");
if ( !$con ) {
die('Could not connect: ' . mysqli_error( $con ) );
}
mysqli_select_db( $con );
$sql = "SELECT address FROM theater WHERE theater_name = '".$q."'";
$result = mysqli_query( $con, $sql );
echo "<table border='1'>
<tr>
<th>Firstname</th>
</tr>";
while( $row = mysqli_fetch_array( $result ) ) {
echo "<tr>";
echo "<td>" . $row['address'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Ok, I've tweaked your files slightly, you shouldn't be using mysql_ or the mysqli_ functions any more, just don't... And you certainly shouldn't be using mysql function in one file and mysqli functions in the other... I've switched them over to use PDO, you're script now isn't susceptible to SQL injection, and as far as I can tell it works just fine.
index.html
<html>
<head>
<script>
function showUser(str) {
if(str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT theater_name FROM theater;";
$sth = $dbh->prepare($sql);
$sth->execute();
echo "<select name='theater_name' id='course' onchange='showUser(this.value);'>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['theater_name'] ."'>" . $row['theater_name']. "</option>";
}
echo "</select>";
?>
</form>
<br>
<div id="txtHint"><b>Info</b></div>
</body>
</html>
getuser.php
<?php
$q = strtolower(trim($_GET["q"]));
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT address FROM theater WHERE LOWER(theater_name) = :q';
$sth = $dbh->prepare($sql);
$sth->bindValue(':q', $q);
$sth->execute();
echo "<table border='1'><tr><th>Firstname</th></tr>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td>" . $row['address'] . "</td>";
echo "</tr>";
}
echo "</table>";
$dbh = null;
I am unable to understand why have you connected with database in both of php files ?
I would suggest you to visit below link.
http://www.w3schools.com/php/php_ajax_database.asp