Hi I'm trying to post my form data via ajax.
But I still want to make use of the default validation and to show the default messages from html form. So the form shows the default error messages of the form but when the form is correctly filled it does a regular form submut instead of executing the preventDefault and then my ajax method. How come it doesn't stop from submiting ? I don't understand, can anybody help me out, that would be great.
my html form:
<form id="add_address">
<div class="form-group">
<input class="form-control" type="text" name="address_address_name" required placeholder="Naam adres*" />
</div>
<div class="form-group">
<input class="form-control" type="text" name="address_address" required placeholder="Straat + Nr*" />
</div>
<div class="form-group">
<input class="form-control" type="text" name="address_zipcode" required placeholder="Postcode*" />
</div>
<div class="form-group">
<input class="form-control" type="text" name="address_city" required placeholder="Plaats*" />
</div>
<div class="form-group">
<input class="form-control" type="text" name="address_phone" placeholder="Telefoon" />
</div>
<div class="form-group">
<input class="form-control" type="text" name="address_email" required placeholder="Email*" />
</div>
<button type="submit" class="btn btn-default right">Save</button>
</form>
my javascript:
$('#add_address button').on('click',submit_form_address);
function submit_form_address(event){
form = $('#add_address');
console.log("yes here:"+ $(form)[0].checkValidity());
if( $(form)[0].checkValidity() != false){
event.preventDefault();
add_address(form);
}
}
function add_address(p_Form){
var url = '/addresses';
data = new FormData($(p_Form)[0]);
$.ajax({
url:url,
method:'POST',
data:data,
cache: false,
contentType: false,
processData: false,
success:success_add_address,
error:error
});
}
Solution for me: I now using this way and this way is working for me to use default validation of the html form and do a custom submit through ajax.
$(document).on('submit', '#add_address', function(e){
add_address($(this));
e.preventDefault();
});
if( $(form)[0].checkValidity() != false){
add_address(form);
event.preventDefault();
}
// OR
if( $(form)[0].checkValidity() != false){
add_address(form);
return false;
}
Related
I have a form that includes a checkbox:
<form action="tienda3.php">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email to confirm the order">
</div>
<div class="form-group">
<div class="checkbox">
<label><input type="checkbox" id="TOS" value="This"> I certify that I am of legal age and I have read and agree to the
Terms of use and
Privacy Policy of Sdocks LLC</label>
</div>
</div>
<button type="submit" onclick="validate()" class="btn btn-primary">Submit</button>
</form>
I need to verify that the user checks the checkbox to post the form to tienda3.php.
I am using this script to validate that the user has checked the checkbox or not:
<script type=text/javascript>
function validate(){
if (document.getElementById('TOS').checked){
alert("checked") ;
}else{
alert("You didn't check it! Let me check it for you.");
return true;
}
}
</script>
If the checkbox is checked then the form is posted to tienda3.php, else an alert must be shown to inform the user that it is mandatory to check the checkbox to continue the process.
In my case, the form is always posted to tienda3.php. The script detects if the checkbox is checked or not, but in both cases, the form always opens file tienda3.php
I suggest you make this changes:
/* replace this:
* <form action="tienda3.php"> */
<form action="tienda3.php" onsubmit="return validate(event)" >
/* replace this:
* <button type="submit" onclick="validate()" class="btn btn-primary">Submit</button> */
<button type="submit" class="btn btn-primary">Submit</button>
/* and replace the validate() function with: */
function validate(event){
if (document.getElementById('TOS').checked){
alert("checked") ;
return true;
} else {
event.preventDefault();
alert("You didn't check it! Let me check it for you.");
return false;
}
}
Let me know if it worked as expected.
You can also find solutions by searching Stackoverflow How to prevent form from being submitted - inline javascript
I prefer to use ajax request instead of form action
HTML
<form>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email to confirm the order">
</div>
<div class="form-group">
<div class="checkbox">
<label><input type="checkbox" id="TOS" value="This"> I certify that I am of legal age and I have read and agree to the
Terms of use and
Privacy Policy of Sdocks LLC</label>
</div>
</div>
<button type="button" onclick="SubmitRequest()" class="btn btn-primary">Submit</button>
</form>
js
function SubmitRequest() {
if (document.getElementById('TOS').checked){
var postObj = {
email: $('#email').val(),
};
$.ajax({
url: "/tienda3.php",
data: JSON.stringify(postObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
console.log(result)
},
error: function (errormessage) {
console.log(errormessage);
}
});
}
});
I try to check if an email exists before allowing to submit the form.
if the email exists, I get the alert which I added to test the form, but it still submits the form and moves to "login.asp".
I also added "event.preventDefault();" to try and stop it, but still it happens
Here is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() { //newly added
$('#Submit').click(function() {
alert('in');
var emailVal = $('#email').val(); // assuming this is a input text field
$.post('User_RegisterCheck.asp', {
'email': emailVal
}, function(data) {
if (data == 'exist') {
alert('exits');
return false;
event.preventDefault();
} else $('#FormRegID').submit();
});
});
});
</script>
</head>
<body>
<form method="post" id="FormRegID" name="FormRegID" action="login.asp">
<div class="form-group ">
<label for="email" class="control-label">email</label>
<input type="email" class="form-control w-75" id="email" name="email" placeholder="email" required>
</div>
<input type="image" name="Submit" src="/images/button_login-register.png" border="0" alt="Submit" id="Submit" style="width: 209px;" />
</div>
</form>
</body>
</html>
How can I validate the email?
The issue is because you stop the submission too late; you're doing it in the AJAX request which is asynchronous. The form has already been sent by the time that occurs.
To fix this call preventDefault() on the event, regardless of the state of the AJAX request. Then you can make the request and if the validation passes you can submit the form element (note: not the jQuery object containing the form) and allow the data to be sent to the server. Try this:
<form method="post" id="FormRegID" name="FormRegID" action="login.asp">
<div class="form-group ">
<label for="email" class="control-label">email</label>
<input type="email" class="form-control w-75" id="email" name="email" placeholder="email" required>
</div>
<input type="image" name="Submit" src="/images/button_login-register.png" border="0" alt="Submit" id="Submit" style="width: 209px;" />
</div>
</form>
jQuery(function($) {
$('#FormRegID').on('submit', function(e) {
e.preventDefault();
var emailVal = $('#email').val();
$.post('User_RegisterCheck.asp', {
'email': emailVal
}, function(data) {
if (data.trim() !== 'exist')
this.submit();
});
});
});
Note that this hooks to the submit event of the form, not the click of the button.
I would also suggest you return a boolean value in a formal data structure from your AJAX call, such as JSON, instead of plaintext. This is because whitespace can cause problems with the latter being interpreted correctly.
I have a login button that works fine,it logs a user in etc.. but i want to allow the user to press the enter key to login as well. how do i do this.I tried a test using onkeypress but it didnt do anything as bellow
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username id="username" />
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="........" id="password" onkeypress=myFunction() /> //i just tried this myFunction() to see if it would give an alert but it doesnt
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-login" id="btnLogin">Log in</button>
</div>
</div>
</form>
function myFunction()
{ alert("button pressed")}
so how do i use the enter key to submit my request in javascript and jquery
As you've placed the input within a form element which contains a submit button, you get this behaviour by default. To hook to it, use the submit event of the form, like this:
$('form').on('submit', function(e) {
e.preventDefault(); // only used to stop the form submission in this example
console.log('form submitted');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" id=" username" />
</div>
<div class="form-group ">
<input type="password" class="form-control" placeholder="........" id="password" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-login" id="btnLogin">Log in</button>
</div>
</form>
Note that I fixed the missing " after the placeholder attribute in the first input. You also don't need the trailing space after all the attribute values, so I removed those too.
First you need to send the Event to the myFunction() function and add ID to your form to add submit manually::
HTML
<form id='myForm'>
<!-- form actions (etc..) -->
<input type="password" class="form-control" placeholder="........" id="password" onkeypress=myFunction(e) />
<!-- form actions (etc..) -->
</form>
Now in ASCII the reenter code is 13 all you need to check is when the pressed key is reenter (13) then you need to take the event key code and call the submit function::
function myFunction(e)
var code = (e.keyCode ? e.keyCode : e.which);
{
if (code == "13")
{
//Calling the submit or clicking manually it
$( "#myForm" ).submit();
}
}
I'm getting the error of MethodNotAllowedHttpException when I run the below code:
<h1>Temp Form</h1>
<form method="post" action="" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="panel panel-default ">
<div class="container">
<div class="panel-body">
<div class="form-group">
<label for="firstName">First Name *</label>
<input name="fname" type="text" class="form-control" id="firstName" placeholder="Enter First Name" required>
</div>
<div class="form-group">
<label for="lastName">Last Name *</label>
<input name="lname" type="text" class="form-control" id="lastName" placeholder="Enter Last Name" required>
</div>
<div class="form-group">
<label for="qualification">Qualification *</label>
<input name="qualification" type="text" class="form-control" id="qualification" placeholder="BE, MCA, MBA Etc." required>
</div>
<div class="form-group">
<label for="emailAddress">Email address *</label>
<input name="email" type="email" class="form-control" id="emailAddress" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contactmessage">Message</label>
<textarea name="desc" type="text" class="form-control" id="contactmessage" placeholder="Message" rows="2"></textarea>
</div>
<input type="submit" id="add" class="btn btn-primary" onclick="addUpdateData(id)" value="Add"></button>
</div>
</div>
</div>
</form>
Code for routes.php :
Route::post('welcome/addupdate','FormController#addUpdateData');
code for controller :
public function addUpdateData(Request $req)
{
$id = $req->input('id');
if($id=="add")
{
$bs = new Basicusers;
$bs->fname = $req->fname;
$bs->lname = $req->lname;
$bs->qualification = $req->qualification;
$bs->email = $req->email;
$bs->desc = $req->desc;
$bs->save();
return "Data Successfully Added";
}
}
What I want is, when user clicks on add button, value in variable data add is passed, and on controller, I will check value for variable and if its add, than I will perform add operation.
meanwhile if the user click on edit button which is provided below in form, that row will be filled in form elements and the add button is changed to update button and value of variable data will be now update and I want to perform update operation...
I'm getting error when I am passing data using POST method
moreover I don't know how to get data passed using POST method..
for GET method I am using $id = Input::get('id'); method and its working
Here is JavaScript Function :
function addUpdateData(data) {
$(function() {
$.ajax({
method: "post",
url: "welcome/addupdate",
data: {
id: data
},
success: function(response) {
alert(response);
}
});
});
}
Try to use absolute path in your ajax request: url: "/welcome/addupdate"
Add a some ID for your form (ex. #form) and pass into the addUpdateData function serialized data from the form.
$('#add').on('click', function(e) {
e.preventDefault();
var data = $('#form').serialize();
addUpdateData(data);
});
Add also a input field as hidden type into the form which should have an ID of the existing resource. Then on the controller action you can get an array of the passed data and if if the ID of the resource exists the perform update. If not then create them.
Can someone help me out here, i have a form which pop ups after a min on a video page, i want the form to close by itself once its submitted so the video could continue, how this is possible with jQuery?
this is my form
<ul class="mktLblLeft">
<div class="txt-fld">
<label>First Name:</label><span class="mktInput"><input class="mktFormText" id="Email" maxlength="255" name="24132" tabindex="1" type="text" value="" />
</span></li>
<label>Last Name:</label><span class="mktInput"><input class="mktFormTex" id="FirstName" maxlength="255" name="24134" tabindex="2" type="text" value="" /></span></li>
<label>Email Address:</label><span class="mktInput"><input class="mktFormText" id="LastName" maxlength="255" name="24136" tabindex="3" type="text" value="" />
</div>
<div class="btn-fld">
<button type="submit">Sign Up »</button>
i have tried this code, is there something wrong with this?
function closeSelf(){
// do something
if(condition satisfied){
alert("conditions satisfied, submiting the form.");
document.forms['certform'].submit();
window.close();
}else{
alert("conditions not satisfied, returning to form");
}
}
An easy way to to this would be to use hide() when the button is clicked.
<button type="submit" onlick="$('#myForm').hide()">Sign Up »</button>
Assuming this is inside a <form id="myForm">
Here's a jQuery AJAX solution:
jQuery('button#yourSubmitButton').on('click', function(event) {
// prevent normal submit
event.preventDefault();
// call ajax submit
jQuery.ajax({
type: "POST",
url: "bin/yourprocess.php",
success: function() {
// fadeout the form
jQuery('.mktLblLeft').fadeOut();
},
error: function() {
// give feedback to user
alert('something went wrong!');
}
});
});