I have a program that gets an input from an HTML input field
<form method>
<input name="filmslike" id="input">
</form>
Then it goes through a javascript file that gets an ajax response from a PHP file
let div2Change = document.getElementById("div2Change");
let input = document.getElementById("input");
input.addEventListener("change", getTable);
function getTable(){
let ajax = new XMLHttpRequest();
ajax.open("GET", "filmslike.php");
ajax.send();
ajax.onreadystatechange = function(){
if (ajax.readyState == 4 && ajax.status == 200){
alert("in if");
array = JSON.parse(ajax.responseText);
str = "<table class='table'>";
for (i = 0; i < array.length; i++){
str += "<tr><td>" + array[i] + "</td></tr>";
}
str += "<table>";
div2Change.innerHTML = str;
}
}
}
the PHP file gives back an array from a database
require "DatabaseAdaptor.php"; // This includes class DatabaseAdaptor as if it where above this code.
$theDBA = new DatabaseAdaptor(); // constructor a DatabaseAdaptor object.
$moviesLike = $_GET['filmslike'];
$array = $theDBA->getAllMoviesLike($moviesLike);
echo json_encode($array);
and the database function returns items that are similar to $part
public function getAllMoviesLike($part) {
$stmt = $this->DB->prepare("SELECT * FROM movies WHERE name like '%" . $part . "%'");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
I don't understand why I'm not getting any change to my innerHTML. The alert says that it goes into the if statement (though it only activates inconsistently). I tried to use POST instead of GET, and it didn't work. What is wrong?
You don't send anything to the server for searching from AJAX. You need to add input value to the request:
ajax.open("GET", "filmslike.php?filmslike="+document.getElementById("input").value);
ajax.send();
Related
Ive searched high and low for information online for this question and have found absolutely nothing.
I have an admin.php file which gets a list of "unchecked" booking references;
$query = "SELECT * FROM $table WHERE servStatus = 'unchecked'";
And for each unchecked iteam thats returned i create a table with the status linked to the corresponding button;
echo "<tr>";
echo "<td colspan=2 style='text-align:center;'>";
echo "<input name=\"sbutton\" type=\"button\" onClick=\"confirm('confirm.php','content', $fetched_serv_ref)\" value=\"Confirm $fetched_serv_ref\" />";
echo "</td>";
echo "</tr>";
On click, i need this to update a status within the DB to 'checked' which is part of the confirm.php file;
$query = "UPDATE $table SET `servStatus` = 'checked' WHERE `assign2`.`servRef` = '$sbutton'";
and the corospong JS/HXR function is as the below;
var hr = createRequest();
function confirm(dataSource, divID, sbutton) {
if (hr) {
var obj = document.getElementById(divID);
var requestbody = "sbutton=" + encodeURIComponent(sbutton);
hr.open("POST", dataSource, true);
hr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
obj.innerHTML = hr.responseText;
} // end if
}; // end anonymous call-back function
hr.send(requestbody);
}
}
However, on click, the console is logging "Uncaught SyntaxError: Invalid or unexpected token - admin.html:1
ANY help or guidance would be appreciated!
Thanks.
I try to make when you select the city, show the district of this city. I am adding my code to below. I made it on local and it has not any issue but whenever I add this on online it's show noting. It consists of 3 parts; First part is input area, second part is Javascript area and last part for connect to database and get date.
here's input area:
<form action="#institutions" method="post">
<p>Select City*</p>
<select class="institutionsSelect" name="cityinstitutions" id="orders-institutions" onchange="getDetaiinstitutions(this.value);">
</select>
<p>Select District </p>
<select class="institutionsSelect" name="districtinstitutions" id="order-details-institutions">
</select> <br>
<input type="submit" name="institutionsList" autocomplete="off" value="LİST OF INSTITUTIONS" class="btn btn-md btn-blue black-hover" >
</form>
Here's javascript area;
<script type="text/javascript">
function getOrdersinstitutions() {
var ajax = new XMLHttpRequest();
ajax.open("GET", "get-orders-institutions.php", true);
ajax.send();
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var html = "<option>Select City</option>";
for (var a = 0; a < response.length; a++) {
html += "<option value='" + response[a].cityId + "'>";
html += response[a].cityName;
html += "</option>";
}
document.getElementById("orders-institutions").innerHTML = html;
}
};
}
function getDetailinstitutions(cityId) {
var ajax = new XMLHttpRequest();
ajax.open("GET", "get-order-detail-institutions.php?cityId=" + cityId, true);
ajax.send();
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var html = "<option></option>";
for (var a = 0; a < response.length; a++) {
html += "<option value='" + response[a].districtId + "'>";
html += response[a].districtName;
html += "</option>";
}
document.getElementById("order-details-institutions").innerHTML = html;
}
};
}
getOrdersinstitutions();
And here's is datebase connection areas. There are 2 different page one call get-orders-institutions.php and other is get-order-detail-institutions.php
**get-orders-institutions.php **
<?php
$connection = mysqli_connect("localhost", "userName", "password", "ys_table");
$sql = "SELECT * FROM ys_city";
$result = mysqli_query($connection, $sql);
$data = array();
while ($row = mysqli_fetch_object($result))
array_push($data, $row);
echo json_encode($data);
?>
and get-order-detail-institutions.php
<?php
$cityId = $_GET["cityId"];
$connection = mysqli_connect("localhost", "userName", "password", "ys_table");
$sql = "SELECT * FROM ys_district WHERE cityId='$cityId'";
$result = mysqli_query($connection, $sql);
$data = array();
while ($row = mysqli_fetch_object($result))
array_push($data, $row);
echo json_encode($data);
?>
Here all i used codes.
As the first option, select city should be written, but it is an empty input line. Whenever i change datebase setting i mean when i write wrong username and password Select City appear.
By the way these codes work fine in local with exactly the same codes with the same database.
Here is online page
online input area
here is local
Local input area
Local input result
What i suppose to do for take same result in online like local?
thanks in advance
UPDATE: I find what's the problem but i dont know how can i fix it.
If more than 16 rows of data are loaded into the ys_city table, it gives an error like this
How can i fix it?
I need to insert a value got from a document.getElementById into a sql query.
I need to do this because i'm trying to autofill a second input box depending on the result of the first (i.e. if i type Rome in the first one i would like the second one to autofill with the related country found in my db, like Italy)
Here is the code:
<?php
echo (" <form NAME='Form1' id='Form1' method=post class=statsform action=page.php > " );
echo (" <input type=text name=city id=city size=50 class=formfield value='$city' onBlur='Assigncode();' > " );
echo (" <input type=text name='Country' id='Country' size=12 value='$Country' > " );
?>
<script>
function Assigncode() {
var elemento = document.getElementById("city");
var elementoCod = document.getElementById("Country");
if (elemento != null && elemento.value != '') {
var city = elemento.value;
if (elementoCod == null || elementoCod.value == '') {
<?php
$query2 = "SELECT * FROM table WHERE city = 'put here the getElementById of the city' ";
$result2 = MYSQL_QUERY($query2);
$i2 = 0;
$country = mysql_result($result2,0,"T_Country");
?>
eval( "document.Form1. Country").value = '<?php echo($country)?>';
}
}
}
</script>
Any suggestion?
Thanks
Here is a slightly modified version of an AJAX example script found on Wikipedia. It should give you the basic idea on how to proceed. If you use jQuery then a lot of this JavaScript could be reduced to just a few lines.
// This is the client-side javascript script. You will need a second PHP script
// which just returns the value you want.
// Initialize the Http request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php?city=' + elemento.value);
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
document.Form1.Country.value = xhr.responseText; // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
send-ajax-data.php:
<?php
$city = $_GET['city'];
$query2 = "SELECT * FROM table WHERE city = '$city'";
$result2 = MYSQL_QUERY($query2);
$country = mysql_result($result2,0,"T_Country");
echo $country;
By the way, the $city variable should be validated and escaped prior to using it in an SQL query.
Page1 has an input form. I validate the input field with a JavaScript:
<input type="text" name="frmBrand" size="50" onkeyup="BrandCheck();" maxlength="100" id="frmBrand" />
<span id="frmBrand_Status">Enter existing or new brand</span>
In the JavaScript I then call a PHP script:
function BrandCheck()
{
var jsBrandName = document.forms["AddPolish"]["frmBrand"].value;
if (jsBrandName !==null || jsBrandName !== "")
{
document.getElementById("frmBrand_Status").textContent = jsBrandName
// alert(jsBrandName);
var xmlhttp = new XMLHttpRequest();
var url = "CheckBrand.php";
var vars = "jsBrandName="+jsBrandName;
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var return_data = xmlhttp.responseText;
document.getElementById("frmBrand_Status").innerHTML = return_data;
}
}
xmlhttp.send(vars);
document.getElementById("frmBrand_Status").innerHTML = "processing.....";
}
}
So far so good. I do get results from the CheckBrand.php because it changes the frmBrand_Status. But I can't get any database results from the PHP page.
<?php
if(mysqli_connect_errno()) { //if connection database fails
echo("Connection not established ");
}
//by now we have connection to the database
else
{
if(isset($_POST['jsBrandName']))
{ //if we get the name succesfully
$jsBrandName = $_POST['jsBrandName'];
$dbBrandName = mysql_real_escape_string($jsBrandName);
if (!empty($dbBrandName))
{
$dbBrandName = $dbBrandName . "%";
$sqlQuery = "SELECT `BrandName` FROM `Brand` WHERE `BrandName` like '$dbBrandName' ORDER BY `BrandName`";
$result = mysqli_query($con, $sqlQuery);
$NumRows = mysqli_num_rows($result);
// $BrandName_result = mysql_fetch_row($BrandName_query);
echo "Result " . $dbBrandName . " ----- ". $jsBrandName . "Number rows " .$NumRows. " BrandName = " .$result. " SQL " .$sqlQuery;
if( $BrandName_result = mysql_fetch_row($BrandName_query))
{
While ($BrandName_result = mysql_fetch_row($BrandName_query))
{
echo "Brand = " .$BrandName_result[0];
}
}
}
else
{
echo "dbBrandName = empty" . $dbBrandName;
}
}
}
?>
When doing this, the html page shows the constant change of the normal variables. For example when the input field holds "Clu" I get the following output the span ID frmBrand_Status:
Result Clu% ----- CluNumber rows BrandName = SQL SELECT `BrandName` FROM `Brand` WHERE `BrandName` like 'Clu%' ORDER BY `BrandName`
Which looks good as the brandname gets the % appended, but the Number of rows is not shown (empty field?), the SQL Query is shown and looks good, but I don't get any results.
And the if( $BrandName_result = mysql_fetch_row($BrandName_query)) section will not be reached, so there definitely is something going wrong in calling the query.
When I run that same query through PHPMyAdmin, i do get the result I expect, which is 1 row with a brandname.
I'm using firebug to try and troubleshoot the SQL Query, but I can't find where I can check this and I probably can't since PHP is serverside. correct? But how should I then trouble shoot this?
Found what was wrong.
The $con string I was using to open the database was no longer available. On other pages in the site, the $con is available, I load the database using an include script on my index page. But it seems that the variable gets lost when it is called through the XMLHttpRequest(). Which is logical now I think of it, since this can also be a call to a remote server. So my CheckBrand.php page was just missing the $con var to connect to the database.
For my bookshop, I started to built a cashdesk script. This is a very simple form, with an ajax dynamic search. This is a script for a local PC, so the script will not be publish on the web.
When I scan the EAN code, I've my form fill with title, author, editor and price. The book is ready to add in the basket.
Now I'm trying to introduce Json in this script : but I don't understand how to get the values of the mysql query in the script, and put them in the correct fields of my cashdesk form.
I've tested the Mysql query and the Json.
The query
<?php
header('Content-Type: text/html; charset=ISO-8859-1');
include('connexion.php');
$connect_db = connect();
$i = 0;
$tmp = array();
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$tmp[$i] = $row;
}
echo json_encode($tmp);
close();
?>
A json exemple :
[{"product_id":"7097","product_name":"Paix pour tous - Livre audio","product_author":"Wayne W. Dyer","product_editor":"Ada","product_price":"20.28"}]
The ajax script
var xhr = null;
function getXhr()
{
if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
else if(window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else
{
alert("Not Working");
xhr = false;
}
}
function ajaxEAN()
{
getXhr();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var data = '{"product_id": "product_id", "product_name":"product_name", "product_author":"product_author", "product_editor":"product_editor", "product_price":"product_price"}';
oData = JSON.parse( data);
for( var i in oData){
document.getElementById( i).value = oData[i];
}
}
}
xhr.open("POST",'ajaxrecupaddr.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
EAN = document.getElementById("EAN").value;
xhr.send("EAN="+EAN);
}
Thanks for any help !
As far as understand, you simply can't take a JSON from response. If so, than you simply should do:
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200) {
oData = JSON.parse(xhr.responseText);
for(var i = 0; i < oData.length; i++) {
for( var key in oData[i]){
document.getElementById(key).value = oData[i][key];
}
}
}
There, xhr.responseText will return a string with JSON received from server.
Also, few notes:
Instead of
header('Content-Type: text/html; charset=ISO-8859-1');
you should better use:
header('Content-Type: application/json;');
Also, in line below you are opened to SQL Injections:
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
instead of simply doing WHERE product_EAN = '$_POST[EAN]' you should do, at least, WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "':
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "'");
See more about mysql_real_escape_string. It will correctly escape all potentially dangerous symbols and will save you from errors when you have ' symbol in EAN. Also, read warning shown on a page linked above. You should better change your database extension as MySQL extension is deprecated.