dropdown on change submit not executing php code - javascript

I have a form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
the form has multipe input type text and 1 dropdown menu.
I also have a submit button called (submit1)
<input class="submit-button" type="submit" name="submit1" value="UPDATE MY INFORMATION" />
My PHP read like this :
if (isset($_POST['submit1']))
{ .... }
If I press the button, it works, no problem.
BUT I also want to submit the form from the dropdown menu change... so it can be executed by both the press of the button OR the change in dropdown... so I have the following for my dropdown
<select name="country" onchange="this.form.submit()">
when I select my dropdown, the page refreshed, but the code in my PHP is not executed... I figured it has to do with the name of $_POST['submit1']...
How can I change onchange="this.form.submit() for it to execute the code in if(isset($_POST['submit1']))...
Thank you

You should avoid inline javascript like that. It's ugly, and reduces readability. The easier way would be to give your elements IDs, like so:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" id="myForm">
But if you don't want to, you can use QuerySelector and grab the name attribute of your input.
var x = document.querySelector("[name='country']");
x.addEventListener("change",function() {
this.parentNode.submit(); //get form parent and submit
});
I'm a bit confused why you're checking the submit button for a value as well, wouldn't you want:
if (isset($_POST['country'])) { ... }
Instead?

You could just document.getElementById('submit1').click() after setting the id on your submit button the same as its name. Of course, you would also do this onchange. I would separate my JavaScript from HTML, so it's cached into your Browser memory. Give your inputs, selects and the like the same id as their name, with the exception of radio buttons, and possibly checkboxes.
Let's start with some common.js:
//<![CDATA[
var doc = document, bod = doc.body;
var IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function gteIE(version, className){
if(IE >= version)bod.className = className;
}
function E(e){
return doc.getElementById(e);
}
//]]>
Now for your otherpage.php:
//<![CDATA[
var cntry = E('country'), sub1 = E('submit1');
cntry.onchange = function(){
sub1.click();
}
// note that the format E('submit1').click(); would also work
//]]>
Of course, you should have:
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='otherpage.js'></script>
</body>
</html>

Check for isset($_POST['country'])
And onchange add this to the drop-down,
onchange= 'document.getElementsByName("submit1")[0].click();'

Related

Can't get input validation Javascript to work

Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.

trying to hide "download" button once clicked

I have a simple form only consisting of a button that is used to download a file. here is the code :
<form method='post' action='download.php?file=file.txt' name='form1'>
<button type='submit'>Telecharger</button>
</form>
Download.php is a small php file with header used to engage download, here it is :
<?php
$filename=$_GET['file'];
header('Content-Type: text/plain');
header("Content-disposition: attachment;filename=$filename");
readfile($filename);
?>
What I'm trying to do is hide the button or the form after the user clicked on it. So far I have tried toying with css and javascript listener but nothing worked so far.
When I click on the button it download the file but doesn't hide the button.
How can I hide the button after submiting the form ?
You can use Javascript:
<form method='post' action='download.php?file=file.txt' name='form1'>
<button onClick='this.style.display = "none";' type='submit'>Telecharger</button>
</form>
This will hide your button when it's clicked. Here is a fiddle.
Sth like this?
document.getElementById("downloader").addEventListener('click', function() {
this.style = "display: none;"
});
<div>
<button type='submit' id="downloader">Telecharger</button>
</div>
You should give your button at the very least a class like so,
<button class="button-toggle" type='submit'>Telecharger</button>
and you can use vanilla js to select and hide it,
document.getElementByClassName("test").addEventListener("click", function( event ) {
event.target.style.visibility = "hidden";
}, false);
or if you're using jQuery
$('.button-toggle').click(function() {
$(this).hide();
});
Should get you close.
The following should work.
<form method='post' action="javascript:alert('Hello there, I am being submitted');" name='form1' id="form">
<button type='submit' id="hide">Telecharger</button>
</form>
<script type="text/javascript">
var button = document.getElementById("hide");
button.addEventListener("click", function(event){
button.style.display = "none";
});
</script>
I changed the action of the form just to check what was happening, but you can replace that with your action path.

jQuery.get to read a file and use the data into a form

I want the script to do the following:
On page load, read a text file with a number (just one line)
Increment the number by 1
Insert the number in an <input> box of the form
Once <form> is submitted, write the number to the text file
When the form gets loaded again, it will rerun the code and the number will increment by 1. This is basically to pre-populate a field with a unique and progressive number prior to form submission.
I am currently using jQuery, PHP and of course HTML:
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js">
$.get("http://www.domain.com/tools/formdata.txt");
function test(){
$.get('http://www.domain.com/tools/formdata.txt', function(data){
x = data++;
});
}
</script>
</head>
<body onload="test()"/>
<form action="save_json.php" method="post">
Contract: <input type="number" name="contract" id="contract" value="x" /><br />
<input type="submit" id="submit" value="Invia" />
</form>
</body>
</html>
PHP
<?php
if(isset($_POST['contract'])) {
// if form fields are empty, outputs message, else, gets their data
if(empty($_POST['contract'])) {
echo 'All fields are required';
}
else {
// adds form data into an array
$formdata = $_POST['contract'];
if(file_put_contents('/var/www/domain/tools/formdata.txt', $formdata)) echo 'Data successfully saved';
else echo 'Unable to save data, try again or contact IT';
}
}
else echo 'Form fields not submitted';
?>
First: I recommend that instead of javascript, you do this with PHP file_get_contents('formdata.txt') at the start of your file, and then you echo it in. That way, the value will be there on load, rather than having to wait for the HTML to render and the javascript to run. Also, it is a much better practice and will let you do a lot more things if you choose to expand the page.
However, here's the solution to the issue presented:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
var x;
function test(){
$.get('file.txt', function(data){
console.log('data',data);
var x = ++data;
console.log('x',x);
$('#contract').val(x);
});
}
</script>
</head>
<body onload="test()"/>
<form action="aoeu.php" method="post">
Contract: <input type="number" name="contract" id="contract" /><br />
<input type="submit" id="submit" value="Invia" />
</form>
</body>
</html>
The things to note:
Close off your <script> tag including the jquery library, then open another one after it.
No need to do the first $.get() you have - save it for the function.
var x = data++; - this increments data AFTER its value has been assigned to x. So, it will never increase. Do ++data instead, and it increments before.
You need to place it somewhere afterwards. How you had the input (value='x') is just trying to put the character "x" into the input. Use javascript to edit the functions value, as in my example.
Your PHP works fine.

form fields not passing through when submit is done via javascript

I can't seem to figure out why this is happening. Any help would be appreciated. I have an html form with two fields. When I run the page and submit the form with a submit button, the field values pass through ok. But if I run the same page and submit with javascript as I show here, the receiving file shows null values for both x and y.
Source File:
<html>
<head>
<script>
document.invoice.x.value = "1";
document.invoice.y.value = "2";
</script>
</head>
<body>
<form method="post" name="invoice" id="invoice" action="process_payment.php">
X: <input type="text" name="x"> Y: <input type="text" name="y">
<script>document.forms["invoice"].submit();</script>
</form>
</body>
</html>
Target File (process_payment.php):
<?php
session_start();
print "<pre>"; print_r($_POST); print("</pre>");
?>
Output I am getting:
Array
(
[x] =>
[y] =>
)
you can set your value in javascript like this:
document.getElementsByName("x").value="1";
document.getElementsByName("y").value="2";
and to submit the form use:
document.forms["invoice"].submit();
Please check this
Use below BEFORE body Close tag check This
<script>
document.invoice.x.value = "1";
document.invoice.y.value = "2";
</script>
OR use jQuery
<script>
$("[name='x']").val("1");
$("[name='y']").val("2");
</script>

Javascript: Need to proceed to another page

I'm using Javascript for deleting a record. But my problem is, when I click the image button its not redirecting to the page I want instead it will remain on the page...
Here's my code:
echo "<button type='submit' name='deletePlaylist[]' value='" . $row['id']."' onClick='myFunction()' style='border: 0; background: transparent; cursor: pointer;'><img src='image/delete.png' /></button> ";
I'm using the button because I'm using an image if I used the input its not working... So I decided to use button
Here's my code in my javascript:
function myFunction()
{
var Xcancel;
var Rokay=confirm("Are you sure you want to delete?");
if (Rokay==true)
{
window.location = 'delete.php';
}
else
{
Xcancel="You pressed Cancel!";
}
}
</script>
I already tried the window.navigate("delete.php"); or the window.location.href='delete.php' also not working...
The confirmation message is displaying already but my main problem its not going to the delete.php where in that form is my deleting function...
NOTE:
The button is under of the <form name='form' method='post' action="">, the delete.php is in the same folder... Before there is no confirmation message and its going to the delete.php but now I tried to insert a confirmation message then its not going to the delete.php... The form action is empty because I have a click able dropdown list where it will proceed to the result.php
Here's the code for my dropdown list:
<select id="year"name="year"onChange="this.form.action='booking_delete_two.php'; this.form.submit()">
<option value="2013" <?php if($get_year=='2013') echo "selected"?>>2013</option>
<option value="2014" <?php if($get_year=='2014') echo "selected"?>>2014</option>
</select>
<select name="id" onChange="this.form.action='booking_delete_three.php'this.form.submit()">
<option value="<?php echo $get_ID; ?>"><?php echo $get_ID; ?></option>
<?php
$q = mysql_query("select * from tblnetwork");
while ($row1 = mysql_fetch_array($q))
{
if($get_ID != $row1[fldNetname])
{
echo "<option value='".$row1[fldNetname]."'>".$row1[fldNetname]."</option>";$get_netname = $row1[fldNetname];
}
}
?>
</select>
As you can see I empty the action because I have a three different pages where it will proceed....
a. booking_delete_two
b. booking_delete_three.
c. delete...
Thank you in advance,!
Make these changes to your script:
function myFunction(evt)
{
evt.preventDefault(); // this will keep the page from submitting and aloow the rest of the script to run
var Xcancel;
var Rokay=confirm("Are you sure you want to delete?");
if (Rokay==true)
{
window.location = 'delete.php';
}
else
{
Xcancel="You pressed Cancel!";
}
}
The form is being submitted to its default action. You need to prevent this submission. Just append onsubmit = "return false" to your form. This will prevent the form from submission.
<form name='form' method='post' action="" onsubmit="return false;">
I would be correcting how forms are meant to be validated instead of making work arounds.You best bet is to follow the same practice as what W3schools sets out below:
http://www.w3schools.com/js/js_form_validation.asp
So it should look like:
<form name="form" action="" onsubmit="return myFunction()">
<button type="submit" name="deletePlaylist[]" value="' . $row['id'].'" style="border: 0; background: transparent; cursor: pointer;">
<img src="image/delete.png" />
</button>
</form>
EDIT:
myFunction() could then look like below:
function myFunction()
{
var Xcancel;
var Rokay=confirm("Are you sure you want to delete?");
if(Rokay == false){
Xcancel="You pressed Cancel!";
}
return Rokay;
}
EDIT2: Added to 'myFunction()' a dynamic way of assigning the form action :p You can leave the original action attribute blank or have it as a default.
EDIT3: Seeing your drop down code I returned my answer to something like it was originally. Test it out.

Categories

Resources