Problem: Multiple forms on the same page, but only the first one is being submitted.
Tried the following:
Equating the data-ids of submit button and Form inorder to submit the clicked form (No Luck)
Dynamic form creation using Javascript.(disbanded that idea after a few tries since it was on a deadline)
Usecase
The number of forms depends on the User. If there is just one comment from him, the form submits, while if there are say 4 forms, only the first one will submit.
Javascript:
$(function() {
$(".submit").click(function() {
var data_id = $(this).data('id');
var form_id = $(this.form).data('id');
if (parseInt(data_id, 10) == parseInt(form_id, 10)) {
var commentid = document.getElementByID('commentid');
alert(commentid + formid);
} else {
alert("10");
}
});
});
PHP code:
if($comment['Comment_Username'] ==$this->getUser()->getName())
{$output .='div class="panel" data-class="'.$comment['CommentID'].'">';
$output .='<form class="form" action="" method="post" data- id="'.$comment['CommentID'].'">';
$output .='<textarea name="edit_text' class="box" rows="2" cols="1">'.$this->getCommentText($comment['Comment_Text']).'</textarea>';
$output .='<input name="commentid" type="hidden" id="commentid" value="'.$comment['CommentID'].'"/>';
$output .='<input type="button' data-id="'.$comment['CommentID'].'" class="submit" value="submit"/>';
Any help would be greatly appreciated.
Thanks in advance
Wrong quote used here
$output .='<textarea name="edit_text" class="box" rows="2" cols="1">'.$this->getCommentText($comment['Comment_Text']).'</textarea>';
Related
This code works, but it shows the heading only for an instant, How we can execute an sql query as well as javascript function to change the innerHTML on a form submission.
//HTML
<div id='heading'> </div>
//form
<form method='post'>
<input type='submit name='option' value='option' onclick='myFunction()' >
</form>
//sql query
if(isset($_POST['option'])===true && empty($_POST['option']===true)){
$sql2= 'SELECT * from maptable ORDER by price';
$result = $mysql->query($sql2);
}
//javascript function
<script>
function myFunction(){
document.getElementById('heading').innerHTML ='OptionName';
}
</script>
<input type='submit name='option'
Look at your code here. You skip a quote It should be like this <input type='submit' name='option'
As I see your form submitting without AJAX, so once you click "submit" button, the page will be reloaded and return a result of PHP script execution.
If you want to run your "myFunction" before submitting you can do this:
<form id="myForm">
...
</form>
<input type='button' name='option' onclick="myFunction()">
And "myFunction":
function myFunction(){
document.getElementById('heading').innerHTML ='OptionName';
document.getElementById('myForm').submit();
}
OR, if you want the "heading" div to be shown some time, you can submit the form using timeout:
function myFunction() {
document.getElementById('heading').innerHTML = 'OptionName';
setTimeout(function() {
document.getElementById('myForm').submit();
}, <timeout of submitting in milliseconds>);
}
If my understanding is correct, You want to call the function before the PHP code is executed.
Just change onclick="myFunction()" to onsubmit= "return myFunction()".
It's also a good practice to surrond your document.getElemen.... with a try catch block.
The way you are executing this at the moment isn't going to work. You are posting directly to the same page with your form without AJAX which means the page refreshes. Since JavaScript is client side, it's not going to persist your heading's innerHTML that you set. There are a million and one ways to fix this.
The quickest way to "fix" this is declare what you want the heading to be in your PHP processing and then output that in the H1 element if it exists:
#PHP
if(isset($_POST['option'])===true && empty($_POST['option']===true)){
$sql2= 'SELECT * from maptable ORDER by price';
$result = $mysql->query($sql2);
// Depending on what you want your Heading to be
// $headingName = $_POST['option'];
$headingName = "OptionName";
}
Set your HTML heading like so:
<div id='heading'><?php echo isset($headingName) ? $headingName : '' ?></div>
Also, your input is missing a quotation, and with this change, you don't need the JavaScript portion anymore:
<input type='submit' name='option' value='option'>
I am designing an e-shop that allows profile registration. I need to have both Javascript & PHP validation for the registration form. (so when any of the fields are empty, I need to get a pop-up message that lets me know which specific field is empty + display on the screen beside the required field a visual message to advise the user where they need to correct the issue)
so far it is not working because my JS validation form activates onsubmit and my PHP is on action. I realize onsubmit activates before action and thus not allowing 'action' to go through.
I tried changing it from 'action' to 'onclick', but onsubmit also activates first and does not allow the PHP to work.
Here's my code for the form (I only included the first name portion so it won't get too long)
<form method="post" onclick="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="myForm" onsubmit="return validateForm()" style="border:1px solid #ccc">
<label><b>First Name</b></label>
<input type="text" name="firstName" placeholder="">
<?php echo $fnameErr;?>
<button type="submit" class="signupbtn" name="submit">Submit</button>
Here's my PHP code:
<?php
$fnameErr = "";
$fname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstName"])) {
$fnameErr = "Name is required";
}
else {
$fname = test_input($_POST["firstName"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I know the PHP code works, because if I delete the JS validation, it works as intended. I appreciate the help.
Please let me know if I need to add any extra information. Also, this hasn't been my first stop. I've been googling and trying to figure out how to fix this issue for hours to no avail...
This is the JS function being called (which also works as intended) this is also the shortened version to include only the name, the rest works the same, more if statements:
function validateForm() {
"use strict";
var fn = document.forms.myForm.firstName.value;
var ln = document.forms.myForm.lastName.value;
var em = document.forms.myForm.email.value;
var phone = document.forms.myForm.phone.value;
var pass = document.forms.myForm.psw.value;
var pass2 = document.forms.myForm.psw2.value;
if (fn === "") {
window.alert("First name must be filled out");
return false;
}
}
<input type="text" name="firstName" required>
You don't need any JavaScript.
Furthermore:
<form action="" method="post">
You don't need to specify the action if you're posting back to the current page. Using $_SERVER['PHP_SELF'] is potentially a vulnerability if you're not careful, and also breaks "pretty URLs" if you have them.
As said by #Niet The Dark Absol you can use the required but if you insist you can add e.preventdefault to prevent form from submitting in case of errors. We can elaborate properly if we can have a glimpse at your Javascript function.
You should change your onsubmit part and remove the onclick. Also your form is not valid as there is no action.
document.getElementById('myForm').addEventListener('submit',validateForm);
function validateForm(e) {
"use strict";
console.log(document.forms.myForm.firstName.value);
var fn = document.forms.myForm.firstName.value;
if (fn === "") {
window.alert("First name must be filled out");
e.preventDefault();
return false;
}
}
<form action="https://stackoverflow.com/" method="post" id="myForm">
<input type="text" name="firstName" >
<input type="submit">
</form>
There was a couple mistakes... But mainly what cause your problem is that onsubmit="return validateForm()". I also added e.preventDefault() it is to prevent the form submission if there is an error.
I've created a form using PHP in which the user has to click on a radio button before clicking on the button to submit the form. It looks as follows:
<form name="films" action="showing.php" method="post">
<table id="filmtable">
<tr><th>Title</th><th>Length</th><th>Description</th><th>Poster</th><th>Required</th></tr>
<?php
//Loop through every row returned by $result query to display it in table.
while ($newArray = mysql_fetch_array($result)){
$title = $newArray['title'];
$length = $newArray['length'];
$description = $newArray['description'];
$image = $newArray['image'];
//Echo statements will display query results on screen.
echo "<tr><td>$title</td><td>$length</td><td>$description</td>";
echo "<td><image src=\"$image\"</td>";
echo "<td><input type=\"radio\" id='wanted' name=\"wanted[]\" value='$title'></td></tr>";
}
// if (! array_key_exists($_POST['wanted[0]'], $result)){
// echo "Select it.";
//}
?>
</table>
<input type="submit" onsubmit = 'return validate()' value="Select Film">
</form>
As a validation measure I created the following in Javascript with the aim of preventing the user from submitting the form if they have not selected a radio button:
<script>
function validate(){
var radio = document.getElementById('wanted').checked;
if(radio=="")
{
alert("Please select a film to continue making a booking.");
return false;
}
return true;
}
</script>
The script prevents the user from submitting the form if no selection has been made from the radio boxes as intended. However, it will only allow the form to be submitted if the first radio box is selected. Selecting any button other than this one will cause the submit attempt to fail. What changes should I make to the JS to rectify this situation?
This PHP fetch loop attributes multiple times the same id="wanted" to many radio buttons.
An Id should be unique.... So it's a bad practice.
Remove the id and add a class instead:
echo "<td><input type=\"radio\" class=\"wanted[]\" name=\"wanted[]\" value='$title'></td></tr>";
Then, the use of jQuery saves pain...
Within your submit script:
if(!$('.wanted').prop("checked")){
alert("Please select a film to continue making a booking.");
return;
}
Add this jQuery lib call in your head:
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
EDIT - See comments
Function validate should be this:
function validate(){
var wantedChecked=$(".wanted:checked");
if (!wantedChecked.prop("checked")){
console.log("false");
return false;
}else{
console.log("true");
return true;
}
}
getElementById returns the first element matching the selector. If you just want to verify that any of them were checked, you could do something like:
var anyChecked = document.querySelectorAll('[name=wanted]:checked').length > 0;
I'm not sure if this is possible, or if I am doing it the wrong way?
I have a form that when submitted, should send the user to a URL depending on the input.
e.g If the users inputs '2', the URL should be books/itemView?id=2
I have created a var = id, which takes the search input box data. Is it possible to add this variable to my current form action? Perhaps there is a more efficient way?
My current code is as follows;
<form id="search" action="<?php echo URL; ?>books/itemView?id=" method="post">
<input type="text" name="search" id="demo"/>
<input type="submit" value="Submit">
</form>
My JS
$(document).ready(function(){
var id = $('#search').val();
});
Quite new to JS so any help appreciated.
JS should be
$('#search').on('submit', function() {
var id = $('#demo').val();
var formAction = $('#search').attr('action');
$('#search').attr('action', formAction + id);
});
If they enter 2 in the search input then your id will be appended to your url like:
url?search=2
So maybe you want to change the name of your search input to id or add another input field.
<form id="search" action="<?php echo URL; ?>books/itemView" method="post">
<input type="text" name="id" id="demo"/>
<input type="submit" value="Submit">
</form>
That should be all you need no jquery or javascript necessary.
When you submit it should result in:
books/itemView?id=2(or whatever is in the search/id input when you click submit)
Hmm, you can try with that:
$(document).ready(function(){
var $form = $('#search');
var id = $form.val();
var $search = $('#demo');
var originalAction = $search.attr('action');
$form.on('submit', function() {
$search.attr('action', originalAction + id);
});
});
Before submitting the form, jQuery's on('submit', handler) function executes the code in handler modifying the attribute action that you want.
originalAction variable stores the content of the action attribute that was partially generated in php, then you append your id dynamically created with js.
When I use JavaScript button with onClick function inside the form tag in frontend.php, it causes mistake. I need this simple application that does simple job, but it got stuck at this.
I provide you two links. First is within the form tag (frontend.php) and there it doesn't work - ADDMORE BUTTON SIMPLY DOESN'T ADD MORE TEXTAREAS! And the second link is without the form tag, and it works, you can try and submit which will leave you to the welldone.php page.
1.LINK - There is a problem
2.LINK - No form tag, no problem
HTML FORM
<form action="http://www.balkanex.info/dev/frontend.php" method="post">
Title: <br/><input type="text" name="title"><br/><br/>
The question is: <br/><input type="text" name="ask"><br/><br/>
<br/>
<input type="submit" name="submit" value="PROCEED"><br/>
</form>
FRONTEND.PHP FILE
<script>
am = 1;
function more(index) {
am++;
var textarea = document.createElement("textarea");
textarea.name = "answer" + am;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner1").appendChild(div);
}
</script>
<?php
echo '<form action="welldone.php" method="post">';
$content = "";
$title = $_POST['title'];
$question = $_POST['ask'];
if($_POST['ask'] != "") {
$answer = '<textarea name="answer1"></textarea>';
$more = '<button type="button" name="more" onClick="more();">Add more</button>';
$content .= '1) '.$question.'<br/>'.$answer.'<br/><div id="inner1"></div>'.$more.'<br/><br/>';
}
echo $content;
echo'<br/><input type="submit" value="CALCULATE"></form>';
?>
RESULTS WELLDONE.PHP FILE
<?php
echo 'WOW, WELL DONE';
?>
The problem is that, when you use more, browser is uses <button name="more"> instead of function more. Then, you get
TypeError: more is not a function
This behavior is only present in forms, that's why without forms your code works.
You can fix it doing one of these:
Changing function name
Changing button name
Writing unobtrusive javascript, adding the event handler from a <script> element instead ofthe inline onclick attribute.
Anyway, your code is completely invalid and in quirks mode. You should validate it and fix the errors.