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

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();
}
}}

Related

Server errors displayed instead of loading data from database

I don't know what I'm missing. I'm trying to load data from database into the navbar. Navbar should have different links for administrators, signed users and other users. Since I didn't make page for sign in and sign up yet, I assumed that the code from page showMenu.php called with AJAX will take last function loaded from functions.php which is a query for not signed in users. But instead of getting data back from the database to write with JS, the code fall into error property of AJAX call and in addition to that displays server error 500 for showMenu.php page. I checked all the paths for both main.js and php pages and names of tables and columns in database and everything is correct. And just for the record, connection.php includes fetch mode, so columns of tables can be accessed with ->. What do I'm missing.
js code
getViaAjax("showMenu",showMenu);
function getViaAjax(fileName, specificFunction) {
$.ajax({
url: "models/" + fileName + ".php",
method: "get",
dataType: "json",
success: function(jsonData){
specificFunction(jsonData);
},
error: function(xhr){
console.error(xhr);
}
});
}
function showMenu(menuJsonData){
let writingMenu = "";
menuJsonData.forEach(partOfMenu=>{
writingMenu+=`<li id="${partOfMenu.id}" class="nav-item">
<a class="nav-link" href="${partOfMenu.href}">${partOfMenu.label}</a>
</li>`;
});
document.getElementById("menu").innerHTML=writingMenu;
}
showMenu.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'GET'){
include "../config/connection.php";
include "functions.php";
try{
if(isset($_SESSION['user'])){
$user = $_SESSION['user'];
if($user->roleId==1){
$jsonMenu = showMenuForAdmin();
}
else {
$jsonMenu = showMenuForSignedInUser();
}
}
else{
$jsonMenu = showMenuForNonSignedInUser();
}
echo json_encode($jsonMenu);
http_response_code(200);
}
catch(PDOException $exception){
http_response_code(500);
}
}
else{
http_response_code(404);
}
?>
function from functions.php I want to be triggered when user not registered or signed
function showMenuForNonSignedInUser(){
global $connection;
$query = "SELECT id, href, label WHERE id NOT LIKE 6;";
$data = $connection->query($query)->fetchAll();
return $data;
}

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.

Comparing strings in JQuery not working

Alright so here's the situation. I have the following code block in my php file, and for some reason, whenever it comes to check data, it doesn't accept. I've printed out the value of data, and it is indeed "accepted" (without quotes obviously). Am I comparing these wrong somehow? Running basically the exact same code in another section of my website and it works fine.
$(document).ready(function () {
$("#sign").click(function () {
jQuery.ajax({
url: "loginConfirm.php",
data: { // Correct
username: $("#username").val(),
password: $("#password").val()
},
type: "POST",
success: function (data) {
if ($("#username").val() === "") {
//Do nothin
} else if (data === "accepted") {
alert("Here");
redirectSignIn();
} else {
alert("There");
$("#signInTitle").html(data);
}
},
error: function () {}
});
});
});
EDIT: php code I'm calling in the url below
<?php
// The global $_POST variable allows you to access the data sent with the POST method
// To access the data sent with the GET method, you can use $_GET
$username = htmlspecialchars($_POST['username']);
$userpassword = htmlspecialchars($_POST['password']);
require_once("dbcontroller.php");
$db_handle = new DBController();
$result = mysql_query("SELECT count(*) FROM loginInfo WHERE userName='" . $username . "' AND password='" . $userpassword . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0)
echo "accepted";
else
echo "denied";
?>
You cant validate if ($("#username").val() === "") { in success function. For that you are suppose to validate it before making Ajax call.
I would like to give some advice here that first you have to validate the inputs of the user if validate then you can call ajax.
and then you not required to check the value of the username in AJAX process.
Like....
if($("#username").val() === "" && $("#passoword").val() === "")
{
//AJAX call
}
else
{
//alert to enter the valid inputs
}
hope you get it my concept...

Ajax POST to PHP - How do I do a reply?

I have sent an email address via an ajax post from javascript to php. I have then searched the database in php to find out if this email exists in the database. How can i then send a message back to the javascript/html to say that the value was present?
This is what I used to send the request:
function postEmail(){
var checkEmail = "someone#gmail.com";
var dataString = 'checkEmail1='+ checkEmail;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "myfile.php",
data: dataString,
cache: false,
success: function(result){
alert("Sent successfully");
}
});
}
and then in the PHP:
$checkEmail2=$_POST['checkEmail1'];
$results = mysql_query("select id from myTable where emailaddress='$checkEmail2' ");
$row = mysql_num_rows($results);
if ($row > 0 ) {
echo "email already exists";
} else {
if ($row == 0 ) {
echo "email doesnt exist";
}
}
Not sure if I should do a get request? Or if you return values or something. Thanks.
(p.s, Im developing a hybrid app so need to use JSON to send/retrieve from PHP)
I think you need to remove second condition! output json or any other format you want. I use json_encode for arrays
try:
$checkEmail2=$_POST['checkEmail1'];
$results = mysql_query("select id from myTable where emailaddress='$checkEmail2' ");
$row = mysql_num_rows($results);
if ($row > 0 ) {
echo "email already exists";
} else {
echo "email doesnt exist";
}
JAVASCRIPT
from your success function, print the result to the console to see the output
console.log(result);
What you echo from the PHP script is sent back to the success function in the javascript, as the result parameter. So the result parameter will contain "email already exists" or "email doesnt exist"

Generate message after sending iFrame Email

I have used the following guide to ifugre out how to send emails with file uploading without refreshing the page: http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/ and it works fine, except that I'd like to be able to take a message from the php I use to upload the file and send the email, so that I can display that message to the user, on the page where they submitted the form from.
I have this code currently in my contact.php page:
if (!$sentMail) {
header('HTTP/1.1 500 Couldnot send mail! Sorry..');
exit();
} else {
echo '<h3>Hi ' . $postName . ', Thank you for your email</h3>
<p>Your email has already arrived in our Inbox, all We need to do is Check it.
<br />Good day.</p>';
}
The only problem is getting that message that I've echoed to show up where I'd like it to go. Any help would be greatly appreciated.
The PHP in the iFrame should post unique sessionID in the database with result.
In the meanwhile you can do an Ajax call to check the database if the mail is sent.
So we got 3 files
Your form (like index.html)
Your Mailer in iframe (like sendMail.php)
Your status checker (like getStatus.php)
Here we go..
Your IFRAME Mailer:
<?php
session_start();
$_SESSION['mailsender'] = mt_rand();
// this is ur iframe mailer
// here your mail send stuff .....
// if mail is sent
mysql_query("INSERT INTO mailsender (mailid, result) VALUES ('".$_SESSION['mailsender']."', 'successfull')");
// if mail fails
mysql_query("INSERT INTO mailsender (mailid, result) VALUES ('".$_SESSION['mailsender']."', 'failed')");
?>
getStatus.PHP :
<?php
session_start();
// check status and give JSON back
// getStatus.php - we be called from front-end
$query = mysql_query("SELECT * FROM mailsender WHERE mailid = '".$_SESSION['mailsender']."'");
$result = "Pending";
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_array($query)) {
$result = $rij['result'];
}
}
echo json_encode(array("result"=>$result));
?>
Your Front-end like Index.html:
<!DOCTYPE html>
<html>
<!-- include jQuery -->
<script>
$(document).ready(function(){
checkMailStatus = function() {
$.ajax({
url: 'getStatus.php',
dataType: 'JSON',
success: function(data) {
if (data['result'] == "successfull") {
// do successfull stuff here
// also clear the interval
}
if (data['result'] == "failed") {
// do failed stuff here
}
if (data['result'] == "pending") {
// still trying to send
// do stuff here while sending (like loading.gif)
}
}
})
}
$(".sendmailbutton").click(function(){
setInterval(function(){
checkMailStatus();
}, 800)
})
})
</script>
</html>

Categories