AJAX and PHP; not passing the variables or not working? - 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

Related

Ampersand being sent as &amp; rather than & when attempting to update MySQL database

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)+"&currenttitle="+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('&amp;', '&', htmlentities($value));
or (better imo)
$value = htmlentities(html_entity_decode($value));

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"){

Will this huge javascript array loaded from a database crash my website?

So on this website I'm making (who knows if i'll actually finish it lol) when someone opens up the new user page, php echos into a javascript script all the usernames from the database to create an array.
<script type="text/javascript">
var allUsers = ['!' <?php
$result = mysql_query("SELECT username FROM users ") or die("error " .mysql_error());
$usersArray = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$usersArray[] = $row['username'] or die("error ". mysql_error());
}
foreach ($usersArray as $name) {
echo ',' . json_encode($name );
}
?> , ];
the point of this is to have a live checker so if you type in a username that already exists, red text shows up next to the username input. But let's say I get 1,000,000 users (completely theoretical). Fortunately, the array only gets created at the beginning of the web page load. But will the function that checks if the username already exists in the huge array and gets called everytime someone changes the text in the username input put too much stress on the script and crash the website? If so, is there a better way to do what I'm describing?
Here's the rest of the code
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
function onUserChange() { //gets called onkeypress, onpaste, and oninput
if(contains(allUsers, str)) {
div.innerHTML = "Username already exists";
div.style.color = "red";
userValid = false;
}
}
</script>
Something along these lines. ( with jQuery and PDO ) - note - code is not tested.
var keyTimer, request;
$('namefield').blur(function(){
onUserChange();
});
$('namefield').keyup(function(){
onUserChange();
});
function onUserChange() { //gets called onkeypress, onblur
keyTimer = setTimeout(function(){
if(request && request.readystate != 4){
//cancel a previous request if a new request is made.
request.abort();
}
request = $.post(
'http://yoursite.com/location/of/username/script.php', //post data to server
{username : $('namefield').val()},
function(data){
if(data == 0 ) { //might be a string here
alert( 'the name is ok to use.' );
}else{
alert( 'someone has this name already.' );
}
}
);
}, 500); //overwrite previous timeout if user hits key within 500 milliseconds
}
Then in the backend
$sql = 'SELECT id FROM users WHERE username = :username';
//insert from post username but we are good programers and are using PDO to prevent sql injection.
//search for the username in the db, count the number of users or rows should be 1 someone has it 0 no one has it assuming its unique.
$stmt = $Pdo->prepare($sql);
$stmt->execute(array(':username', $_POST['username']));
echo $stmt->rowCount();
exit();
etc.....
Do not do it. My counsel is to use ajax to load the php file that will make a query asking only for the user that was typed in the input and retunr only a boolean value(exists=true / notexists=false)
Code example:
HTML(yourFile.html):
<script>
jQuery(document).ready(function(){
//When the value inside the input changes fire this ajax querying the php file:
jQuery("#inputUser").change(function(){
var input = jQuery(this);
jQuery.ajax({
type:"post",
url:"path/to/file.php",
data:input.val(),
success: function(data){
//if php returns true, adds a red error message
if(data == "1"){
input.after('<small style="color:#ff0000;">This username already exists</small>');
//if php returns false, adds a green success message
} else if(data == "0"){
input.after('<small style="color:#00ff00;">You can use this username</small>');
}
}
});
});
});
</script>
<input id="inputUser" type="text" name="username" value="">
PHP(path/to/file.php):
<?php
$username = $_REQUEST['username']; // The value from the input
$res = mysqli_query("SELECT id FROM users WHERE username='".$username."'"); // asking only for the username inserted
$resArr = mysqli_fetch_array($res);
//verify if the result array from mysql query is empty.(if yes, returns false, else, returns true)
if(empty($resArr)){
echo false;
} else{
echo true;
}
?>
As I can see you need to load the PHP code when your website is loading.
First, I recommend you to separate the code. The fact that you can mix Javascript with PHP doesn't mean it is the best practice.
Second, yes, it's not efficient your code since you make Javascript load the result so you can search into it next. What I suggest you is making the search in the server side, not in client side, because as you say, if you have 100 elements maybe the best is to load all the content and execute the function, but if you have 1,000,000 elements maybe the best is to leave the server to compute so it can make the query with SQL.
Third, you can do all this using Ajax, using Javascript or using a framework like jQuery so you don't have to worry about the implementation of Ajax, but you only worry about your main tasks.

Debugging MySQL query in PHP when called from other page

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.

xmlHttp2 function (var params coding needed!)

In this page where this code is,there is a form of 3 details
country,gender,topic
So the idea is to send these 3 details to startChat.php and so that the php can extract the 3 details.
The code is as below
function startChat()
{
xmlHttp2 = GetXmlHttpObject();
if (xmlHttp2 == null)
{
alert("Browser does not support HTTP Request");
return;
}
var url = "startChat.php";
var params = "country,gender,topic";<<<<<<<<<<<<<<<<<<<<<<<what coding this should be?????
xmlHttp2.open("GET", url, true);
xmlHttp2.send(params);<<<<<<<<is this correct?????
xmlHttp2.onreadystatechange = stateChanged2;
}
And also i would need help with the startChat.php part
<?php
include('config.inc.php');
$preference="$_GET[params]";<<<<<<<<<<<<<<<<<<<<<<<<<<<<what coding this should be????????????????????????????????????
include('database.inc.php');
mysql_query("INSERT INTO users (inchat,preference) values('N','$preference')");
echo mysql_insert_id();
mysql_close($con);
?>
Please help,asking sincerely :(
First off, you ought to use a POST request instead of a GET, because it's clear from your code that this request is supposed to change state on the server.
Your params variable should be form encoded. You can do this with encodeURIComponent, like so:
var params = 'country=' + encodeURIComponent(userCountry) +
'&gender=' + encodeURIComponent(userGender) +
'&topic=' + encodeURIComponent(userTopic);
Second, you ought to sanitize the data before you insert it into your DB. Otherwise you expose yourself to SQL injection attacks.
<
?php
include('config.inc.php');
// need to create db connection before mysql_real_escape_string is called
include('database.inc.php');
$country = mysql_real_escape_string($_POST['country'], $con);
$gender = mysql_real_escape_string($_POST['gender'], $con);
$topic = mysql_real_escape_string($_POST['topic'], $con);
mysql_query("
INSERT INTO users(inchat, country, gender, topic)
VALUES('N','$country', '$gender', '$topic')
");
echo mysql_insert_id();
mysql_close($con);
?>
Note that I've also changed your DB structure. In general, it's best to avoid putting more than one piece of data into a single field (DB normalization).

Categories