In javascript how to send data to php file using post method - javascript

In javascript i want to know how to send data to php file using post method.
I have tried diffewrent method. But i didn't get any output so please help me.
My code is shown below.
index.php
<form method="post" name="form" enctype="multipart/form-data">
<input type="text" name="name" id="name" placeholder="Name" required/>
<input type="email" name="email" id="email" placeholder="Email" required/>
<input type="password" name="pass" id="pass" placeholder="Password" required/>
<input type="submit" name="submit" value="Send" onclick="myFunction()"/>
</form>
<script>
function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
//// I want post the values to profile.php
}
</script>
profile.php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
}

Do something like this and pass your values like this and you can check in your profile.php page....Here you cannot check if(isset($_POST['submit'])), but you you can check if(isset($_POST['name']))
<form method="post" name="form" enctype="multipart/form-data">
<input type="text" name="name" id="name" placeholder="Name" required/>
<input type="email" name="email" id="email" placeholder="Email" required/>
<input type="password" name="pass" id="pass" placeholder="Password" required/>
<input type="submit" name="submit" value="Send" onclick="myFunction()"/>
</form>
<script>
function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
$.ajax({
type : "POST", //type of method
url : "profile.php", //your page
data : { name : name, email : email, password : password },// passing the values
success: function(res){
//do what you want here...
}
});
}
</script>

Do some thing like this. Send ajax request on profile.php file.
ON profile.php file print_r($_REQUEST) you will get all your form indexes.
$(document).ready(function() {
$("form").on("submit", function(event) {
$.ajax({
type: 'POST',
url: 'profile.php',
data: $( this ).serialize(),
success: function(data) {
//success code
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" name="form" enctype="multipart/form-data" onSubmit="return false;">
<input type="text" name="name" id="name" placeholder="Name" required/>
<input type="email" name="email" id="email" placeholder="Email" required/>
<input type="password" name="pass" id="pass" placeholder="Password" required/>
<input type="submit" name="submit" value="Send" />
</form>
profile.php
print_r($_REQUEST);

First I need to say that, you can post your data by ajax (without page reloading) or by direct post (reload your page).As your question doesn't tag jquery, so i'm leaving ajax.
Here is the example for post a form data, I mean reload the current page and post the form data in profile.php
Hence your enctype will be enctype="multipart/mixed" instead of enctype="multipart/form-data" because you didn't want to send any file input in your form.
<form method="post" action="profile.php" name="form" id="your_form_id" enctype="multipart/mixed">
<input type="text" name="name" id="name" placeholder="Name" required/>
<input type="email" name="email" id="email" placeholder="Email" required/>
<input type="password" name="pass" id="pass" placeholder="Password" required/>
<input type="button" name="btnsubmit" value="Send" onclick="myFunction()"/>
</form>
<script>
function myFunction() {
//you didn't need to get the data by `document.getElementById()`. just submit your form
//var name = document.getElementById("name").value;
//var email = document.getElementById("email").value;
//var password = document.getElementById("password").value;
document.getElementById('your_form_id').submit();
}
</script>

Related

Submit button calls the javascript function even though the fields are empty and not followed the pattern

I am new to JavaScript. I have a form in an html file that has some text fields. When someone click the submit button, a JavaScript function is called to do some work (in this case, a simple alert). It works as I wanted, when I fill the text fields and click the submit button it calls the JavaScript function and the function shows an alert. However, the problem is, when a user clicks the submit button keeping some fields empty and/or not following the pattern of an email address, it calls the JavaScript function (even though HTML 5 has shown warnings in the form). I want the JavaScript function should only be called if there are no HTML warnings, I mean no empty fields and the user must follow the email pattern. Thank you for your help.
HTML code:
<form id="myForm" method="post" role="form" class="contactForm">
<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" />
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<textarea class="form-control" name="message" id="message" rows="5" data-rule="required" data-msg="Please write something" placeholder="Message"></textarea>
<button id="submitFormData" onclick="SubmitFormData();" type="submit" class="button button-a button-big button-rouded">Send Message</button>
</form>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="alert.js"></script>
Javascript Code (alert.js):
function SubmitFormData() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
alert("SHOW SOMETHING HERE");
}
you can use required attribute in the input and one more thing you can call the SubmitFormData() onsubmit form here's your modified code :
function SubmitFormData() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
alert("SHOW SOMETHING HERE");
}
<form id="myForm" method="post" role="form" class="contactForm" onsubmit="SubmitFormData();">
<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/>
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" required/>
<textarea class="form-control" name="message" id="message" rows="5" data-rule="required" data-msg="Please write something" placeholder="Message" required></textarea>
<button id="submitFormData" type="submit" class="button button-a button-big button-rouded">Send Message</button>
</form>
<script src="http://code.jquery.com/jquery-latest.js"></script>
You just need to add the required attribute to your fields, see
Here is the best working solution for what you want to achieve by using the
form validation JS plugin.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<style>
form label {
display: inline-block;
width: 100px;
}
form div {
margin-bottom: 10px;
}
.error {
color: red;
margin-left: 5px;
}
label.error {
display: inline;
}
</style>
<script>
$(document).ready(function() {
$('form[id="second_form"]').validate({
rules: {
name: 'required',
user_email: {
required: true,
email: true,
},
message: {
required: true,
}
},
messages: {
name: 'This field is required',
user_email: 'Enter a valid email',
message: 'This field is required'
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
</head>
<body>
<h2>Example 2:</h2>
<form id="second_form" method="post" action="">
<div>
<label for="name">Name:</label>
<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" />
</div>
<div>
<label for="email">Email</label>
<input type="email" class="form-control" name="user_email" id="user_email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
</div>
<div>
<label for="message">message:</label>
<textarea class="form-control" name="message" id="message" rows="5" data-rule="required" data-msg="Please write something" placeholder="Message"></textarea>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
The easiest way was to provide an HTML only solution based on a form element's required attribute since the browser will take over the validation of required elements also by their element/control type ...
<form id="myForm" method="post" role="form" class="contactForm" action="https://stackoverflow.com/">
<input
required
type="text" name="name" id="name"
class="form-control" placeholder="Your Name"
/>
<input
required
type="email" name="email" id="email"
class="form-control" placeholder="Your Email"
/>
<textarea
required
name="message" id="message"
class="form-control" rows="5" placeholder="Message"></textarea>
<button
type="submit" id="submitFormData"
class="button button-a button-big button-rouded">Send Message</button>
</form>
A generic custom validation is much more complex and labour-intensive ...
function validateControValue(elm) {
let isValid = true;
const elmType = elm.type;
if (elmType !== 'button' && elmType !== 'submit') {
const $elm = $(elm);
const isEmpty = ($elm.val().trim() === '');
if (isEmpty) {
$elm.val('');
$elm.addClass('validation-error');
} else {
$elm.removeClass('validation-error');
}
// non empty is valid, empty is invalid.
isValid = !isEmpty;
}
return isValid;
}
function handleValidFormSubmit(/* evt */) {
const isValidSubmitData = Array
.from(this.elements)
.every(validateControValue);
return isValidSubmitData;
}
function main() {
$('#myForm').on('submit', handleValidFormSubmit)
}
$(document)
.ready(main);
.validation-error {
border: 1px solid #f00;
}
<form id="myForm" method="post" role="form" class="contactForm" action="https://stackoverflow.com/">
<input
type="text" name="name" id="name"
class="form-control" placeholder="Your Name"
/>
<input
type="email" name="email" id="email"
class="form-control" placeholder="Your Email"
/>
<textarea
name="message" id="message"
class="form-control" rows="5" placeholder="Message"></textarea>
<button
type="submit" id="submitFormData"
class="button button-a button-big button-rouded">Send Message</button>
</form>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<!-- <script src="alert.js"></script> //-->

jQuery Form Processing troubles

I have a problem to process the data from my html form with jQuery. I have this simple form:
<form id="singup">
<input type="text" placeholder="Full Name" id="signup-name">
<input type="email" placeholder="Email Address" id="signup-email">
<input type="password" placeholder="Password" id="signup-pass">
<input type="password" placeholder="Retype Password" id="signup-retype-pass">
<button class="button-hover" type="submit" id="signup-submit">Create account now</button>
</form>
Now I want to get the value of the inputs with jQuery.
$("#singup").submit(function (e) {
var email = $('#singup-email').val();
console.log(email);
e.preventDefault(e);
});
But the browser console tells me the var email is undefined. Why?
Thanks for help!
Typo mistake. use signup-email not singup-email
$("#singup").submit(function (e) {
var email = $('#signup-email').val();
console.log(email);
e.preventDefault(e);
});
$("#signup-submit").on('click', function (e) {
var email = $('#signup-email').val();
console.log(email);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="singup">
<input type="text" placeholder="Full Name" id="signup-name">
<input type="email" placeholder="Email Address" id="signup-email">
<input type="password" placeholder="Password" id="signup-pass">
<input type="password" placeholder="Retype Password" id="signup-retype-pass">
<button class="button-hover" type="button" id="signup-submit">Create account now</button>
</form>

Two forms with submit buttons two different functions. One button to run a javascript

Form1 has the action to link to an external .aspx file. But once I added Form2 and the javascript file, contact-us/js/app.js, to the page. The javascript now controlls both form submit buttons. How do I link the javascript file to only run when Form2 button is submitted?
Form1
<div id="guestLogin">
<form id="frmguestlogin" name="frmguestlogin" method="post" action="AutoLogin.aspx" >
<input type="hidden" name="username" class="text" id="username" onfocus="this.value='';" tabindex="30" value="guest" />
<input type="hidden" name="password" class="text" id="password" onfocus="this.value='';" tabindex="40" value="guest" />
<input type="submit" width="80" height="20" border="0" name="submit" id="submit" value="Guest Login" tabindex="50" />
</form>
</div>
Form2 code. The last script is controlling both submit buttons on the page. How do I only have it control Form2 submit button?
Form2
<div id="form-wrapper">
<div class="inner cover">
<form class="form-signin" id="form-signin" >
<h4 class="sendMsg">Send us a message</h4>
<input type="text" id="first" class="form-control" placeholder="First Name" required>
<input type="text" id="last" class="form-control" placeholder="Last Name" required >
<input type="text" id="company" class="form-control" placeholder="Company" required >
<input type="text" id="phone" class="form-control" placeholder="Phone" required >
<input type="email" id="email" class="form-control" placeholder="Email" required >
<p> Tell us how we can help you</p>
<textarea id="comments" style="font-family: Arial, Helvetica, sans-serif" class="form-control" cols="45" rows="5" required ></textarea>
<button class="btn btn-lg btn-primary btn-block" type="submit">Send Your Message</button>
<input id="subject" name="subject" type="hidden" value="Contact Us" />
</form>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="contact-us/js/bootstrap.min.js"></script>
<script src="contact-us/js/ie10-viewport-bug-workaround.js"></script>
<script src="contact-us/js/app.js"></script>
app.js code to control form2 only:
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
//Submit Form
var first = $("input#first").val();
var last = $("input#last").val();
var company = $("input#company").val();
var phone = $("input#phone").val();
var email = $("input#email").val();
var comments = $("textarea#comments").val();
var subject = $("input#subject").val();
$.ajax({
type: "POST",
url: "contact-us.asp",
data: { first : first,
last : last,
company : company,
phone : phone,
email : email,
comments : comments,
subject : subject },
cache : false,
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
success: function() {
$('.form-signin').hide();
$('.cover').fadeIn('slow').html('<h2>Thank You, '+first+' '+last+'</h2>');
}
});
});
});
To route it with a certain script (without a form submit) I would use a normal button type.
<input type="button" value="Submit" onclick="myFunction()">
The onclick calls the JavaScript function that contains what you want it to do.
Edited - Added notes:
Also this calls just a form in general
$("form").submit
It doesn't specify what form it is, use an ID to find the 2nd form
Code:
$(document).ready(function(){
$("#form2").submit(function(){
alert("Submitted");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Form 1</h1>
Form one goes to aspx.
<form action="AutoLogin.aspx">
First name: <input type="text" name="FirstName"><br>
Last name: <input type="text" name="LastName"><br>
<input type="submit" value="Submit">
</form>
<h1>Form 2</h1>
Form two goes to the JQuery based off of the form ID (this works with external files as well)
<form id="form2">
First name: <input type="text" name="FirstName"><br>
Last name: <input type="text" name="LastName"><br>
<input type="submit" value="Submit">
</form>

HTML form onsubmit error / method="post" not working

I have a working php/mysql form submission and I'm trying to disable the submit button once the form is submitted,
HTML
<form action="" onsubmit="document.getElementById('submit-button').disabled = true;" method="post">
<p><label>Username</label>
<input id="username" type="text" name="username" value="" autofocus/></p>
<p><label>Password</label>
<input type="password" name="password" value="" /></p>
<p><label></label>
<input type="submit" id="submit-button" name="submit" value="Login" /></p>
</form>
It works fine without the onsubmit but when I add it i guess the post method isnt firing. I tried adding:
onsubmit="document.getElementById('submit-button').disabled = true; return true;"
but no luck.
Instead of using javascript. You can directly use php
<form action="" method="post">
<p><label>Username</label><input id="username" type="text" name="username" value="" autofocus/></p>
<p><label>Password</label><input type="password" name="password" value="" /></p>
<p><label></label><input type="submit" id="submit-button" name="submit" value="Login" <?php echo ('POST' == $_SERVER['REQUEST_METHOD']) ? 'disabled' : ''?>/></p>
</form>
If you post then submit button will be disabled.
It seems that your form is submitted directly, executing the 'action' tag. If you want to stay on the same form try using an AJAX request instead..
Try:
<form action="" method="post">
<p><label>Username</label>
<input id="username" type="text" name="username" value="" autofocus/></p>
<p><label>Password</label>
<input type="password" name="password" value="" /></p>
<p><label></label>
<input type="submit" id="submit-button" name="submit" value="Login" /></p>
</form>
with following script:
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$("#submit-button").on("click", function(e){
// For demo purpose
e.preventDefault();
document.getElementById("submit-button").disabled = true;
});
</script>
Using jquery,
<form action="" method="post">
<p><label>Username</label><input id="username" type="text" name="username" value="" autofocus/></p>
<p><label>Password</label><input type="password" name="password" value="" /></p>
<p><label></label><input type="submit" id="submit-button" name="submit" value="Login"/></p>
</form>
within script tags,
$(function(){
$("#submit-button").click(function(){
$("#submit-button").prop("disabled", true);
});
});

JavaScript: Form value is not being validated during submit

On this code, while i try to submit the form, am doing some validation on the input boxes, if the user-name input box value less than 6 and if there is no value, then, i am alerting alert("dshddhhdhdhh");. While I press the submit button, this alert is not working. Where is the mistake? Please.
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
</head>
<body>
<form name="loginForm" method="post">
<input type="text" name="user-name" placeholder="Firstname Lastname"/>
<span class="user-name">Name should not be empty</span>
<input type="password" name="password" placeholder="Password"/>
<input type="password" name="password1" placeholder="Confirm password"/>
<span class="password1">Password does not be match</span><span class="password">Password does not be match</span>
<input type="email" name="email" placeholder="Email" required/>
<input type="url" name="url" placeholder="Website"/>
<span class="url">Invalid Website URL</span>
<input name="submit" type="submit" value="Submit"/>
</form>
<script type="text/javascript">
window.onload = function(){
document.getElementsByName("user-name")[0].value="";
document.getElementsByName("password")[0].value="";
document.getElementsByName("password1")[0].value="";
document.getElementsByName("email")[0].value="";
document.getElementsByName("url")[0].value="";
document.getElementById("FormSubmit").style.display="none";
document.querySelector('span[class="user-name"]').style.display="none";
document.querySelector('span[class="password"]').style.display="none";
document.querySelector('span[class="password1"]').style.display="none";
document.querySelector('span[class="url"]').style.display="none";
document.getElementsByName("user-name")[0].focus();
}
var formElem = document.getElementsByName("loginForm")[0];
formElem.onsubmit = function(){
var returnValue=true;
if (loginForm.user-name.value.length < 6 ){
returnValue = false;
alert("dshddhhdhdhh");
return returnValue;
}
}</script>
</body>
</html>
Your form element is named user-name, but you're checking username. Change
if (loginForm.username.value.length < 6 ){
to
if (loginForm['user-name'].value.length < 6 ){
window.onload = function(){
document.getElementsByName("user-name")[0].value="";
document.getElementsByName("password")[0].value="";
document.getElementsByName("password1")[0].value="";
document.getElementsByName("email")[0].value="";
document.getElementsByName("url")[0].value="";
document.getElementById("FormSubmit").style.display="none";
document.querySelector('span[class="user-name"]').style.display="none";
document.querySelector('span[class="password"]').style.display="none";
document.querySelector('span[class="password1"]').style.display="none";
document.querySelector('span[class="url"]').style.display="none";
document.getElementsByName("user-name")[0].focus();
}
var formElem = document.getElementsByName("loginForm")[0];
formElem.onsubmit = function(){
var returnValue=true;
if (loginForm['user-name'].value.length < 6 ){
returnValue = false;
alert("dshddhhdhdhh");
return returnValue;
}
}
<form name="loginForm" method="post">
<input type="text" name="user-name" placeholder="Firstname Lastname"/>
<span class="user-name">Name should not be empty</span>
<input type="password" name="password" placeholder="Password"/>
<input type="password" name="password1" placeholder="Confirm password"/>
<span class="password1">Password does not be match</span><span class="password">Password does not be match</span>
<input type="email" name="email" placeholder="Email" required/>
<input type="url" name="url" placeholder="Website"/>
<span class="url">Invalid Website URL</span>
<input name="submit" type="submit" value="Submit"/>
</form>

Categories

Resources