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>");
Related
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 trying to pass two different values into an XMLHttpRequestObject.send but cannot seem to get the php script to read them both, it will only read the first value passed. How can I get the PHP to read both the values, here is the sample code:
HTML
<select id="mes" onchange="callCourseYards(this);">
<option>-</option>
</select>
Javascript
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function callCourseYards(selectObject){
if(XMLHttpRequestObject){
XMLHttpRequestObject.open("POST", "php/CourseChoiceTeeOff.php");
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function(){
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
var returnData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('tee');
messageDiv.innerHTML = returnData;
}
}
var data = selectObject.value;
var course = selectObject.value;
XMLHttpRequestObject.send("data=" + data + "course=" + course);
}
return false;
}
PHP
<?php
$pdo_dsn='localhost';
$dbname ='XXX';
$mysql_user='XXX';
$mysql_pass='XXX';
$db = mysqli_connect($pdo_dsn, $mysql_user, $mysql_pass, $dbname);
if(!$db){
print "Unable to connect to MySQL";
}
$myData = $_POST['data'];
$myData1 = $_POST['course'];
$sql_state = "SELECT * FROM ".$myData1." WHERE CourseCode = '".$myData."' ORDER BY CourseCode";
$result = mysqli_query($db, $sql_state);
$out = "";
$myrowcount = 0;
if(!$result){
$out = "Error";
}else{
$out = "<option>Selecciona un campo</option><br/ >";
$numresults = mysqli_num_rows($result);
for ($i = 0; $i < $numresults; $i++){
$row = mysqli_fetch_array($result);
$teeOff = $row['TeeOff'];
$out .= "<option id='".$myData."' value='".$teeOff."'> ".$teeOff."</option>";
}
$out .= "<br/ >";
}
print $out;
?>
I cannot seem to get the values through the XMLHttpRequestObject to go through into the PHP. I am not sure if its the syntax or how they should get past into the PHP.
I have tried using the & and the + symbols to concatenate both values, but I am not sure if this is possible. Does anyone know how I can fix this problem? I need both values to be able to do the mySQL search in the database.
Any help would be greatly appreciated. Thanks
I was trying to code where whenever I hit the submit button it will show an alert message when there's no data fetch. Can anyone help me?
if(isset($_POST['submitEstatus'])) {
if($_POST['empValue'] == $valEmp AND $_POST['ageValue'] == $valAge AND $_POST['genValue'] == $valGen){
$query = "SELECT * FROM users $valEmp $valAge $valGen";
$result = mysql_query($query);
if ($result = 0) {
$message = "No Data";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
while($row = mysql_fetch_array($result)){
$lat = $row['lat'];
$lon = $row['lon'];
$fname = $row['fname'];
$address = $row['address'];
echo("addMarker($lat, $lon, '<b>$fname</b><br />$address');\n");
$ageSelected = $valAge;
$empSelected = $valEmp;
$genSelected = $valGen;
}
}
}
I have this error:
mysql_fetch_array() expects parameter 1 to be resource, integer given
in C:\xampp\htdocs\admin\mapcon.php on line 20
On your if statement you are not comparing the value:
if ($result = 0) { ....
You are setting 0 to $result.
You should use
if ($result == 0) { ...
I created an array for town name, "Auckland" and "Hamilton", but the response from php is always empty, any idea?
UPDATE:
after debugging, I found that the problem is in php query
" where town = '$town' ", once i deleted this line, the rest works perfectly.
But I still can't figure out why :<
javascript:
var _addNewTowntoList = function(){
if (_request.readyState == 4) {
if (_request.status == 200) {
var data = JSON.parse(_request.responseText);
if(data.length == 0){
alert("No such town");
return;
}
var t = data[0].town;
var o = data[0].outlook;
var min = data[0].min_temp;
var max = data[0].max_temp;
var witem = new WLine(t,o,min,max);
console.log(t+" "+o+" "+min+" "+max);
_list.push(witem);
}
}
}
here is the php
$town = $POST_['town'];
$query = "Select * From weather WHERE town = '$town'";
$result = mysqli_query($conn, $query);
//create array for data
$data = array();
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
echo json_encode($data);
change this
$town = $POST_['town'];
> $query = "Select * From weather WHERE town = '$town'";
to
$town = $_POST['town'];
$query = "Select * From weather WHERE town = '".$town."'";
Remember to properly escape the query string
$town = mysqli_real_escape_strin($conn, $_POST['town']);
Because else your script is opened to SQL Injection attack
The other thing to mention here other than correct name for the $_POST is that you can use mysqli_fetch_all function to fetch all results at once and avoid the loop. For example
echo json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));
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?