Hi i am inserting data multiple data with for loop . and fetching thos data from database nd inserting to ghseet again now i want to make it happen at a time.
my for each loop is here
if (in_array($_POST['prodname'][$key], $checked_array)) {
$prodname = $_POST['prodname'][$key];
$prod_price = $_POST['prod_price'][$key];
$prod_qty = $_POST['prod_qty'][$key];
$prodsname = $_POST['prodsname'][$key];
$app_id = $_POST['app_id'][$key];
$district = $_POST['district'][$key];
$upazilla = $_POST['upazilla'][$key];
$store_name = $_POST['StoreName'][$key];
$ward = $_POST['ward'][$key];
for ($x = 0; $x < $prod_qty; $x++) {
$couponnumber = random_int(100, 100000);
$sql = "INSERT INTO `retailer_sales`( `product`, `Amount`, `quantity`,`C_Number`,`Retailer_Number`,`Dtistrict`,`Upzilla`,`coupon_number`,`StoreName`,`ward`) VALUES ('$prodname','$prod_price','$prod_qty','$prodsname','$app_id','$district','$upazilla','$couponnumber','$store_name','$ward')";
$result = $db->query($sql);
if ($result) {
$_SESSION["status"] = true;
} else {
$_SESSION["server_down"] = true;
echo '<script>window.location="../../pages/product_sale/main.php";</script>';
}
}
}
and my javascript code for sending to gsheet is
<script>
const scriptURL = 'https://script.google.com/macros/s/AKfycbzfMQmBwDEO8k0H8jeLlKTE_GzK0XuQ1unZd_5ib_DDBhM17b6FVahIW5f3W4FyfCNOAw/exec'
const form = document.forms['submit-to-gateway']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, {
method: 'POST',
body: new FormData(form)
})
.then(response => $("#form_alerts").html("<div class='alert alert-success'>Id Sent Successfully.</div>"))
.catch(error => $("#form_alerts").html("<div class='alert alert-danger'>Id Could not be Sent.</div>"))
$('#myForm')[0].reset();
})
</script>
i want to insert each data which is inserting to mysql database.
help me with this.
Related
i have been developing a WordPress plugin that has a form that sends some data to a Database.
My problem is that every time i click the submit button the callback runs twice, and the information that appears in my database is duplicated.
My jQuery code is:
$("#submit_btn").click( function (event) {
event.preventDefault();
let uuid = uuidv4()
let form_serialize = $("form").serializeArray();
let dataForm = {
"id": uuid,
'submitId': uuid
}
$.each(form_serialize, function (i, field) {
dataForm[field.name] = field.value
});
$.ajax({
url: ccandidates.ajax_url,
type: "POST",
crossDomain: true,
cache: false,
data: {
security: candidates.ajax_nonce,
action: 'SendToFormApi',
data: dataForm
},
dataType: 'json',
success: function (data, status, xhttp) {
// event.preventDefault();
if (data === true) {
window.location = candidates.merci_page_url;
} else {
window.location.href = candidates.error_page_url;
$("form").trigger('reset')
}
},
}
);
});
Callback function
function SendToFormApi_callback()
{
$formRandyValues = $_POST['data'];
$virtualagencyApiEmail = new virtualagencyApiEmail();
$result = $virtualagencyApiEmail->NyFormApi($formRandyValues);
$response = $virtualagencyApiEmail->NyFormApiCall($result,$formMyValues['id']);
$code = wp_remote_retrieve_response_code($response);
// if code 503 == service unavailable
// if code 401 == auth fail
// if code 400 == object fail
// if code 201 == success response
if ($code === 201) {
echo json_encode(true);
wp_die();
} else {
echo json_encode(false);
wp_die();
}
}
add_action('wp_ajax_SendToFormApi', 'SendToFormApi_callback', 1);
add_action('wp_ajax_nopriv_SendToFormApi', 'SendToFormApi_callback', 1);
public function NyFormApi($params): array
{
$uuidId = $params['id'] ?? $this->getUid();
$position_criteria_object = new Position_Criteria();
$position_criteria_object->type = 'string';
$position_criteria_object->label = 'besoin';
$position_criteria_object->question = 'votre_besoin';
$position_criteria_object->answer = $params['votreBesoin'];
$position_criteria_object->value = $params['votreBesoin'];
$origin_object = new Position_Criteria();
$origin_object->type = 'string';
$origin_object->label = 'origin';
$origin_object->question = 'candidature_oringin';
$origin_object->answer = 'My form';
$origin_object->value = 'My form';
$secteur_object = new Position_Criteria();
$secteur_object->type = 'string';
$secteur_object->label = 'secteur';
$secteur_object->question = 'secteur';
$secteur_object->answer = $params['secteur'];
$secteur_object->value = $params['secteur'];
$region_object = new Position_Criteria();
$region_object->type = 'string';
$region_object->label = 'region';
$region_object->question = 'region';
$region_object->answer = $params['region'];
$region_object->value = $params['region'];
$metier_object = new Position_Criteria();
$metier_object->type = 'string';
$metier_object->label = 'metier';
$metier_object->question = 'metier';
$metier_object->answer = $params['metier'];
$metier_object->value = $params['metier'];
$talent_object = new Talent();
$talent_object->id = $uuidId;
$talent_object->firstName = $params['firstName'];
$talent_object->lastName = $params['lastName'];
$talent_object->email = $params['email'];
$talent_object->phone = $params['phone'];
if(empty($params['qualificationCode'])){
$qualificationCode = "none";
} else {
$qualificationCode = $params['qualificationCode'];
}
return array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode($this->keyEncoded)
),
'body' => array(
'id' => $uuidId, //$params['id'], // str
'workTeamId' => $params['postClient'], // str
'priority' => 1, // int
'positionCriteria' => array(
$position_criteria_object,
$origin_object,
$secteur_object,
$region_object,
$metier_object
), // [{...},{...},...]
'occupationCode' => $qualificationCode, // str,
'occupationLabel' => $params['qualification'], // str
'talent' => $talent_object, // { key = value, ... }
)
);
}
public function MyFormApiCall($params, $id)
{
$url = $this->apiPathRandy . "/" . $id;
return wp_remote_post($url, $params);
}
// Get an RFC-4122 compliant globaly unique identifier
private function getUid(): string
{
$data = PHP_MAJOR_VERSION < 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
After reading and trying some solutions that i found, no of them work in my case.
Thank you for your help.
(note: there are some vars names that were changed for privacy)
I would remove all javascript from the form and do
if ($code === 201) {
header("location: merci.html");
wp_die();
} else {
header("location: erreur.html");
wp_die();
}
I send 2 variables by url:
var http = false;
http = new XMLHttpRequest();
function carrega(){
var nome = document.getElementById('CodigoUtente').value;
var nomes = document.getElementById('Nome').value;
var url_="conexao4?CodigoUtente="+nome+"&Nome="+nomes;
http.open("GET",url_,true);
http.onreadystatechange=function(){
if(http.readyState==4){
var retorno = JSON.parse(http.responseText);
document.getElementById('CodigoUtente').value = retorno.CodigoUtente;
document.getElementById('Nome').value = retorno.Nome;
document.getElementById('DataNasc').value = retorno.DataNasc;
document.getElementById('Sexo').value = retorno.Sexo;
document.getElementById('Estadocivil').value = retorno.Estadocivil;
document.getElementById('Nacionalidade').value = retorno.Nacionalidade;
document.getElementById('Responsavel').value = retorno.Responsavel;
document.getElementById('Parentesco').value = retorno.Parentesco;
document.getElementById('Contato').value = retorno.Contato;
}
}
http.send(null);
}
in the connection page4 I have the php that receives the variables:
$CodigoUtente = $_GET['CodigoUtente'];
$Nome = $_GET['Nome'];
if((isset($CodigoUtente)) && (isset($Nome))){
$query= "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes WHERE (CodigoUtente = '$CodigoUtente') OR (Nome LIKE '%$Nome%')";
$resultados = $conn->query($query);
$json = array();
while ($rowResultados = $resultados->fetch_assoc()) {
$dados = array(
'CodigoUtente' => $rowResultados['CodigoUtente'],
'Nome' => $rowResultados['Nome'],
'DataNasc' => $rowResultados['DataNasc'],
'Sexo' => $rowResultados['Sexo'],
'Estadocivil' => $rowResultados['Estadocivil'],
'Nacionalidade' => $rowResultados['Nacionalidade'],
'Responsavel' => $rowResultados['Responsavel'],
'Parentesco' => $rowResultados['Parentesco'],
'Contato' => $rowResultados['Contato']
);
$json = $dados;
}
echo json_encode($json);
}
The problem is that they only work if you fill in the two inputs and intended that they return the data from the database only when filling one of them.
Curious_Mind was saying this way?
$where_caluse = array();
if(isset($_GET['CodigoUtente'])){
$where_caluse[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";
}
if(isset($_GET['Nome'])){
$where_caluse[] = "Nome = '".$_GET['Nome']."'";
}
$where = array_filter($where_caluse);
$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";
$resultados = $conn->query($query);
if(!empty($where)){
$final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
$query = "$query WHERE ". $final_where;
$json = array();
while ($rowResultados = $resultados->fetch_assoc()) {
$dados = array(
'CodigoUtente' => $rowResultados['CodigoUtente'],
'Nome' => $rowResultados['Nome'],
'DataNasc' => $rowResultados['DataNasc'],
'Sexo' => $rowResultados['Sexo'],
'Estadocivil' => $rowResultados['Estadocivil'],
'Nacionalidade' => $rowResultados['Nacionalidade'],
'Responsavel' => $rowResultados['Responsavel'],
'Parentesco' => $rowResultados['Parentesco'],
'Contato' => $rowResultados['Contato']
);
$json = $dados;
}
echo json_encode($json);
}
I tried to apply the form it said, but it is not working, it gives 500 error when I send the values of the variables.
Can you help fix the problem? I have a form to be populated with these values
$where = " where ";
$CodigoUtente = 'a';
$Nome = '';
if($CodigoUtente != '' && $Nome != '')
{
$where .= "CodigoUtente = '$CodigoUtente' OR Nome = '$Nome';";
}else if ($CodigoUtente != ''){
$where .= "CodigoUtente = '$CodigoUtente';";
}else{
$where .= " Nome = '$Nome';";
}
$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes".$where;
echo $query;
You can try like this way before making you sql query. This will help you to handle WHERE with OR condition, without OR condition and without any condition at all.
$where = array();
$_GET['CodigoUtente'] = 'Sany';
$_GET['Nome'] = 'Bruno';
if(isset($_GET['CodigoUtente'])){
$where[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";
}
if(isset($_GET['Nome'])){
$where[] = "Nome = '".$_GET['Nome']."'";
}
$sql = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";
if(!empty($where)){
$final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
$sql = "$sql WHERE ". $final_where;
}
echo $sql;
DEMO: https://3v4l.org/phZGW
I have the following code in one of api files(DispatchJob_Public) and i need ajax here to call the other file(selectDriverForJobResult) after 2 minutes. I can do that in php with sleep(), but that will keep the server busy. Ajax call is at the end of the php code. Can i embed js in api code? Or is there any alternate to do what i am trying to do.
Moreover i have got response from the first file(DispatchJob_Public), but no response from the second file(selectDriverForJobResult) when i called the endpoint in postman. Because the call wasn't made. If the second file was called, it should have return some response. The strange thing is that i get response from second file when i run it in browser. I think that is because the browser supports the javascript but the call made from android to the end point doesn't support that.
Please can i get any solution for this?
<?php
include_once ('connection.php');
include_once ('fcm_notification.php');
//error_reporting(E_ERROR | E_PARSE);
$user_id = $_REQUEST["user_id"];
$customer_name = $_REQUEST["customer_name"];
$group_id_fk = $_REQUEST["group_id_fk"];
$readynow_checkbox = $_REQUEST["readynow_checkbox"];
$job_points = '';
date_default_timezone_set('Australia/Melbourne');
$date = date('Y-m-d H:i:s');
if(strcasecmp($benefits_type, 'Points') == 0){
if(strcasecmp($fixed_price, '') == 0){
$fixed_price_new = $estimated_price;
}else{
$fixed_price_new = $fixed_price;
}
$sql_job_points = "SELECT `points` FROM `hg_job_points` WHERE '$fixed_price_new' BETWEEN `min_price` AND `max_price`";
$res_jobPoints = mysqli_query($conn, $sql_job_points);
$row_job_points = $res_jobPoints->fetch_assoc();
$job_points = $row_job_points["points"];
}
if(strcasecmp($commission_percent, 'Amount') != 0 && strcasecmp($fixed_price, '') != 0){
$commision_price = ($commission_percent / 100) * $fixed_price;
}
//insert job in job table
$sql = "INSERT INTO `hg_jobs`(`customer_name`, `pickup_address`, `dropoff_address`, `customer_phone`, `instruction`,
`via`, `user_id_fk`, `group_id_fk`, `pickup_time`, `flight_no`, `car_type`, `post_time`)
VALUES ('$customer_name', '$pickup_address', '$dropoff_address', '$customer_phone', '$instruction', '$via', '$user_id', '$group_id_fk',
'$pick_time', '$flight_no', '$car_type', '$date')";
if(mysqli_query($conn, $sql)){
//get job id from jobs table
$job_id = $conn->insert_id;
//insert new record in advance job table
$sql_adv = "INSERT INTO `hg_job_details`(`no_of_passenger`, `no_of_bags`, `child_seats`,
`car_type_specific`, `job_type`, `job_price`, `estimated_amount`, `payment_type`, `benefits_type`, `benefit_percent`,
`benefit_amount`, `job_points`, `ready_now_job`, `job_id_fk`)
VALUES ('$passenger','$bags','$child_seats','$car_type_specific','$job_type','$fixed_price', '$estimated_price',
'$payment_type','$benefits_type','$commission_percent','$commision_price', '$job_points', '$readynow_checkbox', '$job_id') ";
$res_adv = mysqli_query($conn, $sql_adv);
if($res_adv){
echo json_encode(Array('message' => 'job success'));
//get black list users
$sql_black = "SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id'";
$res_black = mysqli_query($conn,$sql_black);
//if specif type car is any
if(strcasecmp($car_type_specific, 'ANY') == 0){
if ($res_black->num_rows > 0) {
//get all fcm key and send notification (if blacklist table not empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type' AND u.user_id !=
(SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id') ";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}else{
//get all fcm key and send notification (if blacklist table empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}
}else{
//if specific car type
if ($res_black->num_rows > 0) {
//get all fcm key and send notification (if blacklist table not empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'
AND cd.car_type_specific = '$car_type_specific' AND u.user_id !=
(SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id') ";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}else{
//get all fcm key and send notification (if blacklist table empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'
AND cd.car_type_specific = '$car_type_specific'";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}
}
?>
<script>
function callDispatch()
{
nIntervId = window.setInterval(myCallback, 5000);
var baseUrl = document.location.origin;
function myCallback()
{
var user_id = '<?=$GLOBALS["user_id"];?>';
var job_id = '<?=$job_id;?>';
$.ajax({
url: baseUrl+'/android/selectDriverForJobResult.php',
type: 'POST',
dataType : 'json',
data: {'user_id': user_id, 'job_id': job_id} ,
success: function(response) {
clearInterval(nIntervId);
var resp = response.toString();
if (resp.includes('true') === true)
{
console.log('true'+ resp);
}
else
{
console.log(resp);
}
},
error: function(response)
{
console.log('Error in ajax'+response.statusText);
clearInterval(nIntervId);
}
});
}
}
callDispatch();
</script>
<?php
}
} else{
echo json_encode(Array('message' => 'error job post'));
}
$conn->close();
?>
I am learning tutorial, but I understand that the author made a mistake / mistakes.
The data is sent via GET in php and write, but do not turn back.
JavaScript:
function loadAllPost() {
var divs = $("#posts");
$.get("twitor.php?action=last", function() {
var posts = [];
for(var i = 0; i < posts.length; i++) {
var newPost = addNewPost(posts[i].name, posts[i].text, posts[i].date);
posts.push(newPost);
}
divs.children().remove();
divs.append(posts);
});
}
$(function() {
loadAllPost();
setInterval(loadAllPost, 5000);
$("#submit").click(function() {
var newPostName = $("#name").val();
var newPostText = $("#text").val();
var newPostDate = (new Date()).toLocaleString();
var newPost = addNewPost(newPostName, newPostText, newPostDate);
newPost.hide();
$("#posts").append(newPost);
newPost.slideToggle();
$("name").val("");
$("text").val("");
$.post("twitor.php?action=new", {
text: newPostText,
name: newPostName
});
});
});
Ie like php sends data, but does not have JS embeds them in HTML.
PHP:
if ($_GET['action'] == 'new') {
addNewPost();
}
elseif ($_GET['action'] == 'last') {
getLastPosts();
}
function getPDO(){
$db_host = "****";
$db_name = "****";
$db_user = "****";
$db_pass = "****";
$PDO = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
//$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
return $PDO;
}
function addNewPost(){
$params = [];
$params['name'] = $_POST['name'];
$params['text'] = htmlspecialchars($_POST['text']);
$PDO = getPDO();
$Statement = $PDO->prepare("INSERT INTO posts(`name`, `text`, `date`) VALUES (:name, :text, NOW());");
$Statement->execute($params);
}
function getLastPosts() {
$PDO = getPDO();
$Statement = $PDO->query("SELECT * FROM posts ORDER BY date DESC LIMIT 15");
if(!$Statement) return;
$posts = $Statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($posts);
}
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?