Getting data from a current HTML, PHP form using JavaScript - javascript

I have a HTML/PHP sale form which I take in all the details of a sale(products, price etc.).
When I "hold" the sale I then pass the id of the sale, using PHP like the following:
<button type="submit" class="btn btn-primary pull-right btnPrintOrder" saleCode="<?php echo $code; ?>" value="hold" name="openTable">Hold</button>
The desired end result is it is supposed to set off a function to print out the sale details to seperate printers(bar/restaurant).
The print function works as I have tested it against older sales already saved to the database.
My problem is it is not registering the details of the current sale and the receipts are blank.
I have tried to put a delay on it to see could it pick the details up after they have been saved to the database but I'm not having any luck.
The function the button passes to is:
$(".saleForm").on("click", ".btnPrintOrder", function(){
var saleCode = $(this).attr("saleCode");
// setTimeout(food(saleCode), 50000);
// setTimeout(drink(saleCode), 50000);
window.open('extensions/tcpdf/pdf/food_order.php?code='+saleCode);
window.open('extensions/tcpdf/pdf/drink_order.php?code='+saleCode);
})
And the PHP code calling the details in drink_order.php is:
public function getDrinkReceiptPrinting(){
// Sale Info
$itemSale = "code";
$saleValue = $this->code;
$saleAnswer = OpenTableController::ShowTableController($itemSale, $saleValue);
$saledate = substr($saleAnswer["date"],0,-8);
$products = json_decode($saleAnswer["products"], true);
$findCategory = 2;
$catProducts = array_filter($products, function ($product) use ($findCategory) {
return $product['category'] == $findCategory;
});
$netPrice = number_format($saleAnswer["netPrice"],2);
//User Info
$itemUser = "id";
$userValue = $saleAnswer["idSeller"];
$userAnswer = UserController::ShowUsersController($itemUser, $userValue);
Any ideas would be great.

Change the PHP button attribute to this:
<button type="submit" class="btn btn-primary pull-right btnPrintOrder" data-sale-code="<?php echo $code; ?>" value="hold" name="openTable">Hold</button>
use data attribute (dataset attribute), since saleData is not standard attribute, and inside jQuery use .data() to get the value (note how to get it in jQuery):
$(".saleForm").on("click", ".btnPrintOrder", function(){
var saleCode = $(this).data("sale-code");
// setTimeout(food(saleCode), 50000);
// setTimeout(drink(saleCode), 50000);
window.open('extensions/tcpdf/pdf/food_order.php?code='+saleCode);
window.open('extensions/tcpdf/pdf/drink_order.php?code='+saleCode);
})

Related

Use AJAX to run PHP script and then return single value

Okay, this question was closed for not being clear enough, so I'm going to completely re-write it in as clear a form as I can...
Project: Room Booking System
Required Function: Check the database for existing bookings matching a criteria, return the result of 'COUNT' SQL query to a textbox which another function then looks to.
The values which need to be inserted into the COUNT criteria are as follows:
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
</br>
Problem: I have a functioning php script which counts the number of rows in the database matching a criteria, which will then return the result to a textbox (main function sorted) when set up in a test directory with nothing else on the page. However, when I embed this php into an existing page (the new booking page) it doesn't work when the 'Check Availability' button is clicked. Instead, it reloads the page (as php does) which is not useful when users have already input their data for checking (and would need to re-enter it). I've Googled and have found that I need to use AJAX to run the php function in the background and then return the result to the textbox on the current page. I have never ever used AJAX and are only new to php, js etc. as it is, so I have no idea what I'm doing
How can you help: I need help in converting my existing code into a working solution to the above problem, probably using a combination of AJAX, PHP and JS functions.
Code:
PHP COUNT CODE (works)
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '2019-12-30' AND Time = 'Period 6' AND Room = 'C3'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
Area of php/html in which the result should be returned (id="availresult")
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
Test AJAX function, as suggested by an existing reply to my post
<script>
function soflow() {
$.post('checkAvailability.php', {info: 'start'}, function(data) { //if you don't need to send any data to the php file then you can set the value to whatever you want
document.getElementById('availResult').innerHTML = data;
});
}
</script>
I have tried various ways to do this myself, including modifying the suggested AJAX code above, but I'm not sure how to get my values from my various textbox over to the PHP function. Also, I don't know how to tell whether the AJAX function is running, or whether there is an error somewhere. At present, the value shown in my 'availresult' textbox does not change.
I appreciate any help with this, and thank anyone who has tried to help so far. I'm not sure how much clearer I can make this - please don't close the question again.
UPDATE:
(index.php):
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
<br/>
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
<script>
function soflow() {
var var_date = $('#datebox').val();
var var_time = $('#timebox').val();
var var_room = $('#roombox').val();
$.post('checkAvailability.php', {info: 'start', date: var_date, time: var_time, room: var_room}, function(data) {
document.getElementById('availResult').innerHTML = data;
});
}
</script>
</body>
</html>
(test.php):
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
if (mysqli_connect_errno()) { // Check connection
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = mysqli_real_escape_string($con, $_POST['date']);
$time = mysqli_real_escape_string($con, $_POST['time']);
$room = mysqli_real_escape_string($con, $_POST['room']);
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '$date' AND Time = '$time' AND Room = '$room'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
You could also do ajax with pure JavaScript, but this is simpler.
Also note that this is just an example on how to do an ajax connection in the first place.

not working form and form variable validation?

my form
<div class="input-holder">
<input type="text" class="search-input" id="string" placeholder="Искать" />
<button class="search-icon" onclick="searchToggle(this, event);"><i class="fas fa-search"></i></button>
</div>
api.php
case 'metafind': {
$string = $_GET['string'];
$list = mysqli_query($connect, "SELECT * FROM `sub_meta` WHERE `meta_key` = 'Название'&& `meta_value` ");
while ($item = mysqli_fetch_assoc($list)) {
if ($item['meta_value'] == $string) {
$id = $item['post_id'];
$arrr[] = array('post_id' => $item['post_id'], 'coords' => $find['meta_value']);
}
}
echo json_encode($arrr);
} break;
when you click on the form gives an error in the console:
(index):121 Uncaught ReferenceError: searchToggle is not defined
at HTMLButtonElement.onclick ((index):121)
it is necessary that when a word is entered into the form it was
searched for a name in the column meta_value by meta_key and then
displayed please help I'm new to php
You should try something like my below example :
1) I created textbox where i will write data then it will search in array and get the value from there where i have made array for example purpose and display the data in #div1
<div class="input-holder">
<input type="text" class="search-input" id="string" placeholder="Искать" />
<button class="search-icon"><i class="fas fa-search"></i>Go</button>
<div id="div1"> </div>
</div>
2) When button click we have to do ajax call then we will get data from there and get that data in response and we will show that response where we want to display
<script>
$(document).ready(function(){
$("button").click(function(){
var stringval = $("#string").val();
$.ajax({data: {val : stringval} , url: "democode.php", type: 'post', success:
function(result){
var data = JSON.parse(result);
console.log(data);
$("#div1").html(data);
}});
});
});
</script>
3) Ajax call on democode.php so in that file we will get data there(you can get data from database if you want) and we will return the data
==democode.php==
<?php
$test['data'] = array("Aleaxa"=>"I'm Beutiful","john"=>"I'm Evil","mishel"=>"baby, I'm Bad Boy!","mohini"=>"I'm MAstana");
if (array_key_exists( $_POST['val'], $test['data'])) {
$key = $_POST['val'];
echo json_encode($test['data'][$key]);
}
?>
So above example work like if i will search Aleaxa and click go button then it will give value of Aleaxa from array and output will be I'm Beutiful
Please checked my demo you will get idea how to do the code with your requirements

How to call a function in a php file using jquery load?

I am trying to display the data i retrieve from the database but it is not being displayed. I have a function in the file getComments.php called "getComments(page)" page is just a integer parameter to choose that database. and as you can see that i need to call this function to print the users comments. I am trying to use "load" but it is not being successful i just want to call this function to load the comments on the page. thank you in advance.
<?php
use TastyRecipes\Controller\SessionManager;
use TastyRecipes\Util\Util;
require_once '../../classes/TastyRecipes/Util/Util.php';
Util::init();
function getComments($page){
echo "<br><br>";
$controller = SessionManager::getController();
$controller->getComments($page);
SessionManager::setController($controller);
}
and in my web page where i want to display it using java script, i tried the following
<div class="page" id="comments">
<p class="style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br><br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type='hidden' id='uid' value = '".$_SESSION['u_uid']."'>
<input type='hidden' id='date' value = '".date('Y-m-d H:i:s')."'>
<textarea id='message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'submitCom'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";
}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML =
$("#comments").load("../extras/getComments.php", getComments(1));
});
});
</script>
Just change your click handler to this:
$("#load-comments").click(function(){
$("#comments").load("../extras/getComments.php", { page: 1 }); //i also added where the elements are loaded
});
and in getComments.php (if practical, otherwise you might need to create a new PHP file which calls the getComments() function and call that from the click handler instead) add something like:
if (isset($_POST['page'])) {
getComments($_POST['page']);
// do any other necessary stuff
exit;
}

Error while passing checkbox values to a Javascript function

I have a checkbox which stores values from database table. So it contains an array of values when I display them on my page.
<input type="checkbox" id="chkdelt[<?php echo $id; ?>]" name="chkdelt[]" value="<?php echo $id; ?>">
Above given is the checkbox code.
I have a popup block which shows the count of checked checkboxes.
<div class="popup">
Show count here <span id="numb"></span>
<button type="button" onclick="paz(<?php echo json_encode(chkdelt); ?>);">Click</button>
</div>
And I am able to show the count successfully using this javascript function given below.
// used to show number of checked checkboxes in popup
function dumpInArray(){
var arr = [];
$('.table-responsive input[type="checkbox"]:checked').each(function(){
arr.push($(this).val());
});
return arr.length; //returns no of checked check boxes
}
$('.select_chk').click(function () {
$('#numb').html(dumpInArray()); // output of dumpInArray() written into numb span
});
And I try to pass this array to a Javascript function while clicking the button inside of popup.
My Javascript is given below:
function paz(a)
{
var temp = new Array();
temp = JSON.parse(a);
for(i=0;i<temp.length;i++)
{
alert(temp[i]);
}
}
The values are not passed to paz() in Javascript. Rest works fine. I want to pass the values of all checked checkboxes to the paz() when I click the button in the popup div.
Thanks. Help???
You need to pass argument to JavaScript function as a string.
You're passing them as a variable which in turn will be becoming as undefined.
To pass argument as a string use function_name('arg') or function_name("arg").
So in your code change:
<button type="button" onclick="paz(<?php echo json_encode(chkdelt); ?>);">Click</button>
to
<button type="button" onclick="paz('<?php echo json_encode(chkdelt); ?>');">Click</button>
Also I'll suggest you to use <input type="button" /> Instead of <button> & I think if chkdelt is variable name in php you'll need to use $ sign before it and use json_encode($chkdelt).
Hope it'll help you.. Cheers :)!

onClick value + restartCode

<input type="button" onclick="restartBattle('Battle=Trainer&BattleID=294','nFOgYlQGjn')" value="Restart Battle" style="width:160px;">
That is the coding of the button. Unless the restart code is entered as well (it's dynamic, changes every refresh), I can't click the button with the methods of Javascript or jQuery that I've tried.
'nFOgYlQGjn' is the restartCode. I've tried this coding to click the button, but it won't work.
var btn = document.querySelector('input[value="Restart Battle"]');
if (btn) {
var x = Math.round((Math.random() * 90) + 663);
var y = Math.round((Math.random() * 15) + 589);
function restartBattle(url, restartCode) {
$('#battleContent').html('Loading...<br /><br />');
$('#battle').load('http://tpkrpg.net/core/battles/battle.php?'+url+'&RestartCode='+restartCode);
}
//btn.click();
}
This should work, since I took the function restartBattle part out of the source code, but it still won't work. Any ideas?
Pass the data as an object to the script. You could use on('click', method here) or click(method here) on the id of the input tag. Make sure jquery is included too.
button:
<input type="button" value="Restart Battle" id="restart" />
css:
#restart
{
width:160px;
}
jQuery:
/* sample how to get the values as variables
method one, static hard coded
var battleType = "Training";
var battleId = 294;
var restartCode = "nFOgYlQGjn";
method 2, php set via echo, requires page to be created by php, example uses theoretical data returned from a database stored as an associative array but could be changed for variables
var battleType = <?php echo $battle['training']; ?>;
var battleId = <?php echo $battle['id']; ?>;
var restartCode = <?php echo $battle['restart_code']; ?>;
*/
function restartBattle( varz )
{
$("#battleContent").html("Loading...<br /><br />");
$("#battle").load("http://tpkrpg.net/core/battles/battle.php", {Battle : varz.data.type, BattleId : varz.data.id, RestartCode : varz.data.code});
}
// handle the click of the button and execute functon with passed data.
$("#restart").on("click", { type : "Training", id : 294, code : "nFOgYlQGjn" }, restartBattle);
Your php code needs to check for this data being passed to it so it can return the data either some json, html, or plain text using echo.
battle.php:
$restartCode = ( ( isset( $_REQUEST['RestartCode'] ) ) ? $_REQUEST['RestartCode'] : false );
if( !$restartCode ) echo "Error : No restart code!";
That is a start, but you need to create variables that hold the data being sent to the php script or else it's hard coded to those values.
See method API

Categories

Resources