How to refresh data in table using ajax? - javascript

I'm new to ajax. I just want to simply view my table from the database using ajax. I have 2 files listbarang.html and showlist.php.
Here's my code
PHP (showlist.php)
<?php
$link = #mysqli_connect("localhost", "root", "","projekpweb");
if($link->connect_errno)
{
echo "Failed to connect. " . $link->connect_error;
}
$sql = "SELECT * FROM `barang`";
$result = mysqli_query($link, $sql);
if(!$result)
{
die("SQL GAK KONEK : " . mysqli_error($link));
}
echo "<table>
<tr>
<th>idbarang</th>
<th>nama</th>
<th>harga</th>
<th>ekstensi_gambar</th>
</tr>";
while ($row = mysqli_fetch_array($result))
{
echo " <tr>
<td>".$row["idbarang"]."</td>
<td>".$row["nama"]."</td>
<td>".$row["harga"]."</td>
<td>".$row["ekstensi_gambar"]."</td>
</tr>";
}
echo "</table>"; ?>
HTML (listbarang.html)
<!DOCTYPE html>
<html>
<head>
<title>LIST BARANG</title>
<script type="text/javascript">
function showList()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("tblList").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","showlist.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="tblList">
<script type="text/javascript">
showlist();
</script>
</div>
</body>
</html>
I wonder why the #tblList doesnt have the content of the the table.
Thanks in advance

Related

How to get onclick to display contents of php file

I am having a problem getting an onclick function to work.
Clicking on "units" in the HTML file, "unit_test" disappears and the contents of unit_display.php shows up instead. This is what I want to happen.
If I click on "Phoenix", however, "prop_test" remains and the results of prop_display.php do not appear.
I can browse to prop_display.php?city=Phoenix and it will pull up the list of properties from that table, so this rules out prop_display.php code as the culprit.
Here is my html file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
<script>
function showProp(str) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("propDisplay").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","prop_display.php?city="+str,true);
xmlhttp.send();
}
function showUnit(str) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("unitDisplay").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","unit_display.php?prop_id="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div onclick="showProp(Phoenix)">Properties</div>
<div onclick="showUnit(8)">units</div>
<br>
<div id="propDisplay">prop_test</div>
<div id="unitDisplay">unit_test</div>
</body>
</html>
Here is prop_display.php:
<?php
include('vars.php');
$city = strval($_GET['city']);
print $city;
if (!$link) {
die('Could not connect: ' . mysqli_error($con));
}
if ($prop_query = mysqli_query($link, "SELECT * FROM property WHERE city='$city' ORDER BY street asc")){}
while ($prop_array = mysqli_fetch_array($prop_query, MYSQLI_BOTH)){
$prop_id=$prop_array['prop_id'];
print " <li><div onclick=\"showUnit($prop_id)\"><a href=\"#\">" . $prop_array['name'] . "<br>
" . $prop_array['street'] . "</a></div>
";
}
mysqli_close($link);
?>
And here is unit_display.php:
<?php
include('vars.php');
$prop_id = intval($_GET['prop_id']);
print $prop_id;
if (!$link) {
die('Could not connect: ' . mysqli_error($con));
}
if ($unit_query = mysqli_query($link, "SELECT * FROM units WHERE prop_id='$prop_id' ORDER BY unit asc")){}
while ($unit_array = mysqli_fetch_array($unit_query, MYSQLI_BOTH)){
print " <li>" . $unit_array['unit'] . "</li>
";
}
mysqli_close($link);
?>
It seems like you are trying to have them click with Phoenix being an object when it should be a string.
Replace this:
<div onclick="showProp(Phoenix)">Properties</div>
with this:
<div onclick="showProp('Phoenix')">Properties</div>

PHP XmlHttpRequest error with simple to-do list

Being new to PHP and ajax XmlHttpRequest calls altogether, I am struggling to figure out what is wrong with my code. Gone through the documentation but it seems I'm struggling to put the db row names into an array. I ideally want to asynchronously display an innerHTML below the input to indicate whether the item is in db or not. Right now it is showing 'undefined' as seen below until I type the last item in the db. it's only responding to the last item in the db meaning there's probably an issue with my loop. Any help is welcome.
index.php
<?php
include 'db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="js/todo.js" type="text/javascript"></script>
<script>
</script>
</head>
<body onload="process()">
<div class="list">
<h1 class="header">My To Do</h1>
<form>
<ul class="items">
<?php
$sql = "SELECT * FROM items ORDER BY items.id ASC";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<li><input type='checkbox' /><label>";
echo $row['name'];
echo "</label></li><br>";
}
} else {
echo "There are no to-dos!";
}
echo "<br/><br/>";
echo "<li><input type='checkbox' /><label>Mark all as completed</label></li>";
?>
</ul><br />
</form>
</div>
<div class="list">
<form class="item-add" method="post">
<input type="text" id="name" name="name" placeholder="Enter new item" class="input" autocomplete="off" required>
<input name="myBtn" type="submit" value="Add Item">
<div id="status"></div>
</form>
</div>
</body>
item.php
<?php
include 'db.php';
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM items ORDER BY items.id ASC";
$result = mysqli_query($conn, $sql);
$itemArray = array();
$rowNum = mysqli_num_rows($result);
//is this the correct way to add db items to an array?
if($rowNum > 0){
while ($row = mysqli_fetch_assoc($result)){
for ($x = 0; $x <= $rowNum; $x++) {
$itemArray[$x] = $row['name'];
}
}
} else {
echo "There are no to-dos!";
}
$entry = $_GET['name'];
if(in_array($entry, $itemArray))
echo 'Item ' .$entry. ' already exists! Please enter a new item...';
elseif ($name == '')
echo "Please enter an item...";
else {
//code for insertion
echo "Successfully Inserted";
}
echo '</response>';
?>
item.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if(window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch(e) {
xmlHttp = false;
}
}
if(!xmlHttp) {
alert("cant create that object hoss");
} else {
return xmlHttp;
}
}
function process() {
if (xmlHttp.readyState==0 || xmlHttp.readyState==4) {
name = encodeURIComponent(document.getElementById('name').value);
xmlHttp.open("GET", "item.php?name="+name, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} else {
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4) {
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
console.log(xmlResponse.documentElement);
message = xmlDocumentElement.firstChild.data;
document.getElementById('status').innerHTML =
'<span style="color:blue">' + message + '</span>';
setTimeout('process()', 1000);
} else {
alert('Something went wrong!');
}
}
}
$name is not defined in your PHP file , Shouldnt it be $entry that you are checking in the elseif condition below
$entry = $_GET['name'];
if(in_array($entry, $itemArray))
echo 'Item ' .$entry. ' already exists! Please enter a new item...';
elseif ($entry == '')
echo "Please enter an item...";
else {
//code for insertion
echo "Successfully Inserted";
}
also the correct way to assign a DB column to an array should be like below .
if($rowNum > 0){
while ($row = mysqli_fetch_assoc($result)){
$itemArray[] = $row['name'];
}
} else {
echo "There are no to-dos!";
}

Using AJAX, PHP and MySQL to display table data

I would like to display one column of data, [pin], based on the [plan] and [order_id] values. plan=9 and order_id=0. Would like to load data without reloading page, using ajax.
Here is my HTML/Script:
<script>
function showPins(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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getPins.php?q="+str,true);
xmlhttp.send();
}
}
</script>
HTML:
<div align="center">
<h3>View PIN's</h3>
<form>
<select name="users" onchange="showPins(this.value)">
<option value="">Select Plan Type:</option>
<option value="1">Plan1</option>
<option value="2">Plan2</option>
<option value="3">Plan3</option>
</select>
</form>
<br/>
<div id="txtHint"></div>
</div>
This is my PHP file (getPins.php):
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('myHost','myUsername','myPw','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"my_db");
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>PIN's</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['pin'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
This is based off the tutorial shown here: http://www.w3schools.com/php/php_ajax_database.asp
Trying to make it work for showing the correct pins for plan type chosen.
your query would be wrong read manual where
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
It would be
WHERE (order_id=0 and plan=9 and id = '".$q."')
Or
WHERE (order_id=0 OR plan=9 and id = '".$q."')
according to your requirment

How to echo style and script tags using php

hello i have a php page that is to output results in my html page using div through an ajax request medium,
i intend outpiting this results using listviews as my application targets mobile phones and tablets, so i am making use of the jquery mobile framework.
i have outputed my results successfully with this
<?php header('Access-Control-Allow-Origin: *'); ?>
<?php
$users = ($_GET['users']);
$user = ($_GET['user']);
$con = mysqli_connect('localhost','whitech3_manage','famakin','whitech3_manage');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"whitech3_manage");
$sql="SELECT * FROM data WHERE fromwhere = '".$users."' and towhere = '".$user."'";
$result = mysqli_query($con,$sql);
echo '<head>';
echo "<link rel='stylesheet' href='themes/transport.min.css' />";
echo "<link rel='stylesheet' href='themes/jquery.mobile.icons.min.css' />";
echo "<link rel='stylesheet' href='themes/jquery.mobile.structure-1.4.2.min.css' />";
echo "<script src='themes/jquery-1.10.2.min.js'></script>";
echo "<script src='themes/jquery.mobile-1.4.2.min.js'></script>";
echo '</head>';
while($row = mysqli_fetch_array($result)) {
echo "<div data-role='collapsible' data-theme='b' data-content-theme='b'>";
echo "<ul data-role='listview' data-filter='true'>";
echo "<li><a href='#'>". $row['fromwhere'] . "</a></li>";
echo "<li><a href='#'>". $row['towhere'] . "</a></li>";
echo "<li><a href='#'>". $row['details'] . "</a></li>";
echo "<li><a href='#'>". $row['time frame'] . "</a></li>";
echo "</ul>";
echo "</div>";
}
mysqli_close($con);
?>
but whenever my results are displayed they r not formatted properly to look like a listview, hence i knw i am supposed to load my style sheets and javascript tags to make sure the listview is displayed properly.
i have tried and tried to echo the links to my stylesheets and js using echo statements, but it dosent seem to make my listview show up properly.
this is what i have tried
echo '<head>';
echo "<link rel='stylesheet' href='themes/transport.min.css' />";
echo "<link rel='stylesheet' href='themes/jquery.mobile.icons.min.css' />";
echo "<link rel='stylesheet' href='themes/jquery.mobile.structure-1.4.2.min.css' />";
echo "<script src='themes/jquery-1.10.2.min.js'></script>";
echo "<script src='themes/jquery.mobile-1.4.2.min.js'></script>";
echo '</head>';
function showUser() {
if (showUser == "") {
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
var usersvalue=encodeURIComponent(document.getElementById("users").value)
var uservalue=encodeURIComponent(document.getElementById("user").value)
xmlhttp.open("GET","http://whitechapelandpartners.com/getuserwrong.php?users="+usersvalue+"&user="+uservalue, true);
xmlhttp.send();
}
}
<div id="txtHint"><b>Person info will be listed here.</b></div><br /><br /><br /><br />
</div>
any suggestion please, by logic i was hoping the echo statement would work
Here is my suggestion
<?php header('Access-Control-Allow-Origin: *'); ?>
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='themes/transport.min.css' />
<link rel='stylesheet' href='themes/jquery.mobile.icons.min.css' />
<link rel='stylesheet' href='themes/jquery.mobile.structure-1.4.2.min.css' />
<script type="text/javascript" src='themes/jquery-1.10.2.min.js'></script>
<script type="text/javascript" src='themes/jquery.mobile-1.4.2.min.js'></script>
<script type="text/javascript">
function showUser(user) { // how do you call this? You need to pass it a user too
if (user == "") {
$("#txtHint").empty();
return;
}
var usersvalue=encodeURIComponent($"#users").val()),
uservalue=encodeURIComponent($("#user").val());
// assuming you are accessing the same origin
$.get("/getuserwrong.php?users="+usersvalue+"&user="+uservalue,
function(data) {
$("#txtHint").html(data);
}
);
}
</script>
</head>
<body>
<?php
$users = ($_GET['users']);
$user = ($_GET['user']);
// I think you do not want to show your userID and password here on this site
$con = mysqli_connect('localhost','...','...','...');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"whitech3_manage");
$sql="SELECT * FROM data WHERE fromwhere = '".$users."' and towhere = '".$user."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo <<<EOT
<div data-role='collapsible' data-theme='b' data-content-theme='b'>
<ul data-role='listview' data-filter='true'>
<li><a href='#'>$row['fromwhere']</a></li>
<li><a href='#'>$row['towhere']</a></li>
<li><a href='#'>$row['details']</a></li>
<li><a href='#'>$row['time frame']</a></li>
</ul>
</div>
EOT;
}
mysqli_close($con);
?>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
try this :
function showUser() {
if (showUser == "") {
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var collapsible = xmlhttp.responseText;
document.getElementById("txtHint").innerHTML = $(collapsible).collapsible();
}
}
var usersvalue=encodeURIComponent(document.getElementById("users").value)
var uservalue=encodeURIComponent(document.getElementById("user").value)
xmlhttp.open("GET","http://whitechapelandpartners.com/getuserwrong.php?users="+usersvalue+"&user="+uservalue, true);
xmlhttp.send();
}
}
<div id="txtHint"><b>Person info will be listed here.</b></div><br /><br /><br /><br />
</div>
I hope this works. :D

Dynamic drop down with PHP MySQL and Java

Complete Dynamic drop down in PHP MySQL & AJAX with mysql Insert query works perfectly.
Code to insert date to MySQL table
<?php
require('../conn/include.php');
require('quick.php');
$query="SELECT * FROM category";
$result=mysql_query($query);
$project=$_POST['project'];
$alttext=$_POST['alttext'];
$relation=$_POST['state'];;
if(isset($_FILES['image'])) {
$errors=array();
$allowed_ext=array('jpg','png','jpeg','JPG');
$filename=$_FILES['image']['name'];
$name=stripslashes($filename);
$type=strtolower(end(explode('.',$filename)));
$size=$_FILES['image']['size'];
$file_tmp=$_FILES['image']['tmp_name'];
if(in_array($type,$allowed_ext) ===false) {
$errors[]= "<span class=\"notification n-error\">Extenstion Not Allowed</span>";
}
if($size > 1048576) {
$errors[]= "<span class=\"notification n-error\">File must be less then 2mb</span>";
}if(file_exists('../../images/a/gallery/'.$filename)) {
$errors[]= "<span class=\"notification n-error\">File $filname Already Exists in directory</span>";
}if(empty($errors)) {
if(move_uploaded_file($file_tmp, '../../images/a/gallery/'.$filename)) {
$insert="Insert into `my`.gallery(name,alttext,project,relation)VALUE('$name','$alttext','$project','$relation')";
//echo $insert;
$que=mysql_query($insert);
echo "<span class=\"notification n-success\">File $filname Uploaded Sucessfully</span>";
header('Refresh:3; url:gallery.php');
}
}else {
foreach($errors as $error) {
echo $error,'<br/>';
}
}
}
?>
AJAX Code
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getState(cate_id) {
var strURL="findsect.php?country="+cate_id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Code for Second Drop Down or findsec.php
<?php
$country=$_GET['country'];
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('my');
$query="SELECT * FROM gallery_section WHERE related='$country'";
$result=mysql_query($query);
?>
<select name="state" onchange="getCity(<?php echo $country?>,this.value)">
<option>Select State</option>
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['title']?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
Thanks to Nick Wilde who helped me.
I'm presuming you mean when the value of the option for the second drop down is multiple words. If that is the case the problem is you are missing quotes; use this instead:
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['title']?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
as the last three lines of your findsec.php

Categories

Resources