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.
Related
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>
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.
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'];
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="
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.