PHP :unable to check if a form is submitted - javascript

I am using a form in php file inside a modal window like this
<div class="modal-body">
<form method="post" action="m.php">
<div class="form-group">
<lable>Name</lable>
<input type="text" class="form-control" required="required">
</div>
<div class="form-group">
<lable>Email</lable>
<input type="text" class="form-control" required>
</div>
<div class="form-group">
<lable>Details</lable>
<input type="text" class="form-control" required>
</div>
<div class="form-group">
<lable>Message</lable>
<textarea name="" id="" class="form-control"></textarea>
</div>
<div class="form-group">
Submit
</div>
</form>
</div>
file name is m.php now when i press the submit button it doesn't detect form submission
<?php
if( ($_SERVER['REQUEST_METHOD'] == 'POST')){
die("form submitted");
}
?>
i tried $_POST['submit'] as well kindly help me whats wrong with it

This is because you dont press a submit button, you press a link called submit. Try replacing it with <input type="submit" value="Submit" />.
Also, your check wether your form has been submitted uses a dangerous method. If you have multiple forms to be handled in your code, it will catch them all. A better approach would be:
if( isset($_POST['nameOfSubmitbutton']) ){}
// because you can now easily do:
if( isset($_POST['completelyDifferentButton']) ){}
If you want to keep the anchor (I advice against it), you can use javascript to fake the submit for you:
document.getElementById('yourAnchor').onclick = function(){
document.getElementById('yourForm').submit();
}
// Or if you have jQuery:
$('#yourAnchor').on('click', function(e){
e.preventDefault();
$(this).closest('form').submit();
});

The submit button you are using is pointing towards the same url, can you try something like?
<input class="btn btn-default" type="submit" value="Submit">
and then try to see if the form is submitted from PHP.
And i also would recommend that you use some framework for this to handle sql injections and/or other exploits.

Wrong use of form submit.
<div class="form-group">
Submit
</div>
You should use it like:-
<div class="form-group">
<input type="submit" class="btn btn-default" name="submit" style="background: #eee; width:100px;display: block;margin-left:auto;" value="Submit"/>
</div>
Hopefully this will solve the issue.

Related

Submit form on enter press

Rookie question. I have a simple form with an input box and a submit button. When the button is clicked it triggers some php to search for the input term & output any results. I want to be able to press enter after typing my search term, rather than having to click the button.
I'm aware this is a basic thing and I've found solutions on here but when I've tried to add a keyup event listener to my code it doesn't seem to change anything and I'm not clear why - with or without the js pressing enter seems to refresh the page? I'm guessing that the problem is I don't want to "submit" the form, I want to do something else?
Here is the code:
<?php
if (isset($_POST['submit'])) {
*Removed the search php because I assume it is not relevant to the question*
?>
<div class="site-section bg-dark" id="start">
<div style="padding-left: 20px">
<h3 class="text-white">Find book based on title</h3>
<div class="col-md-6">
<div class=" mb-4">
<div class="form-group">
<form method="post">
<label for="title">Title</label>
<input type="text" id="title" name="title" class="form-control" placeholder="Title">
<p></p>
<button class="btn m-1 btn-secondary">
<input type="submit" id="submit" name="submit" value="View Results">
</button>
</form>
</div>
</div>
</div>
</div>
<script>
var input = document.getElementById("title");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("submit").click();
}
});
</script>
*Results output here*
</div>
Many thanks.
Edit:
Resolved, thanks for the suggestions. It turned out that this was only a problem in Firefox, not Chrome, and the reason was this:
<button class="btn m-1 btn-secondary">
<input type="submit" id="submit" name="submit" value="View Results">
</button>
input type="submit" is already a button, and wrapping it around another button apparently caused the browser some confusion.

How to reload this form without refreshing whole page?

I am using "Send Email from a Static HTML Form using Google Apps Mail" on my static site. But when I submit a form i have to refresh the whole page to submit another mail. If I don't reload the page success text don't vanish and send button don't work. So i am asking is there any way to refresh my form section without refreshing the whole page? please help me how to do it.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="container mail text-center justify-content-center mt-5">
<div class="row">
<div class="col-12">
<h3>Contact Me Now!</h3>
<hr>
</div>
<div class="col-md-12 col-xs-12 form">
<form method="post" role="form"
action="https://script.google.com/macros/s/AKfycbwtLbTgUDGQxi9FY8Jks6bJs3TnYPBNU7rvO8b8_zrdyD4Pa6g/exec"
method="post" role="form" class="gform " data-email="">
<div class="form-row">
<div class="col form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name"
data-rule="minlen:4 " data-msg="Please enter at least 4 chars " required="true" />
</div>
<div class="col form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email"
data-rule="email " data-msg="Please enter a valid email " required="true" />
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject"
data-rule="minlen:4 " data-msg="Please enter at least 8 chars of subject "
required="true" />
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required"
data-msg="Please write something for me " placeholder="Message " required="true"></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-success w-100 submit">Send Message</button>
</div>
<div style="display:none" class="thankyou_message">
<div class="alert" role="alert"> <em>Thanks</em> for contacting me!
I will get back to you soon!<br>
<i class="fas fa-sync fa-spin"></i>
</div>
</div>
</form>
</div>
</div>
</div>
<script data-cfasync="false" type="text/javascript"
src="https://cdn.rawgit.com/dwyl/html-form-send-email-via-google-script-without-server/master/form-submission-handler.js"></script>
If the form is refreshing the page, you'll need to use preventDefault to cancel its default behaviour then use reset() to reset the form.
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
[...form.elements].forEach(input => console.log(`${input.name}: ${input.value}`)); // Not Important
form.reset();
});
<form method="POST">
<input type="text" name="name" placeholder="name">
<input type="password" name="password" placeholder="password">
<button type="submit">Submit</button>
</form>
In JavaScript there is a function for forms which will reset the form clearing all the data in it, ready for another submit. This can be accomplished by running a JavaScript function on submit. This requires a couple changes in your code.
Firstly, we need to change this:
<button type="submit" class="btn btn-success w-100 submit">Send Message</button>
to this:
<button type="button" onclick="submitForm1()" class="btn btn-success w-100 submit">Send Message</button>
Once done, we can add some JavaScript to your page. If you have a JavaScript file linked to the page already, you can just add this code to that.
function submitForm1() {
let form = document.getElementsByClassName("gform");
form.submit();
form.reset();
}
You can also use document.getElementById("[id]"); and add an ID to your form. This is also preferable.
The first thing that comes to mind it's do all this on js so you can through ajax request send what you want. But I think it's not what you're looking for. You can't send data from page without refreshing, that's how it's work, php or html with some functional. You can change ...
<button type="button" class="btn btn-success w-100">Send Message</button>
... and collect all data by JavaScript and send it through ajax.

Jquery does not select the form element given an ID

I'm trying to submit a form with jquery, but it does not acknowledge that I submitted it when I click the "submit" button.
My html is as follows:
<form id="singleParam" role="form">
<div class="form-group">
<label for="sample_size">Number of samples needed</label>
<input name="choices[sample_size]" type="number" class="form-control" id="sample_size" placeholder="Enter desired number of samples">
</div>
<div class="form-group">
<label for="mode">Mode of the distribution (value most likely to be sampled)</label>
<input name="choices[mode]" type="number" class="form-control" id="mode" placeholder="Enter the likeliest value for your parameter">
</div>
<div class="form-group">
<label for="confidence">Confidence interval factor</label>
<input name="choices[confidence]" type="number" class="form-control" id="confidence" placeholder="Enter desired confidence interval factor">
</div>
<div class="form-group">
<input type="button" class="btn btn-primary btn-lg" id="submit" name="submit">
</div>
</form>
and JS is:
$('#singleParam').on('submit', function () {
alert('Form submitted!');
console.log('Form submitted!');
return false;
});
The alert() or console.log() in the loop do not work, meaning that jquery did not run the code on submit. What am I doing wrong? It might be worth mentioning that I am using bootstrap.
Change the button type from type="button" to type="submit"
EDIT:-
Make sure you are calling all your event handlers once the DOM is fully loaded by adding all the code inside dom ready event like:-
$(document).ready(function() {
// code here
});

Why element.classList.add('class-name'); is not working?

Have HTML (part):
<div class="modal-write-us">
<form class="modal-write-us-form" action="" method="post">
<label>
<input type="text" name="user-name" required>
</label>
<label>
<input type="text" name="e-mail" required>
</label>
<label for="text-field"></label>
<textarea name="text" rows="5" id="text-field" required></textarea>
</form>
<div class="modal-write-us-button">
<button class="btn btn-red" type="submit">Submit</button>
</div>
</div>
I need to add class "modal-error" for div.modal-write-us if submitted form have empty field/fields.
JS:
var modalWriteUs = document.querySelector('.modal-write-us');
var form = modalWriteUs.querySelector('form');
var userName = modalWriteUs.querySelector('[name=user-name]');
var eMail = modalWriteUs.querySelector('[name=e-mail]');
var textArea = modalWriteUs.querySelector('[name=text]');
form.addEventListener('submit', function(event) {
if (!userName.value || !eMail.value || !textArea.value) {
event.preventDefault();
modalWriteUs.classList.add('modal-error');
}
});
But class is not added. Where is my mistake?
First of all, you need to place your submit button into the form.
Then, change submit button to input:
<input class="btn btn-red" type="submit">Submit</input>
Now you need to make some fixes in your JS.Use double quotes in atttribute selectors:
querySelector('[name="user-name"]')
Attribute required doesn't allow to submit empty form, so your submit callback never runs.If you remove required attribute your code will work.
If you put <button class="btn btn-red" type="submit">Submit</button> inside the <form> it should work.
See working Plunker.
<div class="modal-write-us">
<form class="modal-write-us-form" action="" method="post">
<label>
<input type="text" name="user-name" required>
</label>
<label>
<input type="text" name="e-mail" required>
</label>
<label for="text-field"></label>
<textarea name="text" rows="5" id="text-field" required></textarea>
<div class="modal-write-us-button">
<button class="btn btn-red" type="submit">Submit</button>
</div>
</form>
</div>
EDIT: More explanation here:
The elements used to create controls generally appear inside a FORM element, but may also appear outside of a FORM element declaration when they are used to build user interfaces. This is discussed in the section on intrinsic events. Note that controls outside a form cannot be successful controls.

Post data to PHP using AJAX

I am trying to test PHP post data using AJAX. From page test I want to post on to the same page and check if PHP receives post data, if data is posted just to see if redirection is successful, so that I can write authentication code and assign session before page redirects.
When I click on the login button, I just checking isset post data and if data exists then redirect. I am not sure why this is not working. Any help is appreciated.
<script>
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: 'POST',
url: 'http://domain.com/backend/test',
data: { username: "John", password: "Boston" }
});
return false;
});
});
</script>
<?php
if(isset($_POST['username']) && isset($_POST['password'])) {
redirectto("http://domain.com/backend/test2");
// redirecto is a function equivalent to header location
}
?>
<form autocomplete="off" class="ui fluid form segment" method="post">
<div class="ui fluid form segment">
<div class="two fields">
<div class="field">
<label>Email/Username</label>
<input placeholder="Email/Username" name="username" id="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input placeholder="Password" name="password" id="password" type="password">
</div>
</div>
<input type="submit" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
</div>
</form>
Change
<input type="submit" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
to
<input type="button" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
Even if you triggered the click event of #login button, its a submit type and it will trigger the submit event first. Changing the button type should help.
In the JS, instead of using a click event, use submit.
I mean, instead of
$('#login').click(function(){
use
$('#login').submit(function(){
Also, you may add an action property to the form:
<form autocomplete="off" class="ui fluid form segment" method="post" action="#">

Categories

Resources