How to store JavaScript variable in the database - javascript

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.

Related

SQL query not being executed from AJAX '$_POST' to PHP file

I'm retrieving user information from the facebook API and sending it via AJAX to my php file to write into the mysql database.
The reason for this is so I can generate a random voucher code to give to them, which is also being written to the database.
I'm not at all experience in this and I'm just learning along the way.
my php file:
<?php
include_once 'db_connect.php';//$mysqli = new mysqli(HOST, USER, PASSWORD,
DATABASE);
include_once 'psl-config.php';//database login details
if(isset($_POST['name'],$_POST['email'],$_POST['id'])){
$name = $_POST['name'];
$email = $_POST['email'];
$uid = $_POST['id'];
$code = generateRandomString();
$prep_stmt="INSERT INTO memberinfo (name, email, id,code,dateadded) VALUES ('$name','$email','$uid','$code',now())";
$stmt = $mysqli->prepare($prep_stmt);
if($stmt) {
$stmt->execute();
$stmt->close();
}}
my javascript then runs this from the facebook button with the onlogin="checkLoginState();" function:
function checkLoginState() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me', { locale: 'en_US', fields: 'name,email,id' },
function(response) {
$.ajax({
method: "POST",
url: "includes/process_fb_login.php",
data: response,
dataType: 'json',
cache: false,
success: function(data){
console.log(data);
}
});
});
}else{
alert("Failed to login");
}
});
}
At the moment nothing is being written into the database and I'm not even sure how to troubleshoot to see what's being executed along the way.
I had a couple of issues:
Firstly - My database id was type "Integer". Meaning the ID number I was getting from facebook was 15 characters long and the maximum value you can have is 2147483647(10 chars) (Signed) or 4294967295 (Unsigned). So I changed this to varchar.
Secondly - It seems that if(isset($_POST['name'],$_POST['email'],$_POST['id'])) was stuffing me up a bit, I couldn't get it to run past that line.
In the end this is the code that worked for me.
Not sure if it's the best way to do it but, hey, it works for me.
$email_exists="select email from memberinfo where email ='".$_POST['email']."'";
$exe = $mysqli->prepare($email_exists);
if($exe) {
$exe->execute();
$exe->store_result();
if ($exe->num_rows == 1) {
// A user with this email address already exists
$exe->close();
} else {
$prep_stmt = "INSERT INTO memberinfo (name, email,username,id,code,dateAdded)
VALUES ('".$_POST['name']."','".$_POST['email']."','".$_POST['email']."','".$_POST['id']."','$code',now())";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->execute();
$stmt->close();
}
}}

I want to get $username variable from another page using ajax

This is my ajax code:
$(document).ready (function() {
$("#send").click (function() {
var username = $(this).val();
alert (username);
$.ajax({
url : "sendpost.php",
type: 'POST',
async: false,
data: {username},
success: function(datat){}
})
});
});
This is my php code
include ('connection_socio.php');
if(isset($_POST['body']))
{
$body=mysqli_real_escape_string($db, $_POST['body']);
$date_added="123";
$added_by="123";
$username = mysqli_real_escape_string($db, $_POST['username']);
$check = "SELECT * FROM users";
$result_profile = mysqli_query($db, $check);
//check whether the no of rows in users table is more than 0
//get username from database
$getusername = mysqli_fetch_assoc($result_profile);
$user_posted_to = $username;
echo $user_posted_to;
$query_post = "INSERT INTO posts VALUES ('', '$user_poste_to',)";
mysqli_query($db, $query_post);
echo "POSTED SUUCESSFULLY";
}
This is my profile.php code:
if (isset($_GET['u']))
{
$username = mysqli_real_escape_string($db, $_GET['u']);
//checks and remove symbols like # , ' etc
if(ctype_alnum($username))
{
//check user existance
$check = "SELECT * FROM users WHERE username='$username'";
$result_profile = mysqli_query($db, $check);
//check whether the no of rows in users table is more than 0
if(mysqli_num_rows($result_profile) == 1)
{
//get username from database
$getusername = mysqli_fetch_assoc($result_profile);
$username = $getusername['username'];
}
else
{
echo "User dont exist";
exit();
}
}
}
what I want is to fetch variable $username from profile.php page and assign it to $user_posted_to variable in senpost.php page and insert into database using javascript if any expert can help will really appreciate it i have tried this.attr() but thats not working also this.value is also not working I'm unable to fetch username from that page can anyone help me with this the username variable i want to fetch is the username of the user profile which I want to assign to $user_poste_to
I believe, the best way to access the value of $username is to store it to a cookie, once you are in senpost.php, all you need to do is to get the cookie you stored and assign it to $user_posted_to variable. the correct way to get the value of a textbox/form element in by using this $(input[type="text"]).val()
Update your AJax call.
data: {username:username},
here first username will be the index and 2nd username will be the variable which you got using $(this).val()

Lag issues cause of AJAX/PHP

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

Why is my PHP script returning different results on similar inputs?

Background: I am doing ajax calls to a PHP script which returns data to fill a form based on some file key a user inputs. This form is used so users may edit an incorrectly inputted file key from their original submission.
Problem: If a user wanted to edit a file key, they input it into a text box, hit a button for an ajax pull, the form fills, they can then correct their mistakes and submit. However, if they try to edit the new file key again, the form will not fill and I am getting no results returned from the query. This is the php script I have been using to pull the data from the server.
A sample file key might be: 10000010000-0D-MAN.
This is a good response: 10000010000-0D-MAN,N/A,amibaguest,dfgfdgfd,Electrical
This is the response I get on a newly edited file key: Nothing returned. Id: 20000010000-0D-MAN.
Really baffled at the moment. If more information is needed, please let me know.
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("database", $dbhandle)
or die("Could not select database");
$id = $_GET['param'];
if(isset($_GET['param'])) {
$sql = sprintf("SELECT a.File_key, a.Name, a.Uploader, a.File_descriptor, b.keyword1 FROM files as a, keyword as b WHERE a.File_key='%s' AND a.File_key=b.File_key", mysql_real_escape_string($id));
$result = mysql_query($sql);
if($result === FALSE) {
echo mysql_error();
}
if(mysql_num_rows($result)==1) {
while($myrow = mysql_fetch_array($result)) {
$file_key = $myrow["File_key"];
$name = $myrow["Name"];
$uploader = $myrow["Uploader"];
$file_desc = $myrow["File_descriptor"];
$keyword = $myrow["keyword1"];
$text_out .= $file_key.",".$name.",".$uploader.",".$file_desc.",".$keyword;
}// end while
} else {
$text_out = " Nothing returned. Id: ".$id;
}// end else
}// endif
echo $text_out;

after insert no return anything but data have been save

<?php
$host="localhost";
$user="root";
$password="";
$con=mysqli_connect("localhost","root","","recipe");
if ($_GET['type'] == "upload")
{
$title=$_GET['title'];
$creator=$_GET['creator'];
$ingredient=$_GET['ingredient'];
$serving=$_GET['serving'];
$note=$_GET['note'];
$prepare=$_GET['prepare'];
$insertsql = "INSERT INTO upload (title,creator,ingredient,serving,note,prepare)
VALUE ('$title','$creator','$ingredient','$serving','$note','$prepare')";
if(mysql_query($insertsql,$db))
{echo 1; }
else
{echo 0; }
}
?>
<script>
$.ajax({
type : "get",
url : "dataconn.php",
data : "type=upload&title="+title+"&prepare="+prepare+"&creator="+creator+"&ingredient="+ingredien t+"&serving="+serving+"&note="+note,
success : function(data){
alert(data);
}
});
</script>
</head>
</html>
When I pass variable in to PHP from JavaScript it able to save in database but I need some value like the data have been successful save and will come out a alert 1 or 0.
But once I connect to database it cant alert any more. Like some error blocking in database but still can save just does not come out any alert. If I remove it then it running all
It does not sure alert as well.
Change this line:
if(mysql_query($insertsql,$db))
To this line; using mysqli_* extensions and correctly using $con for the query instead of $db which is a connection variable you don’t have set anywhere:
if(mysqli_query($con,$insertsql))
Also, you should set your MySQL calls to return errors like this:
$con=mysqli_connect("localhost","root","","recipe") or die(mysqli_connect_errno());
And change this as well:
$result = mysqli_query($con,$insertsql) or die(mysqli_connect_errno());
if ($result) {
echo 1;
}
else {
echo 0;
}
Also you are using VALUE in the query when it should be VALUES:
$insertsql = "INSERT INTO upload (title,creator,ingredient,serving,note,prepare)
VALUES ('$title','$creator','$ingredient','$serving','$note','$prepare')";
Not to mention in your JavaScript AJAX code you have +ingredien t+ when it should be +ingredien t+:
data : "type=upload&title="+title+"&prepare="+prepare+"&creator="+creator+"&ingredient="+ingredient+"&serving="+serving+"&note="+note,
At the top why are you setting variables for the MySQL connection but then putting values inline?
$host="localhost";
$user="root";
$password="";
$con=mysqli_connect("localhost","root","","recipe");
And finally, I did a cleanup of your main MySQL logic code. I have included mysqli_stmt_bind_param, mysqli_free_result & mysqli_close and set a foreach loop for $_GET values. This simply should work:
// Credentials.
$host="localhost";
$user="root";
$password="";
// Connecting, selecting database
$con = mysqli_connect($host, $user, $password, 'recipe') or die(mysqli_connect_errno());
if (isset($_GET['type']) && !empty($_GET['type']) && $_GET['type'] == "upload") {
// Set a '$_GET' array and roll through each value.
$get_array = array('title', 'creator', 'ingredient', 'serving', 'note', 'prepare');
foreach ($get_array as $get_key => $get_value) {
$$get_value = isset($_GET[$get_value]) && !empty($_GET[$get_value]) ? $_GET[$get_value] : null;
}
// Set the query.
$insertsql = "INSERT INTO `upload` (`title`, `creator`, `ingredient`, `serving`, `note`, `prepare`)"
. " VALUES (?, ?, ?, ?, ?, ?)"
;
// Bind the params.
mysqli_stmt_bind_param($insertsql, 'ssssss', $title, $creator, $ingredient, $serving, $note, $prepare);
// Run the query.
$result = mysqli_query($con, $insertsql) or die(mysqli_connect_errno());
if ($result) {
echo 1;
}
else {
echo 0;
}
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
}

Categories