how to save data on javascript form - php

I have those 2 function on JS :
<script>
function inc(elem)
{
elem.value++;
}
function dec(elem)
{
if(elem.value>1)
{
elem.value--;
}
}
</script>
And this form in html:
<form method="POST" action= "tameio.php" >
<input type="hidden" value="0" id="counter" name="counter">
<input type = "submit" value = "NextPage" name = "submit" onClick="inc(document.getElementById('counter')); ">
<input type = "submit" value = "PreviousPage" name = "submit" onClick="dec(document.getElementById('counter'));">
</form>
And here is the php :
<?php
if(isset($_POST['submit']))
{
echo $_POST['counter'];
if($_POST['submit'] == 'NextPage'){
...
}
}
?>
So the problem is that after i click NextPage button, 0 goes 1 but it is not stored in the form so it goes 0 again on html . If i reclick it it is going to send 1 again. Should I use ajax instead ?

There is no need to do any of that,
<form method="POST" action= "tameio.php" >
<input type="hidden" value="<?=$current_page?>" id="counter" name="counter">
<input type = "submit" value = "NextPage" name = "submit" onClick="inc(document.getElementById('counter')); ">
<input type = "submit" value = "PreviousPage" name = "submit" onClick="dec(document.getElementById('counter'));">
</form>
And in PHP:
<?php
if(isset($_POST['submit']))
{
if($_POST['submit'] == 'NextPage')
{
$current_page = $_POST['counter'] + 1;
} else {
$current_page = $_POST['counter'] - 1;
}
} else {
$current_page = 1;
}
// Fetch the page data based on the current page
...
?>>
But I would recommend you do this with a GET instead of a post.
Previous Page |
Next Page
And in PHP:
<?php
if(isset($_GET['page']) && $_GET['page'] > 0)
$current_page = (int) $_GET['page'];
else
$current_page = 1;

Try like this-
<script>
function inc(elem)
{
document.getElementById('counter').value = elem.value +1;
}
function dec(elem)
{
if(elem.value>1)
{
document.getElementById('counter').value = elem.value -1;
}
}
</script>

Related

how to make a button on a form work when clicked in php?

i have code like this
<body>
<form method = "POST">
<label for="">Star </label>
<input type="text" name = "star"></br>
<input type="submit" value= "Submit">
</form>
<?php
$Star = $Add = $Subs = NULL;
$Picture = "<img src = star.png>";
if($_SERVER['REQUEST_METHOD']=="POST"){
if(isset($_POST['star'])){
$Star = $_POST['star'];
for ($i=1; $i <= $Star + 1 ; $i++) {
echo "$Picture"; }
if(isset($_POST['Op'])){
$op = $_POST['Op'];
switch($op){
case 'ADD':
for ($i=1; $i <=$Star + 1 ; $i++) {
echo "$Picture";
}
case 'SUBS':
for ($i=1; $i <=$Star - 1 ; $i++) {
echo "$Picture";
}
}
}
}
?> <form method="POST">
<input type="submit" value="ADD" name = "Op"/>
<input type="submit" value="SUBS" name = "Op"/>
</form>
<?php } ?>
when I run it in the browser, the submit button works fine and displays a star image according to the input, but when the button is added and minus the star image doesn't increase and decrease. for example, if I input the number of 5 stars and I submit the program it works fine, after that when I click the add or subs button, the stars don't increase or decrease. sorry for my english
You have two forms in this code, first of all, combine both of them into a single form it looks way cleaner than this, and follow the below code it will help to achieve your task. ( Read comments in the code. )
<body>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>">
<label for="">Star </label>
<input type="text" name="star"></br>
<input type="submit" value="Submit" name="submit">
<input type="button" value="ADD" onclick="addNSub(this.value)" /> <!-- (this.value) will send the pressed button attribute value to the function -->
<input type="button" value="SUBS" onclick="addNSub(this.value)" />
</form>
<div id="starContainer">
<?php
$Star = $Add = $Subs = NULL;
$Picture = "<img src = 'star.png' class='starPng'>";
if (isset($_POST['submit'])) {
if (isset($_POST['star'])) {
$Star = $_POST['star'];
if (!empty($Star)) {
for ($i = 1; $i <= intval($Star); $i++) {
echo "$Picture";
}
}
}
}
?>
</div>
<script>
function addNSub(btnValue) {
const parentElement = document.getElementById("starContainer"); //get the star parent dive by it's id
const elements = document.querySelectorAll(".starPng"); //get all the star elements by it's class
if (btnValue == "ADD") { //if button value == ADD this code will execute
for (let i = 0; i <= elements.length; i++) {
if (elements.length == i) {
const getChild = elements[0]; //gets the first element (class ="starPng") under "starContainer" div
const cloneElement = getChild.cloneNode(true); // making clone of that element
parentElement.appendChild(cloneElement); //setting the clone to parent element ("starContainer" div)
}
}
} else if (btnValue == "SUBS") { //if button value == SUBS this code will execute
for (let i = 0; i <= elements.length; i++) {
if (elements.length == i) {
parentElement.removeChild(elements[0]); // removes the first HTML element (class ="starPng") under "starContainer" div
}
}
}
}
</script>
</body>

Populate datalist with mysql fields based on input from another field without reloading page

I am trying to set up a datalist tag that uses fields from my database based on the input from the first field on the form.
I am trying to use AJAX to send the value in the first field (Builder) into my PHP file which will run a query to pull all the records based on that value. Then it echos the options into the datalist for all the contactnames available under that Builder.
<form id="newsurveyform" method="post" action="submitnewsurvey.php">
ID: <input type="text" name="ID" readonly value=<?php print $auto_id; ?>>
Builder:<b style="color:red">*</b> <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
<datalist id="builders">
<?php
while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
echo'<option value="'.$builderinforow['Builder'].'">';
}
?>
</datalist>
Contact Name:
<input list="contactnames" name="contactnames" required>
<datalist id="contactnames">
<div id="contactnamesoptions"> </div>
</datalist>
</form>
<!-- AJAX, send builder value to php file-->
<script>
function findcontactnames(str) {
if (str.length==0){
document.getElementById("contactnames").innerHTML = "";
return;}
else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("contactnamesoptions").innerHTML = this.responseText;
}};
xmlhttp.open("POST", "contactnames.php", true)
xmlhttp.send(str);
}
}
</script>
<?php
include 'dbconnector.php';
$buildername = $_POST["Builder"];
$contactnames = $conn->query("SELECT ContactName FROM SurveyLog'.$buildername.'");
while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
echo'<option value="'.$contactnamerow['ContactName'].'">';
}
?>
Once the user enters the builder, they will click the contact name and it should be populated with all the contact names under that builder.
Right now, it is not populating anything into the contact name field.
In index.php
<form id="newsurveyform" method="post" action="submitnewsurvey.php">
ID: <input type="text" name="ID" readonly value=<?php print $auto_id ?? 0; ?>>
Builder:<b style="color:red">*</b> <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
<datalist id="builders">
<?php
while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
echo'<option value="'.$builderinforow['Builder'].'">';
}
?>
</datalist>
Contact Name:
<input list="contactnames" name="contactnames" required>
<datalist id="contactnames">
<div id="contactnamesoptions"> </div>
</datalist>
</form>
<!-- AJAX, send builder value to php file-->
<script>
function findcontactnames(str) {
if (str.length==0){
document.getElementById("contactnames").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this);
if (this.readyState == 4 && this.status == 200) {
alert('Fired');
document.getElementById("contactnamesoptions").innerHTML = this.responseText;
// document.getElementById("contactnamesoptions").innerHTML = "working";
}
};
xmlhttp.open("POST", "response.php", true)
xmlhttp.send(str);
}
}
</script>
in response.php
<?php echo "test"; ?>
Once you've verified that works, query the database
EDIT:
Now that you've verified that, query the database in response.php
include 'dbconnector.php';
$buildername = $_POST["Builder"];
$contactnames = $conn->query("SELECT ContactName FROM SurveyLog WHERE `columnName` LIKE '.$buildername.' LIMIT 100");
$queryHTML = '';
$result = 0;
while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
$result = 1;
$queryHTML .= '<option value="'.$contactnamerow['ContactName'].'">';
}
if ($result == 1) {
echo $queryHTML;
} else {
echo 'No Builders found';
}
Note: Change the columnName in the query to your real column name

php code for button counter

Am trying to run a php code which counts button clicks. It increments to 1 and then it doesn't count. here is my code:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
if(isset($_POST["button"])){
$counter++;
echo $counter;
}
}
?>
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = post>
<input type = "submit" name = "button" value = "vote" >
</form>
Am not a php expert so can anybody please tell me where am going wrong?
Thanks
Use this php:
<?php
if(isset($_POST["button"])){
$counter++;
echo counter;
}
?>
Also, use this for the opening <form> element
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Try this:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
if(isset($_POST["button"])){
$counter++;
echo $counter;
}
}
?>
<form action = "<?php echo $_SERVER["PHP_SELF"]; ?>" method = post>
<input type = "hidden" name = "counter" value = "<?php echo $counter; ?>" />
<input type = "submit" name = "button" value = "vote" />
</form>
Store the count in a session. Note that this stores a separate count for each user. If you want one single count that is shared between all users then you'll need to store it in a database.
<?php
// Start the session
session_start();
// Make sure a session variable exists
if ( !isset($_SESSION['count']) ) {
$_SESSION['count'] = 0;
}
// Check to see if a vote has been submitted
$vote = isset($_POST['button']) ? $_POST['button'] : false;
if ( $vote ) {
// Increment the vote
$_SESSION['count']++;
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<input type="submit" name="button" value="Vote">
</form>

Change value by JavaScript

The value of the button should change in 1 or 0, but the echo $_POST["ordina"] give always 1 and I don't understand because the code seems correct.
<script> function order() {
if (document.ordination.ordina.value == "1") {
document.ordination.ordina.value = "0";
} else {
document.ordination.ordina.value = "1";
} }</script>
<?php echo $_POST["ordina"]; ?>
<form id="ordination" name="ordination" method="POST" action="">
<button type="submit" value="1" class="button" name="ordina" onclick="order();return true;">Ordina</button>
The alert(document.ordination.ordina.value) give always 1.
Some can help me?
Check it now..
<script> function order() {
if (document.ordination.ordina.value == "1") {
alert(document.ordination.ordina.value); // this one shows 1
document.ordination.ordina.value = "0";
} else {
alert(document.ordination.ordina.value); // this one shows 0
document.ordination.ordina.value = "1";
} }</script>
<?php echo $_POST['ordina'];?>
<form id="ordination" name="ordination" method="POST" action="">
<button type="submit" value="<?php if(isset($_POST['ordina'])){echo $_POST['ordina'];}else{ echo '1';}?>" class="button" name="ordina" id="ordina" onclick="order();return true;">Ordina</button>
after you submit this form the <?php echo $_POST['ordina'];?> is 0...
and set to button value as 0 and again submit the value can be changed to 1.
and its consequently changed 0 to 1 to 0 to 1 but you have first time load this page means the alert shows 1 only..
This always return 1, because your button is a "submit" button, so the body is reloaded each time you click on the button.
<script>
function order() {
if (document.ordination.ordina.value == "1") {
document.ordination.ordina.value = "0";
} else {
document.ordination.ordina.value = "1";
}
alert(document.ordination.ordina.value);
}
</script>
<form id="ordination" name="ordination" method="POST" action="">
<button type="button" value="1" class="button" name="ordina" id="ordina" onclick="order();return true;">Ordina</button>
</form>
I change type "submit" for "button", then it works.
<script> function order() {
if ($("#ordina").val() == "1") {
$("#ordina").val(0);
} else {
$("#ordina").val(1);
} }</script>
<?php echo $_POST["ordina"]; ?>
<form id="ordination" name="ordination" method="POST" action="">
<button type="submit" value="1" class="button" name="ordina" id="ordina" onclick="order();return true;">Ordina</button>

jquery Post problem

I have a code in which i am sending the values from a form to php page where the query lies and for sending the values i am using $.post of jquery everything is going good. I am resulting a table and a button now i want that button will work and 1 of the table column has the radio button list so i want that button will take the radio id of that perticular row on click but my button is not working so please guide me how i can do this my code is here
my javascript function
function searchDetail(searchName) {
var textName = searchName + "Text";
var inputText = $('#' + textName).val();
var formName = searchName + "Form";
if (inputText === "") {
$('#' + textName).css("border", "2px solid red").fadeIn(4000);
}
else {
$('#' + textName).css("border", "1px solid #8dd7f6").show(2000);
$('#searchBox').fadeIn(1000);
$.post('../search/delete' + searchName + '.php', $('#' + formName).serialize(), function(result) {
$('#searchBox').html(result);
})
}
}
my php code
if ($count == "0") {
echo "There is no data with $search = ".$searchKeyword;
} else {
$color = 2;
echo "<table cellspacing='0px' cellpadding='7px'><thead><tr><th>#</th><th>book Id</th><th>book Name</th><th>book Writer</th><th>book Price</th><th>Availability</th></tr></thead><tbody>";
while ($row = mysqli_fetch_array($result)) {
$checkBook = $row['booktotal'] - $row['bookremain'];
if ($checkBook == 1) {
$status = "Yes";
} else {
$status = "No";
}
if ($color % 2 == 0) {
echo "<tr class='even'><td><input type=radio name=group1 value=".$row['bookId']."></td><td>".$row['bookId']."</td><td>".$row['bookName']."</td><td>".$row['bookWriter']."</td><td>".$row['bookPrice']."</td><td>".$status."</td></tr>";
$color = $color + 1;
} else {
echo "<tr class='odd'><td><input type=radio name=group1 value=".$row['bookId']."></td><td>".$row['bookId']."</td><td>".$row['bookName']."</td><td>".$row['bookWriter']."</td><td>".$row['bookPrice']."</td><td>".$status."</td></tr>";
$color = 2;
}
}
echo "</tbody></table><br><input type=button value=Delete id=deleteButton onclick='check()'> <script type=text/javascript> function check(){alert(Hello);}</script>";
mysqli_close($con);
}
?>
my html code
<body>
<div id="deleteFormTable">
<span id="headerFont">Enter Information to Delete Book</span><br><br>
<form id="bookSearchForm" name="bookSearchForm"><label>Search Book:</label> <input type="text" id="bookSearchText" name="bookSearchText"/>&nbsp<select id="bookSearchOption" name="bookSearchOption"><option id="bookSearchId">Id</option><option id="studentSearchName">Name</option></select> <input type="button" value="Search" id="bookSearch" name="bookSearch" onclick="searchDetail(this.id)"></form>
</div>
<div id="searchBox">
<center><div id="searchLoadBox"><img src="../images/loadings.gif" alt="..."></div></center>
</div>
</body>
OK, I think I know what you are asking.
You have a list of items with radio boxes next to them, once the user clicks one and then clicks the button, you want the "value" tied to that radio button.
If that is the case, you can use this to find the value of the "Checked" radio group.
$("#deleteButton").click(function()
{
var bookId = $("input[#name='group1']:checked").val();
}

Categories