PHP Ajax onkeyup doesn't work on my Switch case website - javascript

I have a website where I use php case and include as website.
So depending on the ?page="" result I get it includes a new website.
Example: www.test.come/?page=test.
The example I use to test the PHP and Ajax onkeyup function is this one:
Test.php
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
gethint.php
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Fiona";
$a[] = "Gunda";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
So if my www.test.com/?page=test it will include the Test.php on my website.
Everything on Test.php is uploaded on the website and looks great but when I type in the letter a for example in the box then the name Anna is supposed to pop up but it doesn't.
but if I type the page www.test.com/include/Test.php where the Test.php file exist it works perfectly.
Here is the code that I use to switch between different pages:
<?php
if(isset($_GET["page"])){
$page = $_GET["page"];
} else {
$page = "News";
}
I think this could be the biggest reason why this doesn't work, but then I need an explanation for why and if there is something I can do to make it work.
I can give you a full example on all my code, but that will become a WALL of TEXT, so I thought saving you all time but shorting it up. If you need the full code to figure the issue out then I will help you with it.
Thank you very much for taking time to read this and trying to solve it.
Best regards
Simon

You need to change the AJAX call to use an absolute path for gethint.php. Otherwise it will look for it in the same folder as the page that's making the AJAX call.
xmlhttp.open("GET", "/include/gethint.php?q=" + str, true);

Related

How to build a Username Validator

I want to make a ambassador ID validator (LIKE USERNAME VALIDATOR) using php and xmlHttp request in javascript.
I wanted to send a xmlHttp request to a php file and that php file should return a integer value like "1" or "0". By reading that with javascript, it should change the message and disable or enable the submit button. So I've written the below code, but the javascript is not functional. the php seems to work perfectly, but having a line-break before the integer. is the line brake is responsible to Ineffectiveness of the javascript?
Here is the javascript,
<script>
function checkambassadorid(str){
if (str=="") {
document.getElementById("availability").innerHTML="";
return;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if(parseInt(this.responseText) === "0"){
document.getElementById("availability").innerHTML='<span class="text-success">Username Available</span>';
document.getElementById("submitter").disabled = false;
} else {
document.getElementById("availability").innerHTML='<span class="text-success">Username Not Available</span>';
document.getElementById("submitter").disabled = true;
}
xmlhttp.open("GET","ajax.php?data=checkambassadorid&ambassadorid="+str,true);
xmlhttp.send();
}
}
</script>
Here is the HTML,
Ambassador ID:
<input type="number" onkeyup="checkambassadorid(this.value)" id="ambassadorid" name="ambassadorid"> <span id="availability"></span>
And the PHP,
if($_GET['data'] == 'checkambassadorid'){
mysqli_set_charset($con,"utf8");
if(isset($_GET["ambassadorid"])){
$ambassadorid = mysqli_real_escape_string($con, $_GET["ambassadorid"]);
$query = "SELECT * FROM ambassadordb WHERE ambassadorID = '".$ambassadorid."'";
$result = mysqli_query($con, $query);
echo intval(mysqli_num_rows($result));
}
}
I think #dave nailed your issue on the head, but I'd like to propose a different approach.
Instead of responding with a binary value you could instead return a JSON payload indicating that the username is available (as well as any other pertinent data like suggested names if the requested one is taken)
if($_GET['data'] == 'checkambassadorid'){
mysqli_set_charset($con,"utf8");
if(isset($_GET["ambassadorid"])){
$ambassadorid = mysqli_real_escape_string($con, $_GET["ambassadorid"]);
$query = "SELECT * FROM ambassadordb WHERE ambassadorID = '".$ambassadorid."'";
$result = mysqli_query($con, $query);
$usernameIsAvailable = !(bool)intval(mysqli_num_rows($result));
$obj = new class{};
$obj->username = '$_GET["ambassadorid"]';
$obj->isAvailable = $usernameIsAvailable;
if(!$usernameIsAvailable) {
$obj->suggestions = ['generated', 'list', 'of', 'suggested', 'names'];
}
print json_encode($obj);
}
}
Then in your JS
const o = JSON.parse(this.responseText);
if(o.isAvailable) {
document.getElementById("availability").innerHTML='<span class="text-success">Username Available</span>';
} else {
document.getElementById("availability").innerHTML='<span class="text-success">Username Not Available</span>';
}
document.getElementById("submitter").disabled = !o.isAvailable;
You could even include a message with the response to eliminate the if(o.isAvailable) altogether.
I think the main issue, is that you have:
parseInt(this.responseText) === "0"
an integer 0 will never be equal to the string "0", and since you used ===, it is checking type as well as value. I would do:
if(this.responseText.trim() === "0"){

Cannot get data passed to a php file using AJAX

I am trying to pass data back to the server and then use the reply to update the browser page.
My code for a SELECT input is as follows;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
The script code is as follows;
<script>
function findTeleNo(that){
alert("I am an alert box!" + that);
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("TeleNo").value = this.responseText;
}
}
};
xhttp.open("GET", "findTeleNo.php?q=" + that, true);
xhttp.send();
</script>
The purpose of the script is to take the value selected in the dropdown (variable "that") and submit it to the php file as variable q.
And the PHP file is as follows;
<?php
$MatchCaptain = $_REQUEST["q"];
$teleNo = "";
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$teleNo = $db_field['TeleNo'];
break;
}
}
}
echo $teleNo;
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
$ufullName = $first_name." ".$last_name;
return $ufullName;
}
?>
The php file requests the q variable from the url and makes it $MatchCaptain.
This will be a name like Joe Bloggs. The next piece of code connects to a MySQL table to extract players first names surnames and telephone numbers. The first names and surnames are concatenated to form the fullname which is compared with the $MatchCaptainWhen a match is made the variable $teleNo is set to the Telephone Number of that player. The echo statement rerurns the value to the script.
The field id I am trying to update is;
<p><b>Telephone Number: </b> <span id="TeleNo"> <?php echo $_SESSION["TeleNo"]; ?></span></p>
The alert in the script function findTeleNo shows me that I have entered the function but nothing happens after that.
Any help as to how I get this working would be grateful.
I have changed my script to
<script>
function findTeleNo(that){
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "findTeleNo.php?q=" + encodeURIComponent(that), true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
// OK
alert('response:'+xhttp.responseText);
document.getElementById("TeleNo").innerHTML = this.responseText;
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
};
</script>
The response shown by alert('response:'+xhttp.responseText); is correct and the line of code
document.getElementById("TeleNo").innerHTML = this.responseText;
does print the response to the web page.

Live Search Using Ajax and PHP mysql

I created a Live Search using AJAX,PHP and mysql.here when I click on search result ,redirecting me to a particular page it works perfectly. Now I need a small change.
All I need is:
When I click on the search result, that particular result should be display in the input field.
Here is my AJAX code:
<script type="text/javascript">
END OF AJAX CODE
PHP CODE
<?php
ob_start();
session_start();
include("Base.php");
$dbase=new Base();
#$userID=$_SESSION['userID'];
$createdDate=date("Y-m-d");
$createdTime=date("h:i:s A");
$partialStates=mysql_escape_string($_REQUEST['q']);
$qryy="SELECT * from `gon_pro` WHERE `pro_name` LIKE
'%$partialStates%' ";
$pser=$dbase->execute($qryy);
$ser_nums=mysqli_num_rows($pser);
while($co[]=mysqli_fetch_array($pser)){
}
?>
<?php
foreach ($co as $key => $namo) {
$cv=$namo['pro_name'];
$cv_id=$namo['id'];
$cv_p=$namo['price'];
?>
<a href="pro_det.php?prolod=<?php echo $cv_id; ?>"><p class="res
col-md-6"><?php echo $cv; ?></p></a>
<?php
}
?>
END OF PHP CODE
function getStates(str) {
if (str.length == 0) {
document.getElementById("row").innerHTML = "";
document.getElementById("results").innerHTML =""
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML =
xmlhttp.responseText;
}
};
xmlhttp.open("GET", "support/getStates.php?q=" + str, true);
xmlhttp.send();
}
}
</script>

PHP Ajax error, get 404 when type first char

I see an error in my console it says: showHint() is not defined, while I defined it already, also this live search doesn't return anything when I type it. It assume should work like this.
gethint.php file:
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
//Further names removed for Post
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
index.php
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","/gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
Your error is coming from the __DIR__ which is not defined in your showHint function. Remove this or update it to the correct path in which you're storing your autocomplete dictionary and you should be good.
To echo __DIR__ as the path to your gethint.php file, do the following:
xmlhttp.open("GET","<?php echo __DIR__; ?>/gethint.php?q=" + str, true);
However, i'm going to assume that you're not wanting to do __DIR__ as your path. Ultimately it's up to you to figure out how to set the path to your gethint.php file. We do not know the directory structure of your application or how where you have files stored.

AJAX chat system not working

I can't seem to work this one out. Been a few days and still no progress after re-writing it more times than I can count on my hands.
Here is the Javascript (On same page as html)
Summary: User types text into the input box. That gets sent off to be processed, which then gets sent back and displayed on the screen in the box ID'd as DisplayText on the html page.
<script type="text/javascript">
function SendText() {
if (document.getElementById("Text").innerHTML == "") {
return;
} else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("DisplayText").innerHTML = xmlhttp.responseText;
}
}
Text = document.getElementById("Text").value;
xmlhttp.open("GET", "php/Test.php?Chat=" + Text, true);
xmlhttp.send();
}
}
</script>
Here is the HTML (Same page as the script)
<div>
<p>
<span id="DisplayText">
TEXT GOES HERE
</span>
</p>
</div>
<form action="" onsubmit="SendText();">
<input type="" name="" id="Text" />
<input type="submit" value="Send" name="Send" />
</form>
The PHP code is here
<?php
session_start();
include ("Connect.php");
$Connection = mysqli_connect("localhost", "root", "", "chatsystem");
$Create = "CREATE TABLE " . $_SESSION["Username"] . "Chat(Username VARCHAR(255), Chat VARCHAR(255))";
////////////////////////////////////////////////////////////////////////////////
$DatabaseExist = $Connection->query("SELECT 1 FROM " . $_SESSION["Username"] . "Chat");
if ($DatabaseExist !== false) {
echo "Database exists";
doSomething();
} else {
echo "Database does not exist";
mysqli_query($Connection, $Create);
doSomething();
}
////////////////////////////////////////////////////////////////////////////////
function doSomething() {
// Get the sent chat
$Input = $_REQUEST["Chat"];
// Insert into the database the new chat sent
mysqli_query($Connection, "INSERT INTO " . $_SESSION["Username"] . "chat (`Username`, `Chat`) VALUES ('$_SESSION[Username], '$Input')");
// Select everything from the database
$Result = $Connection->query("SELECT * FROM " . $_SESSION["Username"] . "Chat");
// Display everything from the database in an orderly fashion
// --
// For the length of the database
// Append to a variable the next table row
// --
while ($Row = $Result->fetch_array()) {
// Make Variable accessable
global $Input;
// Append username to the return value
$Input = $Input . $Row["Username"] . " : ";
// Append chat to the return value
$Input = $Input . $Row["Chat"] . "<br />";
}
}
// Will return the value
echo $Input;
?>
My connection to the Database is fine. I'm using it on other pages that work.
So lets assume that's not the problem. :P
Any help or insight from anyone who knows or can think of something that is wrong, I would be very grateful for.
I'm new to AJAX.
You do a wrong test with
if (document.getElementById("Text").innerHTML == "")
It should be the same way you use to get the text for sending in the AJAX
if (document.getElementById("Text").value == "")
So check its value property and not its innerHTML as input elements do not have html content..
Be careful though because your code is wide-open to SQL injection attacks.
1st : use input's value property instead innerHTML
eg. use
if (document.getElementById("Text").value == "")
instead of
if (document.getElementById("Text").innerHTML == "")
2nd : use return false; at the form's onsubmit event; to prevent current page to be refreshed as you are using ajax. Otherwise the page will get refreshed and it wont display the php page's output,
eg. use
onsubmit="SendText(); return false;"
instead of just
onsubmit="SendText();"
Try AJAX Long Polling technique for chat application. Here is example
http://portal.bluejack.binus.ac.id/tutorials/webchatapplicationusinglong-pollingtechnologywithphpandajax

Categories