Lag issues cause of AJAX/PHP - javascript

So i am trying to make an asynchronous call of a PHP script but for some reason there is an error: Maximum call stack size exceeded that is making my site lagging a LOT. There must be a loop somewhere in my code but i can't really find it. I am looking for the past 3 days and still nothing. If someone could spot anything i would be really greatfull. Thanks in advance!
PHP code:
<?php
require_once 'li.php'; //File with the constants
$Username = $_POST['Username'];
$query = "SELECT Username
FROM user_info
WHERE Username = ?
LIMIT 1";
if($stmt = $conn->prepare($query)){ //Prepares the statement!
$stmt->bind_param('s', $Username);
$stmt->execute(); //Executes it!
if($stmt->fetch()){ //Checks if the query returns anything!
$stmt->close(); //If yes then closes the prepared statement!
$error = "Username taken";
echo $error;
}
}
?>
AJAX/JS code:
$(document).ready(function(){
$('#Username').on("keyup", function(){
$.ajax({
type: 'POST',
url: 'NameValidation.php', //Your required php page
data: { Username: Username }, //pass your required data here
async: true,
}).done(function(response){
if(response != ""){
$('#UsernameLabel').html("Username Taken!");
}
});
});
});
In case you didn't understand what i want to do with this code let me explain some more. I want every time the Username input changes to search if the username already exists in the database and alert the user by changing the Label text.
PS: Dont worry about SQL injection security i'll add that later when i fix this problem! ^-^

you are not closing connection if query returns nothing, try changing the code to :
if($stmt->fetch()){ //Checks if the query returns anything!
$error = "Username taken";
echo $error;
}
$stmt->close(); //close connection in any case

Related

Update MYSQL Table On Div Click using Ajax - No Page Refresh?

I have a MYSQL Table called users.
I also have a column called online_status.
On my page I want a user to be able to toggle their status as 'Online' or 'Offline' and have this updated in the database when they click on the div using Ajax, without refreshing the page.
Here's my PHP/HTML code:
<?php if ($profile['online_status'] == "Online") {
$status = "Offline";
}else{
$status = "Online";
} ?>
<div id="one"><li class="far fa-circle" onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"/></li><? echo 'Show as ' .$status; ?></div>
My Ajax:
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "update_status.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
update_status.php
<?php
$var = #$_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = 1";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//added for testing
echo 'var = '.$var;
?>
I am currently getting no alert, nothing is being updated in my database either. Please can someone help me improve/fix the code to get it to work? Also, if there's a way of eradicating the need for the update_status.php file and have the ajax self post then this would be preferred.
Thank you in advance.
From what i see, the reason why no alert pops up nor nothing gets updated is because of the onclick() on button you have. Add quotes around the parameter to the update function. As you have it, javascript sees the parameter as a javascript variable as $profile['online_status']; is a string.
If you had debugged your code, you should see an error pointing towards the onclick() line
Change this
onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"
To
onClick="UpdateRecord('<? echo $profile['online_status']; ?>');"
Also you are hardcoding the where clause in your update statement. You should be using the $_POST['id'] variable via prepared statements
pass data to PHP file
data: { id: id },
add a database connection to your PHP file
<?php
$var = $_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = '$var'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
?>
If you still see any errors then press F12 and go to network tab, then click on that div, network tab will record your ajax file returns, you can check there on by selecting your php file's response, hope it helps

How to store JavaScript variable in the database

I wanted to store the value "totalscore" from my JavaScript code to my database. I tried using ajax call but something is not working, I have not used ajax before.
In the following JavaScript code, I display the value of score which i have found to the html element.
JavaScript code:
if (matches==8){
var totalscore = calcScore();
document.getElementById("score").innerHTML=totalscore;
}
I want to save the value of totalscore in my users database when the submit button is clicked. So i tried something like :
$("#sendscore").on("click",function(){
gamescore= document.getElementById('score').innerHTML;
$.ajax({
type:'POST',
url: 'score-processor.php',
data:{
gamescore: gamescore,
}
})
});
the php code :
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'registration');
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password_1']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
header('location: profile.php');
}
else {
array_push($errors, "Wrong username/password combination");
}
}
}
if(isset($_POST['gamescore'])){
$fetch = "SELECT id FROM users WHERE username='$username'";
$fetchid =mysqli_query($db, $fetch);
while ($row=mysqli_fetch_array($fetchid)){
$id = $row['id'];
$gamescore= $_POST['gamescore'];
$updatescore= "INSERT INTO users(id, score)VALUES('$id','$gamescore') ON DUPLICATE KEY UPDATE score='$gamescore'";
mysqli_query($db, $updatescore);
}
}
In my html :
<?php session_start();?>
<body>
<p>Your score: <span id=score></p>
<button id="sendscore" class="Go-on">Submit</button>
the database table has columns , id, username, email, password and score.
the value for columns id, username, email and password are collected during login/register.
The game runs smoothly and presents the score but when I click the submit button which on clicked should add the value to the table, but nothing happens, no errors in the log and the value is not added to the table.
Problem 1
gamescore= document.getElementById('score');
This is an HTML element, not the value of it.
You need to read the .innerHTML just like you wrote to it earlier
Problem 2
gamescore: gamescore
jQuery.ajax doesn't have a gamescore option. So this is meaningless.
You need to pass data.
data: {
gamescore: gamescore
}
Problem 3
contentType: false,
This stops jQuery overriding the content-type when you pass a FormData object to generate a multipart request (which is useful for uploading files).
You aren't doing that, so contentType: false will break the normal allocation of the correct Content-Type header.
Remove that
Problem 4
processData: false
You need the data to be processed. The object you pass to data needs encoding into the HTML request.
Remove that.
Problem 5
$updatescore= "UPDATE users SET(username='$username', score='$gamescore') WHERE (id='$id')";
You failed to define $username or $id.

Cannot Redirect when Logging in an Account using javascript and php

Currently, I am developing a website, for my own purposes. I am a beginner at web developing so please understand me if I am not getting this correct. Please Help.
I have a code for javascript when clicking an html element button
for logging in. see code below:
$(document).ready(function(){
$("#login").click(function(){
var username = document.getElementById("username").value;
var pword = document.getElementById("password").value;
validateUser(username,pword);
});
});
function validateUser(user,pass){
var username =user;
var pword =pass;
var datasend = "username="+ username + "&password=" + pword;
$.ajax({
type:'POST',
url:'../bench/php/login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
alert("Hello World"); //Trying to pop up
$('#username').val('');
$('#pword').val('');
}
});
}
I successfully triggered the button for the second time I try to click it, and the hello world message will pop out, but it cannot redirect the page if it was successfully logged in using an account in MySQL in WAMP server. Here is the code in PHP below:
<?php
// require("php/config.php");
include("config.php");
session_start();
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = mysqli_real_escape_string($db,$_POST['username']);
echo $mypassword = mysqli_real_escape_string($db,$_POST['password']);
//$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$sql = "SELECT * FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("Location: index.html");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>';
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");';
echo '}, 100);</script>';
}
}
?>
The problem is, the page does not redirect to the index.html even when the second click triggers the HELLO WORLD alert.
I don't know what I am doing wrong.
I don't why this is not working, I see the console, there is no error exist.
can someone help me with this? any help will much be appreciated. thanks and regards.
If you'd like to keep to using the AJAX setup you have at the moment (which is totally fine), what you'll need to do is to beef up the on-success function to read the returned results from your PHP.
A simple example
Instead of
header("Location: index.html");
write
echo "index.html";
exit;
and then add the following to your on-success function:
window.location.href = msg;
That will start to give you a flavour of how the relationship between an AJAX call and your PHP server should look like.
Next steps
Instead of having your AJAX return a string (index.html) have it
return an array of information, perhaps you want to welcome the user
with a personalised message?
You don't need to create a string (var datasend = "username="+ username + "&password=" + pword;) and feed that to your AJAX call, you can send an array.
Make sure your passwords are not stored in plain text on the server.
An ajax request will not follow the Location header of responses to redirect users.
You need to either redirect the user manually using JS in the success callback or change your form submission to use a classic HTML form
The first thing to make sure, PHP Redirect Header doesn't work when sending an Ajax Request.
So the solution to your problem is:
Change this part of your code in PHP file:
header("Location: index.html");
Into:
echo "Success";
exit();
And then in your Ajax Request Success Callback:
success:function(msg){
if (msg == 'Success') {
window.location = "/path/to/redirect";
}
}
Let me know if you have still confusion in this.

PHP Returning incorrect records from MYSQL database

Have the following code.. I have set up a password reset system for my website and it has suddenly broken. I was changing the form sending data method from standard HTML/PHP to using AJAX .post() method but dont think that has anything to do with the results I am seeing.
Issue: when the $timeSQL query runs it returns 0 num_rows(), yet when I run this in phpmyadmin I get the expected results. I am not using a count(*) in my SQL statement as I saw many of these answers were referencing so am not sure what is the problem..
Each attempt I am always getting this code to fire:
echo "<script>
alert('It has been longer than 1 hour since you last requested to reset your password and your code has expired. Please request to reset it again on the login page by clicking Forgot Password link at the bottom of the login page.');
window.location='login.php';
</script>";
Here is pastebin with same code: http://pastebin.com/S5Yi9MAQ
Thanks for all help
<?php
include('config.php');
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
$token = $_GET["token"];
if (isset($_POST['rpTempCode'])){
//Check to see if more than 10 mins has elapsed since password reset request
$timeSQL = "SELECT codeExpireDate, sysdate(), tempCode FROM users WHERE token = '".$token."' AND codeExpireDate > sysdate()";
$timeResult = mysqli_query($db,$timeSQL);
$count = mysqli_num_rows($timeResult);
echo "<script>alert('count: ".$count."');</script>";
if (mysqli_num_rows($timeResult) > 0){
$timeRow = $timeResult->fetch_assoc();
$tempCodeFromDB = $timeRow["tempCode"];
$newPassword = mysqli_escape_string($db, $_POST["rpNewPassword"]);
$tempCode = mysqli_escape_string($db, $_POST["rpTempCode"]);
if ($tempCode == $tempCodeFromDB){
$sql = "UPDATE users SET password = '".$newPassword."', locked = 0 WHERE token = '".$token."'";
$result = mysqli_query($db,$sql);
if ($result == FALSE){
//add error handling here..
echo "Error updating new password in DB..";
} else {
//good
echo "<script> alert('Password updated! You can now login.'); window.location='login.php'; </script>";
}
} else {
echo "<script> alert('Incorrect code entered, please try again.'); </script>";
}
} else {
echo "<script> alert('It has been longer than 1 hour since you last requested to reset your password and your code has expired. Please request to reset it again on the login page by clicking Forgot Password link at the bottom of the login page.');
window.location='login.php';
</script>";
}
}
Update:
So far I have identified that there is an issue when trying to use PHP's $result->num_rows > 0 with jQuery .post() method. It will return 0 records returned count each time. Tried to return all the data and then do the count on the receiving JS/jQuery end and use something like:
var rowCount = $('#countMe').length;
to count all the div's that come back thinking that would work but it also failed..

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.

Categories