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"){
Related
I am currently building an "admin" section where the information shown on the main site can be added to, updated and deleted using this one page.
All of my scripts function as intended, information is added to the database, rows are updated and deleted with no errors in 99.9% of cases.
The database is set up with 3 columns TITLE, DESCRIPTION and Image and when updating any of the rows I use the value in TITLE as my reference for WHERE statements.
However, any title containing an '&' symbol are downloaded fine and insert into my HTML as intended, however when being sent to my update script they are sent as &. This then doesn't register correctly with the update script and then it fails to update. I know '&' is converted to '&' when escaped but cannot understand why there is a second 'amp;' being sent?
Can anyone shed some light on this / point me to appropriate documentation to solve this issue?
Javscript Function(dbtable and titler are variables that decide the table to insert into )
function updating(indexno) {
var current = document.getElementById('title'+indexno).innerHTML;
var newtitle = document.getElementById('titlelink'+indexno).value;
var newdesc = document.getElementById('desclink'+indexno).value;
var newimage = document.getElementById('imagelink'+indexno).value;
if(newtitle == ""){
newtitle = document.getElementById('title'+indexno).innerHTML;
};
if(newdesc == ""){
newdesc = document.getElementById('description'+indexno).innerHTML;
};
if(newimage == ""){
newimage = document.getElementById('image'+indexno).innerHTML;
}
var request = "updatingdb.php?newtitle="+escape(newtitle)+"&newdesc="+escape(newdesc)+"&newimage="+escape(newimage)+"¤ttitle="+escape(current)+"&thetable="+escape(dbtable);
var xhr = new XMLHttpRequest();
xhr.open("GET", request);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send(null);
thetester(dbtable,titler);
}
PHP Script
$thetable = htmlentities($_GET['thetable']);
$currenttitle = htmlentities($_GET['currenttitle']);
$newtitle = htmlentities($_GET['newtitle']);
$newdesc = htmlentities($_GET['newdesc']);
$newimage = htmlentities($_GET['newimage']);
$db = mysqli_connect($servername, $user, $password);
if (!$db)
{
echo"NO CONNECTION AVAILABLE";
exit();
}
mysqli_select_db ($db, "testing");
$query ="UPDATE `$thetable` SET `TITLE`= '$newtitle', `DESCRIPTION` ='$newdesc', `IMAGE` = '$newimage' WHERE `TITLE` = '$currenttitle'";
echo$query;
$results = mysqli_query($db, $query);
if(!$results)
{
echo"not working";
exit();
}
echo"updated";
This happens because you use htmlentities(), which will just see the & character and therefore makes an entity out of it. You could either remove htmlentities from the desired input field or do something like this:
$value = str_replace('&', '&', htmlentities($value));
or (better imo)
$value = htmlentities(html_entity_decode($value));
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);
I am trying to check the result from a function and determine where on my page it should go by using the Session Variable "alernativeRD". It goes to the correct element on the first try, but after that it keeps going only to the first element regardless of whether its right or not. After some testing I've found that "alernativeRD" does get changed every time in the PHP function, but it doesn't change in the Javascript part.
PHP PART
function firstSignInDefault(){
global $con;
$clubUsername= $_SESSION['clubUsername'];
$_SESSION['alternativeRD']='false'; //sets it back to false to avoid having alternativeRD be true for next user
$lastName= mysqli_real_escape_string($con, $_POST['lastNameF']);
$firstName= mysqli_real_escape_string($con, $_POST['firstNameF']);
$memberID= mysqli_real_escape_string($con, $_POST['idNumberF']);
if(!(is_numeric($memberID))){
die("<h3> Student ID must be a number </h3>");
}
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
if(mysqli_num_rows($getMemberRow)==0){
$sql="INSERT INTO memberstable (MemberMadeID,FirstName,LastName,Club)
VALUES ('$memberID','$firstName','$lastName', '$clubUsername')";
$test=false; //checks to make sure sql statement runs fine
if(mysqli_query($con,$sql))
$test=true;
else {
echo "<h3> Error running sql </h3>";
}
$date=date("Y-m-d h:i:sa");
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
$memberRowArray=mysqli_fetch_array($getMemberRow);
$memberPanID=$memberRowArray['UniquePanDBID'];
$sql2="INSERT INTO signinstable (TimeOfSignIn, UniquePanDBID, ClubUsername, FirstName, LastName) VALUES ('$date','$memberPanID','$clubUsername', '$firstName', '$lastName')";
//THE FOCUS OF THIS QUESTION IS BELOW THIS COMMENT
if(mysqli_query($con, $sql2) && $test==true){
$_SESSION['alternativeRD']='true';
echo " <h2 id='signedInPeople' >".$date. " ".$firstName ." ". $lastName ."</h2>";
}
}
else {
echo "<h3> ID Number already in use</h3>";
}
}
JAVASCRIPT/AJAX PART
function processFSIF(){
var xmlHttp= makeXMLHTTP();
// Create some variables we need to send to our PHP file
var url = "signInDataPlace.php";
var idNumberF = document.getElementById("idNumberF").value;
var lastNameF = document.getElementById("lastNameF").value;
var firstNameF = document.getElementById("firstNameF").value;
var typeSignIn="first";
var vars = "idNumberF="+idNumberF +"&lastNameF="+lastNameF +"&firstNameF="+firstNameF +"&typeSignIn=" +typeSignIn;
xmlHttp.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var return_data = xmlHttp.responseText;
//AREA OF PROBLEM BELOW
<?php
if($_SESSION['alternativeRD']=='true'){ ///YOU ARE HERE, alternativeRD is acting stupid
?>
document.getElementById("serverInputList").innerHTML = return_data;
<?php
}else{
?>
document.getElementById("serverInputFSIF").innerHTML = return_data;
<?php
}
?>
}
}
// Send the data to PHP now... and wait for response to update the status div
xmlHttp.send(vars); // Actually executes the request
document.getElementById("serverInputFSIF").innerHTML = "processing...";
}
Your Javascript was printed only once, before you use AJAX. You can return the session value together with response, or you can set the cookie in PHP, than use it in javascript.
I'm making an administrative interface for a semester project app.
Our last duty is to make an admin page. I've set up everything an admin should have access to (updating user info, deleting a user, resetting stats, etc etc) except for the most important one: Creating a new user.
When I input the data to create the user, nothing new shows up in the data base. Tried it with a standard query (no variables, you'll see below) and still nothing went through leading me to believe that it is not accessing the variables at all.
My Javascript AJAX:
function createNewUser()
{
if (confirm("Are you sure you wish to create this user?") == true)
{
createNewUserAJAX();
}
}
function createNewUserAJAX()
{
var fName = document.getElementById('ADDFirstName').value;
var lName = document.getElementById('ADDLastName').value;
var user = document.getElementById('ADDUserName').value;
var password = document.getElementById('ADDPassword').value;
var password2 = document.getElementById('ADDPassword2').value;
var slateID = document.getElementById('ADDSlate').value;
var keeperID = document.getElementById('ADDKeeper').value;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(user+" created successfully!");
toggleCreateUserInterface();
}
}
if (password == password2)
{
xmlhttp.open("GET","AddUserAJAX.php?uname="+user+"&pwd="+password+"&slate="+slateID+"&keeper="+keeperID+"&fName="+fName+"&lName="+lName, true);
xmlhttp.send();
}
else
{
alert("Passwords must match");
}
}
The code on my ADDUserAJAX.php page:
<?php
$userName = mysql_real_escape_string($_GET['uname']);
$pw = mysql_real_escape_string($_GET['pwd']);
$slateID = mysql__real_escape_string($_GET['slate']);
$keeperID = mysql_real_escape_string($_GET['keeper']);
$fName = mysql_real_escape_string($_GET['fName']);
$lName = mysql_real_escape_string($_GET['lName']);
mysql_connect('127.0.0.1', 'root', '');
#mysql_select_db('slatekeeperdatabase') or die("Unable to select database");
$lastUserQuery = mysql_query("select max(userID) from users;");
$lastUserID = mysql_result($lastUserQuery,0);
$newUserID = $lastUserID+1;
$lastStatsQuery = mysql_query("select max(statsID) from stats;");
$lastStatsID = mysql_result($lastStatsQuery,0);
$newStatsID = $lastStatsID+1;
//$query= "INSERT INTO users VALUES (".$newUserID.", ".$fName.", ".$lName.", ".$pw.", ".$userName.", '', 1, 1000, 100, ".$slateID.", ".$keeperID.", ".$newStatsID.", 0)";
$query2 = "insert into users values (9, 'James','Lom', 'red','jlom4', '', 1, 1000, 100, 1, 1, 1, 0 );";
mysql_query($query2);
mysql_close();
?>
$query variable is what I'm trying attempting to get through. $query2 was just test query to check if it was even passing at all (which it is not)
Any help is much appreciated. It's so strange because I got it working previously with the test data (never got it working with what I'm actually attempting to get through). Perhaps I put incorrect syntax somewhere that I cannot locate... (oh, POST will be used after everything gets working. Security isn't our primary concern at this point.)
I think you use mysql_real_escape_string before making mysql connection. If there's no connection, mysql_real_escape_string won't do anything.
you are not giving Query fields to insert
$query2 = "insert into users (id, Name etc) values (9, 'James','Lom', 'red','jlom4', '', 1, 1000, 100, 1, 1, 1, 0 );";
i noticed "". in your $query2 remove this i think i can also be a error and second remove ; in the kind of )
To debugg echo your $query2 see what is missing and also try to run your query directly in database SQL
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.