I have a tip section that can be "custom" input from a customer. When the customer enters a value, I want to pass it to PHP for updating the order.
I'm unsuccessful and I'm thinking I'm approaching this problem the wrong way since I can't get it to work. What options are available to me without using AJAX?
The tip section:
<?= ($receipt['tip'] > 0 ?
'<tr id="tip-area"><th>Tip</th>
<td><textarea id="tip" name="update_tip" readonly>'. $receipt['tip'].'</textarea></td>
</tr>'
: '') ?>
My form which has different tip options:
<form method="post">
<tr>
<button title="20% Tip" type="submit" name="update_tip" id="update_tip" class="tip-button"
value="<?= ($_SESSION['order']['quote']['subtotal'] * 0.2); ?>">
<small>20%<br><?= number_format(($_SESSION['order']['quote']['subtotal'] * 0.2), 2) ?></small>
</button>
<button title="Edit Tip" type="button" name="update_tip" id="custom-tip" class="tip-button">
<small>Edit<br>Tip<br></small>
</button>
<button title="Save Tip" type="submit" id="save_tip" class="hidden">
<small>Save<br>Tip</small>
</button>
</tr>
</form>
My jQuery:
$('#custom-tip').click(function(){
$('#tip').removeAttr('readonly').focus();
$('.tip-button').addClass("hidden");
$('#save_tip').removeClass("hidden");
});
$('#save_tip').click(function (){
var tip = $('textarea#tip').val();
$('<input type="hidden" name="update_tip" value="' + tip + '">').submit();
});
$('#tip').focus(function(){
this.value = '';
});
When they press "Edit Tip", the readonly property is remove, the area comes into focus and value is cleared.
Then the user should enter a value and hit Save.
Then I'm trying to retrieve the value they entered.
I think this is what you want:
$("form").submit(function() {
$("<input>", {
type: "hidden",
name: "update_tip",
value: $("#tip").val()
}).appendTo($(this));
});
This will create the hidden input with the value from the textarea and append it to the current form when before the form is submitted.
You need to have PHP code on the same page (because your form does not specify an action) that handles the data. Use the 'name' attribute for your input to specify the key of the value you wish to access in the $_POST super global. For example, if I post a form with the following code:
<form method='POST'>
<input type='hidden' value='hello' name='world'>
<input type='submit' value='submit'>
</form>
Then in PHP, I can access the value of the element with the name "world" with the following code:
$_POST['world']
Use this syntax to acquire the data from the form and persist it/update it.
Related
I'm creating website project where you can edit a post after it has been published. I've a made the site with PHP, SQL and jQuery, and all posts that are published to the site gets outputted to the websites "feed" via a while-loop (not included in this questions content). All posts have a unique ID added to them when they are published (in the database).
The issue I now have is that the second form (post__edit) doesn't prompt at all.
I've figured out that I need to pass the id of a post inside an <input type="hidden" value="$postID"> field. This form below just prompts the actual post_edit form that is used to submit a post change.
echo '
<form method="post">
<button type="button" class="post__editBtn">Edit post</button>
<input type="hidden" name="post__editHidden" value="'.$postID.'">
</form>';
When the button class: post__editBtn gets clicked a jQuery click eventlistener is triggered that fades in the form (post_edit) that let's you make the changes to a post and submit them.
$('.post__editBtn').click(function() {
$('.post__edit').fadeIn();
});
Then what I have is a PHP if-statement that checks if the hidden value has been set. If it has then I echo out the previously hidden form, and assigns a SESSION variable to be used later on when doing the UPDATE query.
if(isset($_POST['post__editHidden'])) {
$_SESSION['post__editHidden'] = $_POST['post__editHidden'];
echo'
<form method="post" action="../../php/includes/updatePost.php" class="post__edit">
<input type="text" name="postTitle" placeholder="Edit title" required>
<textarea name="postMsg" maxlength="255" placeholder="Edit message" required></textarea>
<button type="submit">Edit Post</button>
<button class="post__edit-close">Close</button>
</form>';
}
To sumarize
The first form triggers the jQuery fadeIn effect for the correct post (with $postID)
The jQuery just fades in the second form (post__edit)
The second form (post__edit) takes the post__editHidden value (the correct ID for the correct post) and assigns it to a SESSION variable that can later be used to make the SQL UPDATE query, that runs when the second form is finally submitted (to updatePost.php).
I believe that because I have the first forms button set to type="button" it doesn't submit the form so isset($_POST['post__editHidden'] doesn't run. But if I change the button to a normal submit type then the first form is just summited and reloads the page which it's on. I could maybe just e.preventDefault in my jQuery fadeIn, but I don't know if that works.
I'm quite new to PHP and SQL so I might have it all wrong. Thanks anyways!
It's more of a suggested alternative than an answer.
The session variable usage would be more useful in other cases where we could obfuscate the ID value for example or reuse it in an orphan (disconnected) navigation level...
But in this case, I'd better use an only one form and fill it's input values using Ajax.
This Demo updates values only for postId' 32... It should work when it's used alongside a functional dynamic ajax handler that gets an Id and returns it's jSon object.
$('.post__editBtn').click(function() {
var myform = $('.post__edit');
var postId=$(this).attr('data-id');
myform.find("input[name='post__editHidden']" ).val(postId);
$.ajax({
type: "GET",
dataType: "json",
url: "https://api.myjson.com/bins/kx5xs", // replace with php later
data: {id: postId},
success: function(data) {
myform.find("input[name='postTitle']" ).val(data[0].title);
myform.find("textarea[name='postMsg']" ).val(data[0].content);
},
error : function(){
alert('Some error...!');
}
});
$('.post__edit').fadeIn();
//for demo puropose to show the new value in the update form:
console.log($(".post__edit input[name='post__editHidden']").val());
});
.post__edit{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class"post">
Post 30<button type="button" data-id="30" class="post__editBtn">Edit post</button>
</div>
<div class"post">
Post 32<button type="button" data-id="32" class="post__editBtn">Edit post</button>
</div>
<div class"post">
Post 37 <button type="button" data-id="37" class="post__editBtn">Edit post</button>
</div>
<!--all data-id values would be replaced with '.$postID.' in the php loop-->
<form method="post" action="../../php/includes/updatePost.php" class="post__edit">
<input type="text" name="postTitle" placeholder="Edit title" required>
<textarea name="postMsg" maxlength="255" placeholder="Edit message" required></textarea>
<button type="submit">Save Post</button>
<button class="post__edit-close">Close</button>
<input type="hidden" name="post__editHidden" value="">
</form>
And we add a file ex:ajax.php that we call with ajax where we get an ID, we do get that record from the database to return our json. Something like this :
<?php
$id=$_GET['id'];
$stmt = $conn->query("SELECT title,content * FROM posts WHERE postId=$id LIMIT 1");
$result=...
echo json_encode($result);
To get a jSon like this :
{"id": "32","title": "POst 32","content": "POst 32 talks about HiTECH"}
I have the following table dynamically generated using php and MySQL. The number of rows and number of buttons generated are dynamic.
<?php
if($resultCheck != 0){
while($result = mysqli_fetch_array($tableQueryExecute)){
$normalShiftDuration = $result['shift1Duration'];
?>
<tr> <form method="post" id="vtagViewTwo">
<td name=""><select class="form-control" name="normalShiftOa" id="normalShiftOa"><option>1</option></select></td>
<td>
<input type="submit" class="btn btn-primary" name="editButton" id="editButton" value="Save">
</td>
</form></tr>
<?php
}
}
?>
I want to get value of the <td> which is normalShiftOa value with the button click using jQuery click event as below.
$("#editButton").click(function(){
alert("Clicked");
});
But since there are many button generating for each row with the same id, I am not able to do it. Does anyone know how to do it? I am able to do it using php $_POST['editButton'] method. But I want to do it using jQuery.
Edit 1
I changed the id editButton to class and tried the following. But it is not working
$(".editButton").click(function(){
alert($(this).$("#normalShiftOa").val());
});
Instead of using ids, use class editButton. Then, if you want to get the value of the select, use jQuery like shown below:
$(".editButton").click(function(){
let tdValue = $(this).closest("form").find("select").val();
});
Edit: Code snippet that works.
$(".editButton").click(function(event){
let tdValue = $(this).closest("form").find("select").val();
alert(tdValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr> <form method="post" id="vtagViewTwo">
<td name=""><select class="form-control" name="normalShiftOa" id="normalShiftOa"><option>1</option></select></td>
<td>
<input type="submit" class="editButton btn btn-primary" name="editButton" id="editButton" value="Save">
</td>
</form></tr>
For a project, I need to generate a dynamic html form that will send POST info to a PHP page via the ACTION field.
The form has not to be static, it has to be dynamic so the user has to be able to generate(ADD) a not fixed(dynamic) number of input tags, then when all the inputs are generated and filled the user may click on submit button and send all the info to a php document via post.
I'm completely lost
I've been playing with this piece of code that generates the inputs but I'm not able to send the data via post to the php file
<script>
var choices=[];
choices[0]="one";
choices[1]="two";
function addInput(divName){
var newDiv=document.createElement('div');
newDiv.innerHTML="<input type='text'>";
newDiv.innerHTML=newDiv.innerHTML+"</input>";
document.getElementById(divName).appendChild(newDiv);
}
</script>
<form class="new" method="post" action="action.php">
<div id="dynamicInput">
</div>
<input type="button" value="Add" onclick="addInput('dynamicInput');" />
<input type="button" value="Save" />
</form>
To submit the form, one possible scenario is to change the type of Save button to submit:
<input type="submit" value="Save" />
Also add name property to your auto generated inputs. Otherwise you won't access the submitted $_POST data:
<input name="enter_name[]" type='text'>
As you see, I'm concatenating [] to the input field. That will convert all submitted data into an array. Otherwise, that last one auto generated input will overwrite the previous entered data.
just change your input type to submit instead of save
<input type="submit" value="Save" />
and you don't need to create new div each time to create an input you can either append it to the div you already have
document.getElementById(divName).innerHTML+= "<input type='text' name= 'added_input[]'/>";
or
var newInput=document.createElement('input');
// if you want each input in separate lines
newInput.style.display = "block";
newInput.setAttribute("name","added_input[]");
document.getElementById(divName).appendChild(newInput);
and in your php file you can get post values like this :
for ($i = 0; $i < $_POST['added_input']; $i++){
echo $_POST['added_input'][$i];
}
for more option to get post values see This Question
As the title says This is the code that I tried with. The forms must appear one by one because information from previous forms determine how the next ones will look.
$(document).ready(function(){
$('#first_form').submit(function(){
$('#first_form').fadeOut('fast');
$('#second_form').fadeIn('fast');
});
});
<form action="new_patch.php" method="POST" id="first_form">
Title: <input type="text" name="patch" placeholder="Patch 4.20">
<br/>
Number of Champions: <input type="number" name="champ_number" min="1" max="99">
<br/>
<input type="submit" value="submit">
</form>
<form action="new_patch.php" method="POST" id="second_form" style="display: none;" >
<input type="text" value="text">
<input type="submit" value="submit">
<?php
$champ_number = null;
if(isset($_POST['champ_number']))
{
$champ_number = $_POST['champ_number'];
for($champ_number;$champ_number>0;$champ_number--)
{
echo "<br/>Champion ".$champ_number."<input type=\"number\" name=".$champ_number." min=\"1\" max=\"99\">";
}
}
?>
</form>
You're mixing client-side and server-side form code. Submitting the form will reload the page entirely, so from the looks of your code it will fade in the new form when the old form is submitted, but then reload the page so the old form will show again anyway.
You could either:
Let the PHP determine how the next form appears based on the submission of the first form, e.g. if (isset($_POST["First_form_submit"]) { Show second form... }
Probably better and more user-friendly: make the second form appear below once the user has filled in the relevant inputs on the first form before they've submitted
you can use:
$('#first_form').submit(function(){
$('#first_form').fadeOut(function() {
$('#second_form').fadeIn('fast');
});
return false;
});
From the jQuery documentation the syntax is fadeIn( [duration ] [, complete ] ) it accepts a duration and a onComplete callback that you can use to execute the next action when the first is completed.
I did this once too, just add a submit class to the button and make it like this:
<input type="submit" value="submit" class="submit">
Change script to a click function.
$(document).ready(function(event){
event.preventDefault();
$('.submit').click(function(){
$('#first_form').fadeOut(400);
$('#second_form').fadeIn(400);
});
});
PS, also you need to prevent submit default...otherwise it will just submit the form, see this JSfiddle
I have a list of names and some buttons with product names. When one of the buttons is clicked the information of the list is sent to a PHP script, but I can't hit the submit button to send its value. How is it done?
I boiled my code down to the following:
The sending page:
<html>
<form action="buy.php" method="post">
<select name="name">
<option>John</option>
<option>Henry</option>
<select>
<input id='submit' type='submit' name='Tea' value='Tea'>
<input id='submit' type='submit' name='Coffee' value='Coffee'>
</form>
</html>
The receiving page: buy.php
<?php
$name = $_POST['name'];
$purchase = $_POST['submit'];
//here some SQL database magic happens
?>
Everything except sending the submit button value works flawlessly.
The button names are not submit, so the php $_POST['submit'] value is not set. As in isset($_POST['submit']) evaluates to false.
<html>
<form action="" method="post">
<input type="hidden" name="action" value="submit" />
<select name="name">
<option>John</option>
<option>Henry</option>
<select>
<!--
make sure all html elements that have an ID are unique and name the buttons submit
-->
<input id="tea-submit" type="submit" name="submit" value="Tea">
<input id="coffee-submit" type="submit" name="submit" value="Coffee">
</form>
</html>
<?php
if (isset($_POST['action'])) {
echo '<br />The ' . $_POST['submit'] . ' submit button was pressed<br />';
}
?>
Use this instead:
<input id='tea-submit' type='submit' name = 'submit' value = 'Tea'>
<input id='coffee-submit' type='submit' name = 'submit' value = 'Coffee'>
The initial post mentioned buttons. You can also replace the input tags with buttons.
<button type="submit" name="product" value="Tea">Tea</button>
<button type="submit" name="product" value="Coffee">Coffee</button>
The name and value attributes are required to submit the value when the form is submitted (the id attribute is not necessary in this case). The attribute type=submit specifies that clicking on this button causes the form to be submitted.
When the server is handling the submitted form, $_POST['product'] will contain the value "Tea" or "Coffee" depending on which button was clicked.
If you want you can also require the user to confirm before submitting the form (useful when you are implementing a delete button for example).
<button type="submit" name="product" value="Tea" onclick="return confirm('Are you sure you want tea?');">Tea</button>
<button type="submit" name="product" value="Coffee" onclick="return confirm('Are you sure you want coffee?');">Coffee</button>
To start, using the same ID twice is not a good idea. ID's should be unique, if you need to style elements you should use a class to apply CSS instead.
At last, you defined the name of your submit button as Tea and Coffee, but in your PHP you are using submit as index. your index should have been $_POST['Tea'] for example. that would require you to check for it being set as it only sends one , you can do that with isset().
Buy anyway , user4035 just beat me to it , his code will "fix" this for you.
Like the others said, you probably missunderstood the idea of a unique id. All I have to add is, that I do not like the idea of using "value" as the identifying property here, as it may change over time (i.e. if you want to provide multiple languages).
<input id='submit_tea' type='submit' name = 'submit_tea' value = 'Tea' />
<input id='submit_coffee' type='submit' name = 'submit_coffee' value = 'Coffee' />
and in your php script
if( array_key_exists( 'submit_tea', $_POST ) )
{
// handle tea
}
if( array_key_exists( 'submit_coffee', $_POST ) )
{
// handle coffee
}
Additionally, you can add something like if( 'POST' == $_SERVER[ 'REQUEST_METHOD' ] ) if you want to check if data was acctually posted.
You can maintain your html as it is but use this php code
<?php
$name = $_POST['name'];
$purchase1 = $_POST['Tea'];
$purchase2 =$_POST['Coffee'];
?>
You could use something like this to give your button a value:
<?php
if (isset($_POST['submit'])) {
$aSubmitVal = array_keys($_POST['submit'])[0];
echo 'The button value is: ' . $aSubmitVal;
}
?>
<form action="/" method="post">
<input id="someId" type="submit" name="submit[SomeValue]" value="Button name">
</form>
This will give you the string "SomeValue" as a result
https://i.imgur.com/28gr7Uy.gif