jquery ajax not calling php class correctly - php

I am trying to make a ajax call to do a database update in my php class. However, it seems the class is being called but the parameters are not passed for some reason.
Here is my jquery:
$(".sendRSVP").click(function(e){
e.preventDefault();
var nameArray = [];
//var uniqueCode = parseInt($(this).find('.theCheckbox').attr('id'));
//var response = ($(this).find('.theCheckbox').is(":checked")) ? '1' : '0';
//the parameters passed should be uniqueCode and response which both gave legit values
if($("#displayContacts").is(":visible")){
$.get("submitRSVP.php", {rs: '1', resp: '12345'})
.done(function(rtn){
console.log(rtn); //error is returned
})
}
});
Here is my php code:
<?php
require 'dbh.php';
$rsvp = $REQUEST["rs"];
$response = $REQUEST["resp"];
session_start();
if(session_start()) $invitationCode = $_SESSION['login_user'];
$hint = "here1";
try{
$updateQuery = "UPDATE `db686470460`.`GuestWithPlusOnes` SET `Confirmed`= '$response' WHERE `GuestWithPlusOnes`.`UniqueID`= '$rsvp'";
$updateStmt = $conn->prepare($updateQuery);
$updateStmt->execute();
if ($updateStmt->rowCount() > 0) {
$hint = 'success';
}else {
$hint = 'error';
}
$_SESSION['login_user'] = $rsvp;
$updateStmt = null;
}
catch(Exception $e){
$hint = $e;
}
echo $hint;
?>
I definitely have a record in my table with that uniqueId because when I change the query to:
$updateQuery = "UPDATE `db686470460`.`GuestWithPlusOnes` SET `Confirmed`= '1' WHERE `GuestWithPlusOnes`.`UniqueID`= '12345'";
that updates as normal. Is there something else I could be missing?

Related

Problem converting PHP file to Prepared statements

I'm trying to convert PHP file to Prepared statements. The original file is as follows and it is 100% working before modification:
<?php
include 'connt.php';
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$Name = $obj['Name'];
$loginQuery = "select * from Users where Name = '$Name' ";
$check = mysqli_fetch_array(mysqli_query($con, $loginQuery));
if ($check) {
$check['result'] = 'Login Matched';
$SuccessMSG = json_encode($check);
echo $SuccessMSG;
} else {
$InvalidMSG = array("result" => "Invalid Username or Password Please Try Again");
$InvalidMSGJSon = json_encode($InvalidMSG);
echo $InvalidMSGJSon;
}
mysqli_close($con);
In the above code, I am checking the data if it matches or not by using the flutter language code:
Future CheckName() async {
setState(() {
visible = true;
});
// var url = 'https://///////////////.php';
var data = {'Name': nameController.text};
var response = await http.post(url, body: json.encode(data));
Map<String, dynamic> message = jsonDecode(response.body);
if (message['result'] == 'Login Matched') {
setState(() {
visible = false;
});
Navigator.push(context, MaterialPageRoute(builder: (context) => Main()));
} else {
setState(() {
visible = false;
});
_showMyDialog();
}
}
Now after modifying the php code as follows:
<?php
include 'connt.php';
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$Name = $obj['Name'];
$sql = "SELECT * FROM Users WHERE Name=?"; // SQL with parameters
$stmt = $con->prepare($sql);
$stmt->bind_param("s", $Name);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$user = $result->fetch_assoc(); // fetch data
if ($result) {
$check['result'] = 'Login Matched';
$SuccessMSG = json_encode($check);
echo $SuccessMSG;
} else {
$InvalidMSG = array("result" => "Invalid Username or Password Please Try Again");
$InvalidMSGJSon = json_encode($InvalidMSG);
echo $InvalidMSGJSon;
}
mysqli_close($con);
After modification as above on the code. Now it works, but even if the name is wrong, it works correctly, it does not check if the name is present or not.
How to convert the first file from PHP in a correct way to Prepared statements or can solve the existing error?

How to get php session data from a google sign in

I am trying to create a website where users login with their google login (https://developers.google.com/identity/sign-in/web/sign-in). The site has multiple pages and gets data for the user from a mysql database. I would like to store the users' data (name, email) in a php session to have ready for the php when accessing the database. The login function works, but I can't figure out how to get the data to php, with it currently all in javascript.
There wasn't a conventional way to do this, but I was able to get the information from the google auth token
function get_var($var_index) {
$id = $_POST["id"];
$id_token = file("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" . $id);
$var = str_replace("\"", "", $id_token[$var_index]);
$var = str_replace(",", "", $var);
$var = substr($var, strpos($var, ":") + 2 );
return $var;
}
$name = get_var(12);
$email = get_var(5);
$img_url = get_var(13);
$exp = get_var(8);
$iss = get_var(9);
if ($_SERVER['REQUEST_TIME'] < $exp) {
session_start();
$_SESSION["name"] = $name;
//$_SESSION["imageurl"] = $img_url;
$_SESSION["email"] = $email;
$_SESSION["exp"] = $exp; // when to auto logout
header("LOCATION: page.php");
exit();
} else{
header("LOCATION: loginpage.html");
}
You can use ajax for this. It's a very efficient way. just make sure you have jquery uncmopressed or minified (not slim) in you page and you're good to go.
This my javascript code in my page where the button is:-
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
$.ajax({
type: "POST",
url: "googlesignin.php?action=google",
data: "gmail=" + profile.getEmail() + "&name=" + profile.getName(),
success: function(result) {
if (result == 1) {
alert("Hello, " + profile.getName());
$("#googlesignin").hide();
} else {
alert("failed to login");
}
}
})
}
So now the new file called googlesignin.php from where you will execute the insert query to the mysql database
if ($_GET['action'] == "google") {
$email = $_POST['gmail'];
$name = $_POST['name'];
$query = "SELECT * FROM google WHERE email='".$email."' AND name='".$name."'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
echo 1;
} else {
$query = "INSERT INTO google (email, name) VALUES ('".$email."', '".$name."')";
$result = mysqli_query($link, $query);
echo 1;
}
}
so now we have stored our post variables as php variables and we can use them easily to execute our insert query. but we need to check whether the email has first registered or not.

How to get a single mysql value and output it to an ajax call?

I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.

How to pass variables from PHP to Flash (ActionScript 3)

I need to select game's number from MySql database and pass It to Flash game (ActionScript 3).
For now I have AS3 code:
function getVars(e:Event):void{
var req:URLRequest = new URLRequest("top.php");
var loader:URLLoader = new URLLoader(req);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, getVarComplete);
}
function getVarComplete(e:Event):void{
var gameNr.text = e.target.data;
}
And here is PHP code (I don't know how selected row pass to variable and send It to flash)
$id = $_SESSION['id'];
$mysqli = new mysqli("localhost","xxx","xxx","xxx");
$query = "SELECT GameNr
FROM Game
WHERE FBId = '". mysql_real_escape_string($id) ."'
ORDER BY PlayTime DESC LIMIT 1";
UPDATE:
If I use following PHP:
<?php
session_start();
$id = $_SESSION['id'];
$mysqli = new mysqli("localhost","xx","xx","xx");
$query = "SELECT GameNr
FROM Game
WHERE FBId = '". mysql_real_escape_string($id) ."'
ORDER BY PlayTime DESC LIMIT 1";
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
}
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row["GameNr"];
}
$result->free();
}
$mysqli->close();
?>
www.myhost.com/top.php returning correct value NA==
If I use following AS3 code:
function onVarsLoaded(e:Event) {
var msg:String = "Communication with the server was successful.\n\n";
msg += "foo -> "+e.target.vars.foo+"\n";
trace(msg);
}
It returning me: foo -> undefined
If I change this
msg += "foo -> "+e.target.vars.foo+"\n"; to
msg += "foo -> "+e.target.vars+"\n";
It returning me incorrect value: foo -> NA=%3D
Try this:
AS3:
import net.kaegi.loaders.VarLoader;
var vl:VarLoader;
sendBtn.addEventListener(MouseEvent.CLICK,sendBtnHandler);
function sendBtnHandler(e:MouseEvent) {
// Variables sent by POST-Method:
var varObj:Object = {};
varObj.textinput0 = escape(textinput0.text);
varObj.textinput1 = escape(textinput1.text);
vl = new VarLoader("http://yourserver.com/landing.php?foo=foo", varObj);
vl.addEventListener(Event.COMPLETE, onVarsLoaded);
vl.addEventListener(Event.CANCEL, onVarsCancel);
}
function onVarsLoaded(e:Event) {
var msg:String = "Communication with the server was successful.\n\n";
msg += "foo -> "+e.target.vars.foo+"\n";
tf_servermsg.textColor = 0x009900;
tf_servermsg.text = msg;
}
function onVarsCancel(e:Event) {
tf_servermsg.textColor = 0x990000;
tf_servermsg.text = e.target.errormsg;
}
PHP
// handle coming get
$foo = $_GET["foo"];
// handle coming post from flash
$textinput0 = $_POST["textinput0"];
$textinput1 = $_POST["textinput1"];
// send it to flash
$yourdata = "hello world"; // your mysql data here
echo $yourdata;
PHP code in addition to your code
$mysqli->real_query($query);
$res = $mysqli->use_result();
while ($row = $res->fetch_assoc()) {
echo $row['GameNr'];
}
Please check in format the data is required from PHP script. currently the php code will give you result of GameNr as text.
Hope it helps!

Query in Jquery IF statement

I have a jquery save script like :
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Your file is save as : '+ naam);
window.location.replace("index.php?id=latest");
}
else
{
alert('Not saved');
}
I save a div in save.php which creates an new id in the database
What I want to achive is were
window.location.replace("index.php?id=latest");
id=latest must become (id=id from last saved file).
I tried
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
window.location.replace("index.php?id="+MBId);
and
var MBID =
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo $MBId ?>
window.location.replace("index.php?id="+MBId);
They both failed.
How can I run the query in the if(naam !=null) statement?
At first place you must fix your jQuery POST... You don't use POST respond which is wrong.. You should wait for it and then continue with other actions
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam }, function(responde){
if(responde.id)
window.location.replace("http://yoururl.com/index.php?id="+responde.id);
else
alert("No responde...");
}, "json");
}
else
{
alert('Not saved');
}
For better results I suggest you to use JSON data in that post/respond..
At your PHP code you have to set:
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo json_encode(array('id'=>$MBId));
exit();
?>
P.S. For window.location.replace please set your FULL url: "http://localhost/index.php?id=" OR atleast put slash at start of it "/index.php?id="
Solution
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Uw moodboard is opgeslagen als '+ naam);
window.location.replace("index.php?id=<?php $q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = ($data[0] + 1); echo "$MBId";?>");
}
This Works for me , i didnt need to make a jquery var i could echo the variable in php.
And i had to add 1 cause the sql query is loaded when the page is loaded.
So the file isn't saved yet when i get the highest id.

Categories