I have an HTML table which I want to update every 1 second on page. It have few div and classes within. So I tried AJAX to update it every 1 second. HTML is this:-
<div class="abcd">
<div style='float: left;'>
<br><br>
<p style="padding-left:16px; font-size: 20px;">Amount(<?php echo $market; ?>) | Price(<?php echo $bm; ?>)   | Total(<?php echo $bm; ?>)</p>
<div class="panel-hello scrollbar" id="style-11">
<div class="data-table">
<table class="table table-hello table-bordered table-hover force-overflow" id="btcaddresses">
<tbody style="border: 1px solid green; height: 300px; overflow-y: scroll;">
</tbody>
</table>
</div>
</div>
</div>
And AJAX script:-
function loadXMLDoc()
{
var xmlhttp;
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.getElementsById("btcaddresses").innerHTML=xmlhttp.responseText; // your div
}
}
xmlhttp.open("GET","getdatabase.php",true); //your php file
xmlhttp.send();
}
window.setInterval(function(){
loadXMLDoc();
}, 1000);
And getdabase.php contains:-
<?php
require('../setup.php');
$seql = "select price, sum(total), sum(aleft) from trade where status = 'active' and bm = 'USD' and m = 'BTC' and type = 'sell' group by price";
$query100 = mysqli_query($conn, $seql);
while ($row = mysqli_fetch_array($query100))
{
echo '<tr style="cursor: pointer; font-size: 15px;">
<td>'.number_format($row['sum(aleft)'], 8).'</td>
<td>'.number_format($row['price'], 8).'</td>
<td>'.number_format($row['sum(total)'], 8).'</td>
</tr>';
}
mysqli_close($conn);
?>
Problem is , it is not working and even if does it's not having any table classes specified in class.
<?php
require('../setup.php');
$seql = "select price, sum(total), sum(aleft) from trade where status = 'active' and bm = 'USD' and m = 'BTC' and type = 'sell' group by price";
$query100 = mysqli_query($conn, $seql);
$result = '';
while ($row = mysqli_fetch_array($query100))
{
$result .= '<tr style="cursor: pointer; font-size: 15px;">
<td>'.number_format($row['sum(aleft)'], 8).'</td>
<td>'.number_format($row['price'], 8).'</td>
<td>'.number_format($row['sum(total)'], 8).'</td>
</tr>';
}
mysqli_close($conn);
echo $result;
?>
This should work, but indeed you should return a json.
Edit : full html code working fine for me : (I had to remove some php parts)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="abcd">
<div style='float: left;'>
<br>
<br>
<!-- <p style="padding-left:16px; font-size: 20px;">Amount(<?php echo $market; ?>) | Price(<?php echo $bm; ?>)   | Total(<?php echo $bm; ?>)</p> -->
<div class="panel-hello scrollbar" id="style-11">
<div class="data-table">
<table class="table table-hello table-bordered table-hover force-overflow" id="btcaddresses">
<tbody style="border: 1px solid green; height: 300px; overflow-y: scroll;">
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
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("btcaddresses").innerHTML = xmlhttp.responseText; // your div
}
}
xmlhttp.open("GET", "getdatabase.php", true); //your php file
xmlhttp.send();
}
window.setInterval(function () {
loadXMLDoc();
}, 1000);
</script>
</body>
</html>
Related
I have a AJAX example (from W3Schools) I'm trying to run on my server:
HTML:
<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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q=1?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">Sophia</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
PHP (getuser.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']);
// connect to db
$sql="SELECT * FROM names WHERE first = '".$q."'";
$result = mysqli_query($web_dbi, $sql) or die("Error " . mysqli_error($web_dbi));
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>grad year</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['first'] . "</td>";
echo "<td>" . $row['last'] . "</td>";
echo "<td>" . $row['gradyear'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
I'm getting two errors on console. First, upon loading the page:
Font from origin 'url1' has been blocked from loading by Cross-Origin
Resource Sharing policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'url2' is therefore not
allowed access.
Then, when I select an option value from the drop-down the console get caught up at "xmlhttp.send();" with the message:
GET (url.getuser.php?q=1) 404 (Not Found)
Any help is appreciated.
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.
I needed to add runtime rows on a table and then send data to database. I managed to do most of it however I am stuck on 2 parts of the program.
I am using Ajax to check the available quantity from a drop down, which I wish to display in the corresponding row, but cant, I have been able to alert the correct value so far).
The php post is sending me one parameter less than is available on the form if I fill any row, but send me the correct amount of parameters if I add rows and don’t fill any information. ( ie if I add 3 blank rows and click on submit it submits 4 values, -> because one row is hidden however if I fill any of the 3 rows in the screen it sends as parameter only 3 post for $name)
function getSpQty(strURL) {
var xmlhttp;
console.log(this)
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) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
document.getElementById('sp').value = xmlhttp.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + xmlhttp.statusText);
}
}
}
xmlhttp.open("GET", strURL, true);
xmlhttp.send(null);
}
<?php include_once( "dbConn-SP.php"); $sqlSP="select * from dbo.SparepartManagement" ; $stmtSP=s qlsrv_query($connIgms, $sqlSP); ?>
<html>
<head>
<script src="js/jquery1.7.js"></script>
<script>
$(document).ready(function() {
var id = 0;
// Add button functionality
$("table.dynatable button.add").click(function() {
id++;
var master = $(this).parents("table.dynatable");
// Get a new row based on the prototype row
var prot = master.find(".prototype").clone();
prot.attr("class", "")
prot.find(".id").attr("value", id);
master.find("tbody").append(prot);
});
// Remove button functionality
$("table.dynatable button.remove").live("click", function() {
$(this).parents("tr").remove();
});
});
</script>
<style>
.dynatable {
border: solid 1px #000;
border-collapse: collapse;
}
.dynatable th,
.dynatable td {
border: solid 1px #000;
padding: 2px 10px;
width: 170px;
text-align: center;
}
.dynatable .prototype {
display: none;
}
</style>
<script type="text/javascript" language="JavaScript1.2" src="spQty.js"></script>
</head>
<body>
<form action="test.php" method="post" name="frm">
<table width="100%" class="dynatable">
<thead>
<tr>
<th width="144">ID</th>
<th width="144">Spareparts</th>
<th width="144">Quanitity</th>
<th width="144">Issued Quantity</th>
<th width="140">
<button type="button" class="add">Add</button>
</th>
</tr>
</thead>
<tbody>
<tr class="prototype">
<td>
<input type="text" name="id[]" value="0" class="id" />
</td>
<td>
<select style="width:200px" name="name[]" id="sp" onChange="getSpQty('SPName.php?spareparts='+this.value)">
<option value="error">Select Spare Parts</option>
<?php while($viewAllSP=s qlsrv_fetch_array($stmtSP,SQLSRV_FETCH_ASSOC)) { echo "<option value='$viewAllSP[GeneralItemDescription]'>$viewAllSP[GeneralItemDescription]</option>\n"; }; ?>
</select>
</td>
<td>
<input type="text" name="col4[]" value="" />
</td>
<td>
<input type="text" name="col3[]" value="" />
</td>
<td>
<button class="remove">Remove</button>
</td>
</tr>
</table>
<input type="submit" value='send' />
</form>
</body>
</html>
this is the SPName.php
include_once("dbConn-SP.php");
$spareparts=$_REQUEST['spareparts'];
$tsqls = "select InitialQty from SparepartManagement where GeneralItemDescription ='$spareparts'";
$params = array();
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query($connIgms, $tsqls , $params, $options);
$row_count = sqlsrv_num_rows($stmt);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$test = $row['InitialQty'];
}
echo $test;
?>
here is test.php
<?PHP
error_reporting(0);
include_once("dbConn-SP.php");
$Qty = $_POST["col4"];
$IssuedQty = $_POST["col3"];
$name= $_POST["name"];
//Step 3: Insert statment
print_r($name);
for ($i = 1; $i < sizeof($Qty); $i++) {
$j=$i-1;
$Insert = "INSERT INTO SparepartTransaction (SPDesc,InitialQty,QtyIssued) Values ".
" ('$name[$j]','$Qty[$i]','$IssuedQty[$i]')";
$stmt = sqlsrv_query($connIgms,$Insert);
}
sqlsrv_close($connIgms);
?>
unfortunately i do not have enough reputation to post a image here so here is a link with the actual display on my screen
http://prntscr.com/749n4n
what i want is that instead of having an alert as -> alert(xmlhttp.responseText);
i wish this value to be displayed on the cell beside the drop down. any help will be appreciated.
How to convert xmlhttp.responseText to js array
this is my {"name":"Eswara Manikanta Varma","email":"eswar1251#gmail.com","mobile":"9966578911"} getting from xmlhttp.responseText so now i want to convert in js array..
when ever i'm alerting var object the alert seem like this [object Object]
I would like to print it as jsarray[mobile]
my page 1 :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Invoice</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<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)
{
var object = JSON.parse(xmlhttp.responseText);
alert(object);
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<header>
<h1>Invoice</h1>
<address contenteditable>
<p>Jonathan Neal</p>
<p>101 E. Chapman Ave<br>Orange, CA 92866</p>
<p>(800) 555-1234</p>
</address>
<span><img alt="" src="logo.png"><input type="file" accept="image/*"></span>
</header>
<article>
<h1>Recipient</h1>
<address contenteditable>
<p>Some Company<br>c/o Some Guy</p>
</address>
<form>
<table class="meta">
<tr>
<th><span contenteditable>Invoice #</span></th>
<td><span contenteditable>101138</span></td>
</tr>
<tr>
<th><span contenteditable>Date</span></th>
<td><span contenteditable>January 1, 2012</span></td>
</tr>
<tr>
<th><span contenteditable>Amount Due</span></th>
<td><span id="prefix" contenteditable>$</span><span>600.00</span></td>
</tr>
</table>
<table class="inventory">
<thead>
<tr>
<th><span contenteditable>Item</span></th>
<th><span contenteditable>Description</span></th>
<th><span contenteditable>Rate</span></th>
<th><span contenteditable>Quantity</span></th>
<th><span contenteditable>Price</span></th>
</tr>
</thead>
</body>
</html>
page 2 :
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','enter','esmart');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,'esmart');
$sql="SELECT * FROM suppliers WHERE name LIKE '%$q%'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$x['name']=$row['name'];
$x['email']=$row['email'];
$x['mobile']=$row['mobile'];
}
echo json_encode($x);
mysqli_close($con);
?>
I think your problem is in the PHP code.
with this:
while($row = mysqli_fetch_array($result))
{
$x['name']=$row['name'];
$x['email']=$row['email'];
$x['mobile']=$row['mobile'];
}
echo json_encode($x);
You're going to get only the last row of your query.
To be able to get an array you may need something like this:
$response = array();
while($row = mysqli_fetch_array($result))
{
$x['name']=$row['name'];
$x['email']=$row['email'];
$x['mobile']=$row['mobile'];
$response[] = $x;
}
echo json_encode($response);
Now you'll get [{"name":"Eswara Manikanta Varma","email":"eswar1251#gmail.com","mobile":"9966578911"}, ...] and after JSON.parse it will be an array of objects.
try to use:
mysqli_fetch_assoc($result)
instead of
mysqli_fetch_array($result)
<!--viewservice.php-->
On blur i send data to get_service_category.php with the help of ajax function getservice_search. Before sending i alert the variable it give full string as Buff & Gelcoat [Acrylic Nail Enhancement] but when it is posted to get_service_category.php and then echoed back to the page it just print Buff after that it is trimmed
<label>Search Service</label>
<input type='text' name='country' id="select_service" value='' class='auto' onblur="getservice_search(this.value)"/>
<img src="img/icons/search-50.png" height="22" width="22" style="padding-left:5px;margin-bottom:-5px;cursor:pointer;" id="search" alt="Search" title="Click To Search" />
<script type="text/javascript" src="../js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/javascript">
$(function() {
//autocomplete
$(".auto").autocomplete({
source: "search_services.php",
minLength: 1
});
});
</script>
<script type="text/javascript">
function getservice_search(x)
{
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("box1").innerHTML=xmlhttp.responseText;
}
}
var select_service = document.getElementById("select_service").value;
alert(select_service);
xmlhttp.open("GET","get_service_category.php?select_service="+select_service,true);
xmlhttp.send();
}
</script>
enter code here
<!--get_service_category.php -->
<?php
include('../config/connect.php');
include('unset_super_admin.php');
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
if(isset($_GET['service_category']))
{
$service_category = $_GET['service_category'];
$sql ="select * from services where service_cat_id='$service_category' ";
}
else if($_GET['select_service'])
{
$select_service=clean($_GET["select_service"]);
$sql ="select * from services where service_name='$select_service' ";
}
else if($_GET['select_service']=="")
{
$sql ="select * from services";
}
$result_services = mysql_query($sql);
if($result_services)
{
echo $select_service;
?>
<table style="text-align:center;" class="viewcustomer">
<tr>
<th>Id</th>
<th>Service Name</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
while($rowresult=mysql_fetch_array($result_services))
{
echo "<tr>";
echo "<td>$rowresult[service_id]</td>";
echo "<td>$rowresult[service_name]</td>";
echo "<td>$rowresult[service_price]</td>";
echo '<td><Img src="img/icons/button_edit.gif" title="EDIT" alt="EDIT SERVICE" /> </td>';
echo "</tr>";
}
}
?>
You neglected to URL-encode your values properly – & in a query string separates parameters from each other, so ?select_service=Buff & Gelcoat… would mean one parameter named select_service with value Buff, and then a second parameter named Gelcoat….
Use encodeURIComponent on the value before putting it into the query string.