PHP AJAX script not working properly on all conditions - javascript

I have a script where I want to process form data using ajax. The script is returning the success message but not the error message. Have a look at the scripts below.
AJAX Script
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
flip: $("#flip").val(),
amount: $("#amount").val()
};
$.ajax({
type: "POST",
dataType : "json",
url: "flip-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#submit").show();
$("#loading").hide();
},3000);
}
});
return false;
});
});
PHP Script
<?php
session_start();
include'config/db.php';
$msg = null;
$sessionid = (!empty($_SESSION['login']))?$_SESSION['login']:null;
$wp = $pdo->prepare("SELECT set_cointoss_wp, set_cointoss_prob FROM settings");
$wp-> execute();
$sp = $wp->fetch();
$percent = $sp['set_cointoss_wp'];
$probablity = $sp['set_cointoss_prob'];
$bal = $pdo->prepare("SELECT mb_acbal, mb_wallet FROM mem_balance WHERE mb_id = :mem");
$bal-> bindValue(':mem', $sessionid);
$bal-> execute();
$bf = $bal->fetch();
$balance = $bf['mb_acbal'];
$wallet = $bf['mb_wallet'];
$coin = (!empty($_POST['flip']))?$_POST['flip']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
if($_POST){
if($wallet < $amount){
$msg = "<div class='message-error'>Sorry buddy! You have insufficient balance. Please <a href=''>recharge</a> your wallet.</div>";
}else{
$deduct = $wallet-$amount;
$prob = rand(1, 10);
//set new wallet balance after bet amount deduction
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_wallet = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $deduct);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
if($coin == ''){
$msg = "<div class='message-error'>Sorry buddy! Fields cannot be left empty.</div>";
}else{
if($coin == "head"){
if($prob <= $probablity){
$result = 1;
}else{
$result = 2;
}
if($result == 1){
// win
$wa = $amount*$percent;
$win_amount = $wa/100;
$final_cash = $win_amount+$balance;
// update database with winning amount
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $final_cash);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
$msg = "<div class='message-success'>Congratulations buddy! You won... <strong>$".$win_amount."</strong> has been credited to your account.</div>";
}else{
// loose
$msg = "<div class='message-error'>Sorry buddy! You lost... But do not loose hope. Try your luck again :)</div>";
}
}else{
if($prob <= $probablity){
$result = 2;
}else{
$result = 1;
}
if($result == 1){
// loose
$msg = "<div class='message-error'>Sorry buddy! You lost... But do not loose hope. Try your luck again :)</div>";
}else{
// win
$wa = $amount*$percent;
$win_amount = $wa/100;
$final_cash = $win_amount+$balance;
// update database with winning amount
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $final_cash);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
$msg = "<div class='message-success'>Congratulations buddy! You won... <strong>$".$win_amount."</strong> has been credited to your account.</div>";
}
}
}
}
echo json_encode(array('status' => $msg, 'deduct' => $deduct));
}
?>
Here in the scripts above, when if($wallet < $amount) condition is false and else condition is executed, the scripts works fine and returns <div class='message-success'> as required. But, if if($wallet < $amount) condition is true then its not returning <div class='message-error'> and the loading image keeps on moving (as if waiting for the response) but does not receives any response in return. I am stuck since a few days on this but not being able to find any solution for the same. Please help.

I am not sure but I think in your php script $deduct has been declared inside the else block.
so when the script executes and if ($wallet < $amount) condition evaluates to true, then the else part is skipped and you directly return this:-
return echo json_encode(array(
'status' => $msg,
'deduct' => $deduct
));
so it might be the case that $deduct is not recognized. try executing by declaring the $deduct before the if block.

Related

JSON_encode not outputting anything

I want to send a query result from one php file to my javascript, I've used an AJAX which seems to work as it is getting data from my BaseClass.php. However when using JSON_encode, it is not outputting anything at all. So I can't work out how to send a query result from one php file(MySQLDao.php) to my BaseClass.php so I am then able to send it to my Javascript file.
My Code:
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
//$param=$_REQUEST['action'];
//echo json_encode($_GET);
//echo var_dump(json_encode($_GET));
$handle = fopen("php://input", "rb");
$param = $_REQUEST['action'];
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
ob_clean();
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
$result = $dao->getResults($recieved);
}
$dao->closeConnection();
//Return the result of the query
ob_clean();
echo json_encode("param" .$param);
echo json_encode("body" .$body);
echo json_encode("recieved" .$recieved);
echo json_encode("result" .$result);
exit();
}
?>
output for the above echo statements:
"paramgetResults""body""recieved""result"
MySQLDao.php - this file holds the query result that I want to pass to my js
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults()
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
// echo($obj);
// return $obj;
//}
echo json_encode($result);
//echo($result);
//return false;
}
}
?>
My AJAX code in my js file:
$.ajax ({
type: "GET",
datatype: "application/json",
url: "BaseClass.php",
data: { action : 'getResults' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
//alert(output);
}
//error, function(err){console.log(err)}
});
Any help is appreciated thanks!

Variable is not defined even though it is?

Hi I'm trying to call a php function when a button is pressed but I keep getting the error in the title.
I'm calling the function like so:
echo("<th><input type='button' name = 'Attack_Btn' onclick = 'FightPlayer(".$row['username'].")' value ='Attack'></th>");
just say the username that it gets from $row['user... is James the error will display
index.php:1 Uncaught ReferenceError: casualjames is not defined
This is the code that it calls next
function FightPlayer(enemyName){
var xhttpe;
if (window.XMLHttpRequest) {
xhttpe = new XMLHttpRequest();
} else {
xhttpe = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttpe.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
BattlePlayers();
}
};
xhttpe.open("GET", "FightPlayer.php?enemyname="+enemyName, true);
xhttpe.send();
}
and then it calls my php script passing in the variable enemyname for it to use
<?php
session_start();
include 'Training.php';
$link = mysqli_connect("","","","");
if (isset($_SESSION['username'])) {
$enemyname = $_REQUEST["enemyname"];
echo $enemyname;
$energyRemove = 1;
$ExperienceGain = 1;
$sql = "SELECT * FROM userstats WHERE username = '$enemyname'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_assoc($result);
$Defence = $row["Defence"];
$winChance = CalculateWinChance($link,$Defence);
$sql = "SELECT Energy FROM userstats WHERE username = '".$_SESSION['username']."'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_assoc($result);
$rand = rand ( 1 , 100 );
if($row["Energy"] < 1 ){
echo "<script type='text/javascript'>alert('Not enough energy to fight. please restore in character page');</script>";
}else{
if($rand < $winChance){
$_SESSION['Battlemessage'] = "you won against ".$enemyname;
$sql = "UPDATE userstats SET `Energy` = `Energy` - '$energyRemove' WHERE username = '".$_SESSION['username']."'";
mysqli_query($link,$sql);
$sql = "UPDATE userstats SET `Experience` = `Experience` + '$ExperienceGain' WHERE username = '".$_SESSION['username']."'";
mysqli_query($link,$sql);
$sql = "UPDATE userstats SET `Satoshi` = `Satoshi` + 2 WHERE username = '".$_SESSION['username']."'";
mysqli_query($link,$sql);
}else{
$_SESSION['Battlemessage'] = "you lost against ".$enemyname;
$sql = "UPDATE userstats SET `Energy` = `Energy` - '$energyRemove' WHERE username = '".$_SESSION['username']."'";
mysqli_query($link,$sql);
$sql = "UPDATE userstats SET `Satoshi` = `Satoshi` + 1 WHERE username = '".$enemyname."'";
mysqli_query($link,$sql);
}
echo "";
}
calculateLevel($link);
}
?>
I'm not sure where the error is actually happening I've put my scripts through online code checkers and it all returns normal. Where am I going wrong here?
The string you're passing into your javascript function needs to be quoted, or else it thinks that it's a variable:
echo("<th><input type='button' name = 'Attack_Btn' onclick = 'FightPlayer(\"".$row['username']."\")' value ='Attack'></th>");
Your error is most likely with the onclick...you need to escape quotes in the function argument here:
echo("<th><input type='button' name = 'Attack_Btn' onclick = 'FightPlayer(\"".$row['username']."\")' value ='Attack'></th>");

Variable getting via Ajax is empty ( Phonegap-Ajax-Json-PHP-MySQL )

I created an android application using Phonegap. I made an account in 000webhost and I've added my PHP files on the server. In the phpMyAdmin, I've created my database.
Right, now I tried to connect my project with the online database and insert or check some data in it.
PROBLEM:
When I run the application in my mobile phone i get this alert from the success: ... part of code in ajax :
There is no such username.
(my PHP had in comments all the echo, except the: echo json_encode)
When I added this line (var_dump($_POST);) right after i am getting the $usernamefrom ajax in the PHP and run my app, I saw this alert: array(1){ [\"username\"]=> string(2) \"hi"\" }
When I added these lines: if (empty($username)) { echo '...' } , after I run my app, I saw that in the alert inside the error: ... part of the ajax, it is printed the echo that is inside this if. So, the $username is empty for sure.
This is my JavaScript file: (I get correctly for sure all the values from html so Focus on the two Ajax parts of code)
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
var el = document.getElementById("register");
el.addEventListener("click", Register, false);
}
function Register() {
var username = document.getElementsByName('username')[0];
var password = document.getElementsByName('password')[0];
var email = document.getElementsByName('email')[0];
var strong_flag_user = 0;
var user = username.value;
if (username.value == "") {
$("#username").focus();
document.getElementById('username').style.boxShadow = "0 0 7px #f00";
navigator.notification.vibrate(500);
}
else{
$.ajax({
url: "http://www.guidemeforall.freeiz.com/phps/check_for_dublicates/check_username.php",
type: "POST",
crossDomain: true,
data: { username: user },
dataType:'json',
success: function(response){
if (response.status == 'success') {
alert(response.message);
document.getElementById('username').style.boxShadow = "none";
strong_flag_user = 1;
}
else if (response.status == 'error') {
alert(response.message);
navigator.notification.alert("This username is already taken! Please use another one!", null, 'Username', 'Okay');
document.getElementById('username').style.boxShadow = "0 0 7px #f00";
navigator.notification.vibrate(500);
strong_flag_user = 0;
//window.location("main.html");
}
else {
alert("error");
strong_flag_user = 0;
}
},
error: function(error){ //function(error){
alert(JSON.stringify(error));
strong_flag_user = 0;
//window.location = "main.html";
}
});
}
//>5 characters, 1 upper case, at least 1 lower case, at least 1 numerical character, at least 1 special character
var passExp = /(?=^.{6,15}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*/;
var strong_flag_pass = 0;
if (!(password.value.match(passExp))) {
$("#password").focus();
document.getElementById('password').style.boxShadow = "0 0 7px #f00";
navigator.notification.alert("Please enter a strong Password! It has to have at least: 6 characters, 1 upper case, 1 lower case, 1 numerical character and 1 special character!", null, 'Password', 'Okay');
navigator.notification.vibrate(500);
strong_flag_pass = 0;
}
else{
document.getElementById('password').style.boxShadow = "none";
strong_flag_pass = 1;
}
var emailExp = /^.+#[^\.].*\.[a-z]{2,}$/;
var strong_flag_email = 0;
if (!(email.value.match(emailExp))) {
$("#email").focus();
document.getElementById('email').style.boxShadow = "0 0 7px #f00";
navigator.notification.alert("Please enter a correct Email!", null, 'Email', 'Okay');
navigator.notification.vibrate(500);
strong_flag_email = 0;
}
else {
document.getElementById('email').style.boxShadow = "none";
strong_flag_email = 1;
}
var gender;
if (document.getElementById("gender").value == "female")
gender = 'F';
else
gender = 'M';
var about_you = document.getElementById("about_you").value;
var age = document.getElementById("radio-choice").value;
if (document.getElementById('radio-choice-1').checked) {
age = document.getElementById('radio-choice-1').value;
}
else if (document.getElementById('radio-choice-2').checked) {
age = document.getElementById('radio-choice-2').value;
}
else if (document.getElementById('radio-choice-3').checked) {
age = document.getElementById('radio-choice-3').value;
}
else if (document.getElementById('radio-choice-4').checked) {
age = document.getElementById('radio-choice-4').value;
}
else if (document.getElementById('radio-choice-5').checked) {
age = document.getElementById('radio-choice-5').value;
}
else if (document.getElementById('radio-choice-6').checked) {
age = document.getElementById('radio-choice-6').value;
}
if (strong_flag_user == 1 && strong_flag_pass == 1 && strong_flag_email == 1){
//add to db
register_db(email.value, password.value, username.value, gender, about_you, age);
}
}
function register_db(em, pass, user, gend, about, ag) {
$.ajax({
url: "http://www.guidemeforall.freeiz.com/phps/sign-up.php",
type: "POST",
crossDomain: true,
data: { username:user, password:pass, email:em, gender:gend, about_you:about, age:ag },
dataType:'json',
success: function(data)
{
if (data.status == 'success')
{
alert("Success!");
}
else if (data.status == 'error')
{
alert("Failure!");
}
}
});
}
This is my PHP file in which I check if the username already exists (Username = Primary Key):
<?php
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
//require_once('../database_config.php');
$server = "my***.000webhost.com";
$database = "a1****37_guideme";
$username = "a1****37_guideme";
$password = "*****";
$con = mysql_connect($server, $username, $password);
// if($con) { //echo "Connected to database!"; }
// else { //echo "Could not connect!"; }
mysql_select_db($database, $con);
$topost = file_get_contents('php://input');
$thedata = json_decode($topost, true);
$username = $thedata['username'];
//var_dump($_POST);
//if (empty($username)) {
// echo 'The username is either 0, empty, or not set at all';
//}
$sql = "SELECT COUNT(*) as Count FROM `user` WHERE `username`='$username'";
$result= mysql_query($sql, $con);
$rows = mysql_fetch_array($result);
$count = $rows['Count'];
if (!$result) {
die('Error: ' . mysql_error());
//$response_array['status'] = 'error';
//echo json_encode($response_array);
}
else {
if ($count == 0) {
echo json_encode(array('status' => 'success','message'=> 'There is no such username'));
//$response_array['status'] = 'success';
//echo json_encode($response_array);
}
else
{
echo json_encode(array('status' => 'error','message'=> 'The username already exists'));
//$response_array['status'] = 'error';
//echo json_encode($response_array);
}
}
mysql_close($con);
?>
And this is the PHP file in which I tried to insert the new entry in my database ( my credentials are for sure correct):
<?php
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
//require_once('database_config.php');
$server = "mys****.000webhost.com";
$database = "a***37_guideme";
$username = "a***37_guideme";
$password = "******";
$con = mysql_connect($server, $username, $password);
// if($con) { //echo "Connected to database!"; }
// else { //echo "Could not connect!"; }
mysql_select_db($database, $con);
$topost = file_get_contents('php://input');
$thedata = json_decode($topost, true);
$username = $thedata['username'];
$password = $thedata['password'];
$email = $thedata['email'];
$gender = $thedata['gender'];
$age = $thedata['age'];
$about_you = $thedata['about_you'];
$sql = "INSERT INTO user (username, password, email, gender, age, about_you) ";
$sql .= "VALUES ('$username', '$password', '$email', '$gender', '$age', '$about_you')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
// $response_array['status'] = 'error';
// echo json_encode($response_array);
}
else {
echo json_encode(array('status' => 'success','message'=> 'No problem'));
// $response_array['status'] = 'success';
// echo json_encode($response_array);
}
mysql_close($con);
?>
My problem solved by changing the way I get the data in my PHP to -> $user = $_POST['username']; instead of the way with Json (json_decode e.t.c.).

Undefined index errors - How do I set the last amount after discount?

I made a coupon code system for the admin to create new coupons. On the form, I need to calculate the last amount to be paid after the discount. I wrote the
if(!empty($discountCode)) {
$amount = ($unitCost - $unitCost * $couponDiscount / 100);
}
before adding the shipping costs and processing the payment. I'm not sure if it's correct...
I'm getting undefined index errors for $email - $qty - $cardName - $cardAddress1 - $cardAddress2 - $cardCity - $cardState - $cardZipcode - $shippingMethod - $product - $token - $couponDiscount, weird but not for $unitCost, $intRate or $domRate.
How can I fix this?
This is my form preorder.php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Stores errors:
$errors = array();
// Need a payment token:
if (isset($_POST['stripeToken'])) {
$token = $_POST['stripeToken'];
// Check for a duplicate submission, just in case:
// Uses sessions
if (isset($_SESSION['token']) && ($_SESSION['token'] == $token)) {
$errors['token'] = 'You have apparently resubmitted the form. Please do not do that.';
} else { // New submission.
$_SESSION['token'] = $token;
}
} else {
$errors['token'] = 'The order cannot be processed. Please make sure you have JavaScript enabled and try again.';
}
$unitCost = 6995;
$intRate = 1500;
$domRate = 500;
//print_r($_POST);
$email = $_POST['email'];
$qty = $_POST['qty'];
$cardName = $_POST['card-name'];
$cardAddress1 = $_POST['address'];
$cardAddress2 = $_POST['address2'];
$cardCity = $_POST['city'];
$cardState = $_POST['state'];
$cardZipcode = $_POST['zipcode'];
$shippingMethod = $_POST['shipping-method'];
$product = $_POST['productColor'];
$token = $_POST['stripeToken'];
$couponDiscount = $_POST['couponDiscount'];
if(!empty($discountCode)) {
$amount = ($unitCost - $unitCost * $couponDiscount / 100);
}
if($shippingMethod == 'International') :
$amount = $qty * ($intRate + $unitCost);
$description = ''.$qty.' - products(s) in '.$product.'(+International Shipping)';
else:
$amount = $qty * ($domRate + $unitCost);
$description = ''.$qty.' - products(s) in '.$product.'(+Domestic Shipping)';
endif;
// Charge the order:
$charge = Stripe_Charge::create(array(
"amount" => $amount, // amount in cents, again
"currency" => "usd",
"description" => $description,
"customer" => $customer->id
));
// Check that it was paid:
if ($charge->paid == true) {
$amountReadable = $amount / 100; // to add in decimal points
echo '<div class="alert alert-success">Your card was successfully billed for $'.$amountReadable.'</div>';
$status = "paid";
$tracking_num = "";
The form submission is done along with the coupon validation inside preorder.js, which is working well and checking the code correctly :
// Watch for the document to be ready:
$(document).ready(function() {
// Watch for a form submission:
$("#preorder").submit(function(event) {
// Flag variable:
var error = false;
// disable the submit button to prevent repeated clicks:
$('#submitBtn').attr("disabled", "disabled");
// Check for errors:
if (!error) {
Stripe.card.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
}, stripeResponseHandler);
}
// Prevent the form from submitting:
return false;
}); // Form submission
//Coupon code validation
$("#coupon_code").keyup(function(){
var value = $(this).val();
var data = {
code:value,
validateCouponCode:true
}
$.post("core.php",data,function(response){
//Since the response will be json_encode'd JSON string we parse it here
var callback = JSON.parse(response);
if(callback.status){
$("#couponStatus").html(" <span style='color:green'>Coupon is valid =) "+callback.discount_rate+"% discount</span> ");
}else{
$("#couponStatus").html(" <span style='color:red'>Coupon is not valid</span> ");
}
})
})
//Coupon Code validation END
}); // Document ready.
// Function handles the Stripe response:
function stripeResponseHandler(status, response) {
// Check for an error:
if (response.error) {
reportError(response.error.message);
} else { // No errors, submit the form:
var f = $("#preorder");
// Token contains id, last4, and card type:
var token = response['id'];
// Insert the token into the form so it gets submitted to the server
f.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// Submit the form:
f.get(0).submit();
}
} // End of stripeResponseHandler() function.
Here is the core.php:
//For ajax requests create an empty respond object
$respond = new stdClass();
$respond->status = false;
//END
$conn = mysql_connect("localhost",DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME);
//Execute the query
$foo = mysql_query("SELECT * FROM coupons WHERE expire > NOW() OR expire IS NULL OR expire = '0000-00-00 00:00:00'");
//Create an empty array
$rows = array();
while ($a=mysql_fetch_assoc($foo)) {
//Assign the rows fetched from query to the array
$rows[] = $a;
}
//Turn the array into an array of objects
$coupons = json_decode(json_encode($rows));
if(#$_POST["validateCouponCode"]){
foreach ($coupons as $coupon) {
if($coupon->coupon_code == $_POST["code"]){
//Coupon found
$respond->status = true;
//Additional instances to the respond object
$respond->discount_rate = $coupon->coupon_discount;
}
}
echo json_encode($respond);
}
After hours of practice on this, I ended up finding the solution and it's working.
Thanks for everyone for their suggestions.
Still open to any kind of advice to improve the code.
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Stores errors:
$errors = array();
// Need a payment token:
if (isset($_POST['stripeToken'])) {
$token = $_POST['stripeToken'];
// Check for a duplicate submission, just in case:
// Uses sessions, you could use a cookie instead.
if (isset($_SESSION['token']) && ($_SESSION['token'] == $token)) {
$errors['token'] = 'You have apparently resubmitted the form. Please do not do that.';
} else { // New submission.
$_SESSION['token'] = $token;
}
} else {
$errors['token'] = 'The order cannot be processed. Please make sure you have JavaScript enabled and try again.';
}
$unitCost = 4995;
$intRate = 1500;
$domRate = 500;
//print_r($_POST);
$email = $_POST['email'];
$qty = $_POST['qty'];
$cardName = $_POST['card-name'];
$cardAddress1 = $_POST['address'];
$cardAddress2 = $_POST['address2'];
$cardCity = $_POST['city'];
$cardState = $_POST['state'];
$cardZipcode = $_POST['zipcode'];
$shippingMethod = $_POST['shipping-method'];
$product = $_POST['kloqeColor'];
$token = $_POST['stripeToken'];
$couponDiscount = '';
$sql = "SELECT * FROM `------`.`coupons` WHERE `coupon_code` = '" .addslashes($_POST['coupon-code']) . "'";
//echo $sql;
$query = $connectAdmin->Query($sql);
if($query->num_rows > 0) {
$results = $query->fetch_array(MYSQLI_ASSOC);
$couponDiscount = $results['coupon_discount'];
}
//echo '<pre>' . print_r($_POST, true) . '</pre>';
$amount = $unitCost;
if(!empty($couponDiscount)) {
//$amount = ($unitCost - $unitCost * $couponDiscount / 100);
//echo 'Discount not empty<br>';
$amount = $unitCost * ((100-$couponDiscount) / 100);
}
//echo $amount . '<br>';
Can you please add your html of the form? You didn't list stripeToken as undefined index and this your if condition. So the variables $unitCost, $intRate or $domRate can be defined since you are assigning numbers. The question is, why stripeToken is defined but not the other indexes. Probably there is a problem with the form and its fields?

Ajax it does nothing when sending parameters to a php page

I am a beginner using ajax and am trying to change the status of reading a book by clicking an image.
I had the code working but without ajax. Now I have no php error but not a change in mysql.
The code:
<script type="text/javascript">
function sendState(state_id){
var hd_haveread = $("#hd_haveread").val();
var hd_toread = $("#hd_toread").val();
var hd_reading = $("#hd_reading").val();
var val = 0;
var baseurl = "img/";
switch(state_id){
case 1:
if (hd_haveread == "0"){
document.getElementById('hd_haveread').value = "1";
document.getElementById('hd_toread').value = "0";
document.getElementById('hd_reading').value = "0";
val = 1;
}
else{
document.getElementById('hd_haveread').value = "0";
val = 0;
}
break;
case 3:
if (hd_toread == "0"){
document.getElementById('hd_toread').value = "1";
document.getElementById('hd_haveread').value = "0";
document.getElementById('hd_reading').value = "0";
val = 1;
}
else{
document.getElementById('hd_toread').value = "0";
val = 0;
}
break;
case 2:
if (hd_reading == "0"){
document.getElementById('hd_reading').value = "1";
document.getElementById('hd_haveread').value = "0";
document.getElementById('hd_toread').value = "0";
val = 1;
}
else{
document.getElementById('hd_reading').value = "0";
val = 0;
}
break;
}
var parameters = {
"book" : <?php echo $id_book; ?>,
"state" : state_id,
"val" : val
};
$.ajax({
cache: false,
data: parameters,
url: 'change_state_ajax.php',
type: 'post',
dataType: "html",
beforeSend: function (){
},
success: function (response){
switch(state_id){
case 1:
if (hd_haveread == "0"){
$("#img_haveread1").css("display","none");
$("#img_haveread2").css("display","inline-block");
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
else{
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
}
break;
case 3:
if (hd_toread == "0"){
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
$("#img_toread1").css("display","none");
$("#img_toread2").css("display","inline-block");
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
else{
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
}
break;
case 2:
if (hd_reading == "0"){
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
$("#img_reading1").css("display","none");
$("#img_reading2").css("display","inline-block");
}
else{
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
break;
}
}
});
}
</script>
And the change_state_ajax.php code:
<?php
if(isset($_POST['book']) && isset($_POST['state']) && isset($_POST['val'])){
include 'connection.php';
include('php_lib/config.ini.php');
include_once('php_lib/login.lib.php');
$lib_id = $_POST['book'];
$state = $_POST['state'];
$val = $_POST['val'];
$result=changeState($lib_id, $state, $val);
echo $result;
}
function changeState($lib_id, $state, $val){
session_start();
$usu_id = $_SESSION['USSER']['id'];
$mark = 0;
$pos = 0;
$query = $pdo->prepare('SELECT uliusu_id, ulilib_id, uliedl_id FROM '.TABLE_USSERS_BOOKS.' WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->execute();
while($row = $query->fetch(PDO::FETCH_OBJ)){
$mark = 1;
$state_actual = $row->uliedl_id;
}
if($mark == 0){
$query = $pdo->prepare('INSERT INTO '.TABLE_USSERS_BOOKS.' (uliusu_id, ulilib_id, uliedl_id, uli_posicion, uli_fecha) VALUES (:fil_usu_id, :fil_lib_id, :fil_edl_id, :fil_pos, NOW())');
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->bindParam(':fil_edl_id', $state, PDO::PARAM_INT);
$query->bindParam(':fil_pos', $pos, PDO::PARAM_INT);
$query->execute();
}else{
if($state == $state_actual){
$query = $pdo->prepare('DELETE FROM '.TABLE_USSERS_BOOKS.' WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$queryquery->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->execute();
}else{
$query = $pdo->prepare('UPDATE '.TABLE_USSERS_BOOKS.' SET uliedl_id = :fil_edl_id WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_edl_id', $state, PDO::PARAM_INT);
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->execute();
}
}
if($state == 1){
$result = 0;
}else{
$result = 1;
}
return $result;
}
?>
Can anyone help me solve this?
Thanks.
You are not checking for the proper variables. Your JavaScript passes a var called estado but you check in PHP for a var called state.
And because you require all three variables to be set your condition fails.
Also like Hank said in his comment your jQuery.Ajax call uses POST (type: 'post',) but then in your PHP script you check GET variables which of course are not set.
Either change you jQuery call type to GET or change the checking in your PHP script to POST
if(isset($_POST['book']) && isset($_POST['state']) && isset($_POST['val'])){
include 'connection.php';
include('php_lib/config.ini.php');
include_once('php_lib/login.lib.php');
$lib_id = $_POST['book'];
$state = $_POST['state'];
$val = $_POST['val'];
$result=changeState($lib_id, $state, $val);
echo $result;
}
Things I noticed:
1) First you are POSTing but in PHP, you are using $_GET.
2) you are passing "book", "estado", "val" but are trying to get "book", "state", "val", so it never enters into if condition

Categories

Resources