I am trying to place 2 HTML forms on the same page, then use JavaScript to control the target .php file they submit to, based on which submit button is pressed.
At the moment, it's sending to the correct php/email address, but also taking the user away from the page - which is what I want to prevent.
Any help would be appreciated. Here is my HTML:
<div class="col-md-6">
<form class="form" id="ajax-contact-form" action="multi/sendmail.php">
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="fa fa-user"></i></span>
<input type="text" name="contact_name" id="contact_name" class="form-control" placeholder="Name" required>
</div>
</div>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="fa fa-envelope"></i></span>
<input name="contact_email" id="contact_email" type="email" class="form-control" placeholder="Email" required>
</div>
</div>
<textarea name="contact_message" id="contact_message" placeholder="Message" rows="8" class="form-control" required></textarea>
<div class="controls send">
<button type="submit" class="btn-primary btn-lg" value="Submit1" id="submit2" onClick="mainform">Send</button>
<div class="loading"></div>
<div class="results"></div>
</div>
</form>
</div>
<!--FORM 2-->
<div class="col-md-6">
<form class="form2" id="ajax-contact-form2" action="multi/sendmail2.php">
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="fa fa-user"></i></span>
<input type="text" name="contact_name" id="contact_name" class="form-control" placeholder="Name" required>
</div>
</div>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="fa fa-envelope"></i></span>
<input name="contact_email" id="contact_email" type="email" class="form-control" placeholder="Email" required>
</div>
</div>
<textarea name="contact_message" id="contact_message" placeholder="Message" rows="8" class="form-control" required></textarea>
<div class="controls send">
<button type="submit" class="btn-primary btn-lg" value="Submit2" id="submit2" onClick="form2">Send</button>
<div class="loading"></div>
<div class="results"></div>
</div>
</form>
</div>
<!--/FORM 2-->
And here is my JavaScript:
function mainform() {
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail.php', $('.form').serialize(), function(data) {
$('.results').html(data);
}).success(function() {
$('.loading').hide();
})
}
function form2() {
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail2.php', $('.form2').serialize(), function(data) {
$('.results').html(data);
}).success(function() {
$('.loading').hide();
})
}
And here is my old JavaScript, which worked:
$('form').submit(function(e) {
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail.php', $('.form').serialize(), function(data){
$('.results').html(data);
}).success(function(){
$('.loading').hide();
})
})
And one of the PHP files:
<?php
$name = isset($_REQUEST['contact_name']) ? $_REQUEST['contact_name'] : '' ;
$email = isset($_REQUEST['contact_email']) ? $_REQUEST['contact_email'] : '' ;
$message = isset($_REQUEST['contact_message']) ? $_REQUEST['contact_message'] : '' ;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From:".$name." ".$email;
// Replace mail#website.com with your email
mail( "me#email.com", "Message from My Future Now Website",$message, $headers );
print "<strong>Form submitted successfully.</strong>";
?>
What am I doing wrong?
Have you tried changing the second place that the following lines appears to something else?
<div class="loading"></div>
<div class="results"></div>
I see both javascript functions refer to an element like it's the only one, and you have two now. If you change the second one to this:
<div class="results2"></div>
<div class="loading2"></div>
Then you can change
function form2(){
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail2.php', $('.form2').serialize(), function(data){
$('.results').html(data);
}).success(function(){
$('.loading').hide();
})
}
to:
function form2(){
e.preventDefault();
$('.loading2').show();
$.post('multi/sendmail2.php', $('.form2').serialize(), function(data){
$('.results2').html(data);
}).success(function(){
$('.loading2').hide();
})
}
I think that will give you greater success. Let me know if you run into any further problems after trying such a change
There are several problems here which are preventing the functionality you want.
Your page is posting because when you call e.preventDefault() - I suspect you are getting a JavaScript error, indicating that e is undefined.
Because the default behavior of a submit button being clicked is therefore not being prevented - it occurs... and the default behavior is a full-page post to the server. This is why you're being taken away from your page.
There are 2 ways you can solve for this easily:
1. Solution 1: Just add the event parameter back in
function mainform(e) { ... }
function form2(e) { ... }
This will simply fix the JavaScript error you currently have, and allow your e.preventDefault() to work.
However - you are using jQuery on your page already - so I suggest that you maintain consistency with your tools - and use jQuery's event binding syntax. This is how your original JavaScript was written - and you can now go back to it.
2. Solution 2: Reintroduce jQuery
Change the ID of your your first form's submit button to ID="submit1'. Currently both buttons have the same name, which is invalid HTML and may cause issues.
Remove the onclick= binding syntax from both button elements.
Update your JavaScript as follows:
New JavaScript:
$('#submit1').on('click', function (e) {
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail.php', $('.form').serialize(), function(data) {
$('.results').html(data);
}).success(function() {
$('.loading').hide();
})
});
$('#submit2').on('click', function (e) {
e.preventDefault();
$('.loading').show();
$.post('multi/sendmail2.php', $('.form2').serialize(), function(data) {
$('.results').html(data);
}).success(function() {
$('.loading').hide();
})
});
Note that we still added back in the e to each function() call - exactly as in Solution 1.
If this doesn't work for you - feel free to comment and ask for more help.
Related
I am creating a form which will be submitted through the use of jQuery AJAX, but I am for some reason only able to submit the form once. To submit again I have to refresh page?
How do i accomplish the form and script so I do not have to refresh?
Here is the form:
<form role="form" class="form-horizontal validate" name="create_form" id="create_form">
<div class="form-group">
<label class="col-sm-2 control-label" for="name">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" data-validate="required" data-message-required="Remeber to fill name" placeholder="">
</div>
</div>
<div class="form-group-separator"></div>
<div class="form-group">
<button id="submit_btn" class="btn btn-success">Create</button>
<button type="reset" class="btn btn-white">Reset</button>
</div>
</form>
And here is the AJAX part:
$(document).ready(function(){
$("#submit_btn").on("click", function () {
$.ajax({
type: 'POST',
url: 'data/create.php',
cache: false,
data: $('#create_form').serialize()
})
.done(function(data){
$("#name").val("");
})
.fail(function() {
console.log("ERROR");
});
// Prevent refreshing the whole page page
return false;
});
});
Hoping for help and thanks in advance :-)
use submit instead of click.
$('#submit_btn').on('submit', function(e) {
e.preventDefault();
... //rest of the code
});
I don't really see why you are wanting to run your script on document load. I would suggest you to include the script's source in the html and include an onClick attribute to the button element and then assign the event handler function call to it to be fired every time you click the Submit button.
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
I am building a portfolio website and in the contact form, I want a success/fail response after submission. I prefer to stay on the same page whilst this process.
I tried other solutions that were in other pages related to this topic but I could not understand why they did not work for me. Since I am a newbie, I will appreciate a crystal clear explanation. Thanks a lot!
I tried the solution under this topic: Submit contact form with success/fail alert on same page
MY CURRENT HTML CODE IS;
<form id="contact-form" method="post" action="contact.php" role="form" enctype="text/plain">
<div class="messages"></div>
<div class="controls">
<div class="form-group">
<input id="form_name" type="text" name="name" class="form-control" placeholder="Name *" required="required" data-error="name is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input id="form_email" type="email" name="email" class="form-control" placeholder="E-mail *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input id="form_subject" type="text" name="subject" class="form-control" placeholder="Subject">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="send a message."></textarea>
<div class="help-block with-errors"></div>
</div>
<input type="submit" name="submit" class="btn btn-send float-" value="Send message">
<p class="text-muted"><strong>*</strong> These fields are required.</p>
</div>
<div class="clearfix"></div>
</form>
I expect to see confirmation or fail report on the same page after submitting the form. It can be anywhere on the page. I just want the visitor to know that I received their message or could not.
Simple example jQuery version:
$("#contact-form").submit(function() {
var name = $("#form_name").val();
var email = $("#form_email").val();
// ...other fields
// and validation if empty or e-mail is valid etc.
// if validation fails just return false;
if( !name ) {
// here You can send message or activate help-block
return false;
}
// if everything correct use for example ajax from jquery
$.ajax({
url: '/url/to/receiver',
type: 'post',
data: { name: name, .... },
dataType: 'jsonp',
success: function( r ) {
if( r.success ) {
// message and pass form validation
// clear fields, or hide contact form
}
if( r.error ) {
// show error
}
}
});
return false;
});
Remember to return from server JSON like { success: true } or { error: true, msg: "message why fails" }.
But it will be much better, when You will change input type=submit to button, and then make:
$("#contact-form .class-of-input-button").off().on('click', function() { /* rest of the code */ });
Hello I want to get the value of this input and fetch it using ajax no database at all. thank you. how can i do it with ajax?
<form method="POST">
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</form>
there is my inputs and here is the button.
<form action="top-up.php" method="POST">
</div>
</div>
<div class="col-md-6" style="margin-top: -160px">
<div class="caption">
<div class="jumbotron">
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt" onchange = "change()"></textarea><br><br><br>
<input class="btn btn-primary btn-lg" type="submit" name="btnSubcode" value="PROCESS"></input>
</div>
</div>
</div>
</div>
</form>
so the final output sould not refresh the page and the textarea value will be send to the textbox
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process.
http://malsup.com/jquery/form/#getting-started
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<input type="submit" value="Submit Comment" />
</form>
// prepare Options Object
var options = {
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
};
// pass options to ajaxForm
$('#myForm').ajaxForm(options);
Firstly, rewrite your html code as below:
<form id="form" action="top-up.php" method="POST">
</div>
</div>
<div class="col-md-6" style="margin-top: -160px">
<div class="caption">
<div class="jumbotron">
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
<input class="btn btn-primary btn-lg js-form-submit" type="submit"></input>
</div>
</div>
</div>
</div>
</form>
Then, you can write JS something like this:
$(document).on('click','.js-form-submit', function (e) {
e.preventDefault();
var formData = $('#form').serialize();
var url = $('#form').attr('action');
$.ajax({
type: "POST",
cache: false,
url: url // Your php url here
data : formData,
dataType: "json",
success: function(response) {
//var obj = jQuery.parseJSON(response); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handling here');
}
});
});
I have a register form that I wish to do validation on the moment a user clicks submit. This is what the HTML looks like:
<form ng-submit="RegistrationC.fireReg()" novalidate name="register">
<div class="row">
<div class="col-md-6 form-group">
<input type="text" autocomplete="off" class="form-control" placeholder="First Name" ng-model="RegistrationC.first_name" required name="first_name">
<div class="help-block" ng-messages="register.first_name.$error" ng-show="submitted && register.first_name.$error">
<p ng-message="required">This field is required.</p>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 form-group col-md-offset-3">
<button type="submit" class="btn btn-success btn-block" ng-click="submitted=true">Register Now</button>
</div>
</div>
</form>
It is showing the validation message if a username is not typed in, but it still submits. What am I missing?
EDIT 1
//init.js - RegistrationController
reg_list.fireReg = function () {
var url = 'user/register';
api.makeCall(reg_list, url)
.then(function (response) {
reg_list.response = response;
console.warn(response);
$location.path('/user/verify');
})
.catch(function (errorMessage) {
console.log("got an error in initial processing", errorMessage);
event.restoreButton();
});
};
I know there's issues in this function, I will fix them at a later stage.
Submit this form only if it is valid. <whatever_form_name>.$valid
<form ng-submit="register.$valid && RegistrationC.fireReg()" novalidate name="register">
Just add checkpoint whether form is valid or not before submitting form
Try like this
<form ng-submit="register.$valid && RegistrationC.fireReg()" novalidate name="register">
If you want to disable html5(or browser) validator, You have to remove 'required' attribute in your html code
http://www.the-art-of-web.com/html/html5-form-validation/
http://www.w3schools.com/tags/att_input_required.asp
I have a little form in my modal which looks like this:
<form name="form" action="" method="post">
<div class="modal-body">
<input type="text" name="edited_id" value="" id="edited_id" class="hidden"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="edited_name" class="form-control" id="edit_name" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="edited_email" class="form-control" id="edit_email" value="">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="edit_submit" class="btn btn-primary" value="Edit user"/>
</div>
</form>
and I want to prevent the form to submit if the user enters an email that it is already in my database. I have the following script:
$("#check_email").click(function() {
var email = $(this).parent().siblings().find("#email").val();
var that = $(this);
$(this).parent().parent().submit(function( event ) {
$.get("php/verify_email.php", {email: email}, function(data){
if(data === "")
{
that.parent().parent().unbind('submit').submit();
}
else {
alert(data);
event.preventDefault();
}
});
});
});
The problem is that if I put the even.preventDefault() in that else condition, the $.get() seems to not trigger, because I guess that the form submits faster. Otherwise if I put the event.preventDefault() right after the .submit(function( event ) { then I can't unbind the submit to work after the user changes the email.
What I am doing wrong?
P.S.
My php file looks like this:
<?php
include "connect.php";
if(isset($_GET['email']) && !empty($_GET['email'])){
$sql = "SELECT * FROM users WHERE email='".$_GET['email']."';";
$result = $conn->query($sql);
if ($result->num_rows > 0){
echo "The email is already in our database. Please try another one!";
}
}
?>
I understand you would like to avoid form sending if email is already used.
At first, where is your magic button to do this :D ?
I added button in example.
You must be sure that your "this" is element you want, creating structure like .parent().parent().parent() everywhere is stupid - one change and everything not work.
Next thing to avoid form submit you must return false; inside submit function, preventDefault() work with <a> or other events like click
And next.. if you send ajax your callback function can back to your browser after your submit click.
For example checkClick -> sendAjax -> submitClick -> ajaxBack
And next :D - PHP: Your form have method="post" but server use $_GET
So.. if you send post you must use $_POST if get than $_GET
This time you used $.get so i dont know your ajax configuration but this can cause errors.
Here is some code but im sure this is not final implementation you want, but it should help :)
sorry for english btw.
html:
<form name="form" action="" method="post">
<div class="modal-body">
<input type="text" name="edited_id" value="" id="edited_id" class="hidden"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="edited_name" class="form-control" id="edit_name" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="edited_email" class="form-control" id="edit_email" value=""> <button type="button" id="check_email" data-dismiss="modal">check</button>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="edit_submit" class="btn btn-primary" value="Edit user"/>
</div>
</form>
javascript:
$("#check_email").click(function() {
var email = $(this).parent().find("#email").val();
var that = $(this);
alert(email);
console.log($(this).parent().parent().parent())
$(this).parent().parent().parent().submit(function( event ) {
$.get("php/verify_email.php", {email: email}, function(data){
if(data === "")
{
that.parent().parent().unbind('submit').submit();
}
else {
alert(data);
event.preventDefault();
}
});
return false;
});
});