I hope you can help me
I have this form
<form action="do_login.php?id=" method=post>
<label>Enter your Frequent Diner ID</label><br>
<div class="shake-id">
<input id="fd-id" class="log-input" type="text" name=loginid value="" maxlength="8" placeholder="Frequent Diner ID" /><br>
</div>
<div class="id-alert" style="display: none;">Your Frequent Diner ID must have 8 digits. Check and try again</div>
<label>Enter your Password</label><br>
<div class="shake-pass">
<input id="pass" class="log-input" type="password" name=password value="" maxlength="20" placeholder="Password" /><br>
</div>
<div class="pass-alert" style="display: none;">Pass wrong</div>
<input type=hidden name=call_from value="login.php">
<input type=hidden name=forward_url value="<?PHP echo urlencode(#$_REQUEST["forward_url"])?>"><br><br>
<input id="test" type=submit value="Login">
</form>
This form execute the file do_login.php (I can not modify this action) but I have added this script before to execute the form:
$('form').submit(function () {
var value = document.getElementById('fd-id').value;
if (value.length !== 8) {
$('.shake-id').effect("shake");
$('.id-alert').fadeIn('slow');
$('#fd-id').addClass('input-wrong');
return false;
}
var value1 = $("#fd-id").val();
var value2 = $("#pass").val();
$.ajaxSetup({url: "check.php",type: 'POST', async: true, data: 'parametro1='+value1+'¶metro2='+value2+'',
success: function(result){
if (result==("OK")){
return true; //here should execute DO_LOGIN.PHP
} else {
$('.shake-pass').effect("shake");
$('.pass-alert').fadeIn('slow');
$('#pass').addClass('input-wrong');
return false; //here should NOT execute the DO_LOGIN.PHP
}
},
error:function(){
alert('dio error');
}
});
$.ajax();
});
This is working properly but the form is still calling to do_login.php. I want to call the form only if the ajax is successfull... I have added return false; and return true; in the ajax but anyway after process keep executing do_login.php
If you see my first lines of the script them execute another verification and return the form false successful but when I use the same in the ajax the return false looks like it doesnt work
Thanks in advance
It is because the ajax request is asynchronous. So the form submitwon't wait for the ajax request to complete and return true/false, since the default action is not prevented the form is submitted.
The solution is to prevent the form submit in the submit handler, then in the ajax handler if the request is successfull then call the submit again.
$('form').submit(function (e) {
//stop form from submitting
e.preventDefault();
var value = document.getElementById('fd-id').value;
if (value.length !== 8) {
$('.shake-id').effect("shake");
$('.id-alert').fadeIn('slow');
$('#fd-id').addClass('input-wrong');
return false;
}
var value1 = $("#fd-id").val();
var value2 = $("#pass").val();
var frm = this;
$.ajax({
url: "check.php",
type: 'POST',
data: 'parametro1=' + value1 + '¶metro2=' + value2 + '',
success: function (result) {
if (result == ("OK")) {
frm.submit();
} else {
$('.shake-pass').effect("shake");
$('.pass-alert').fadeIn('slow');
$('#pass').addClass('input-wrong');
}
},
error: function () {
alert('dio error');
}
});
});
Also note that I have removed the use of ajasSetup as it is not really needed, just use $.ajax() directly
Use e.preventDefault();
Place this just after you form submit function.
Related
I have a ajax call I want to use on a form so the user doesn't have to reload the page but it just keeps loading. I have tried to change the post route but I haven't had any success. Can someone point me in the right direction. Here is my code:
HTML
const http = new XMLHttpRequest();
const submit = document.querySelector('.submit');
http.onload = () => {
submit.addEventListener('click', () =>{
const alertMessage = document.querySelector('.alert');
const email = document.querySelector('#email').value;
const name = document.querySelector('.name').value;
if (name === '' || email === '') {
alertMessage.innerHTML = 'Name And Email Required';
console.log(name)
} else {
alertMessage.innerHTML = 'Success! Someone will be in touch with you soon!'
// email.value = '';
// form.reset();
}
});
}
http.open('POST', '/index.html', true);
http.send();
FORM
<div class="contactform">
<div class="alert"></div>
<form action="/index.html" method="POST" class="form">
<input type="text" name='name' id='name' placeholder="Name">
<input type="email" name='email' id='email' placeholder="Email">
<textarea class="messages" name="messages" placeholder="Message...."></textarea>
<button class="submit" type="submit" value="submit">Send</button>
</form>
</div>
You need to override form's onsubmit event to prevent submitting:
$("formSelector").bind('submit', function (e) {
var isValid = someYourFunctionToCheckIfFormIsValid();
if (!isValid) {
e.preventDefault();
return false;
} else {
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: { "text": jQuery("#edit-body").html()
},
success: function (result) {
console.log(result);
}
});
e.preventDefault();
return false;
}
});
By calling
e.preventDefault();
return false;
You prevent synchronous postback from occurring.
UPDATE:
If you don't want to override form submit, maybe you could place your button outside of form tag (you can adjust position with css if necessary)?
here I am comparing the location name whether its already entered or not, In my code I am getting alert when I click submit button but also data submitted. onchange function not working as I expected, can anyone help me how stop the data not submitting when I get alert?
When submitting time validation should be done, why because in our test server we are getting some delay after click button, so only data submitting after alert also. do you have any idea on this? Thanks in advance
<form class="form-inline" id="desgForm" accept-charset="UTF-8" method="post" action="../locationSubmit.htm" enctype="multipart/form-data">
<input type="text" id="locationName" autocomplete="off" name="locationName" class="form-control validate[required]" onchange="desgCheck();" onkeyup="firstToUpperCase1();" value="">
<button type="submit" class="btn btn-primary" >Save</button>
</form>
Javascript:
<script>
function desgCheck()
{
var locationName = document.getElementById('locationName').value;
$.ajax({
type: "POST",
url: "../designation/locationName.htm",
data: {
locationName: locationName
},
dataType: "text",
success: function (data)
{
if ($.trim(data) !== 'Data available')
{
alert("This Location already exist!!");
document.getElementById("locationName").value = "";
return false;
}
},
error: function (error) {
document.getElementById("locationName").value = "";
}
});
}
function firstToUpperCase1() {
var str = document.getElementById("locationName").value;
var a = str.toUpperCase();
$("#locationName").val(a);
}
jQuery("#desgForm").validationEngine();
</script>
I'm developing an application (a kind of social network for my university). I need to add a comment (insert a row in a specific database). To do this, I have a HTML form in my html page with various fields. At time of submit I don't use the action of form but i use a custom javascript function to elaborate some data before submitting form.
function sendMyComment() {
var oForm = document.forms['addComment'];
var input_video_id = document.createElement("input");
var input_video_time = document.createElement("input");
input_video_id.setAttribute("type", "hidden");
input_video_id.setAttribute("name", "video_id");
input_video_id.setAttribute("id", "video_id");
input_video_id.setAttribute("value", document.getElementById('video_id').innerHTML);
input_video_time.setAttribute("type", "hidden");
input_video_time.setAttribute("name", "video_time");
input_video_time.setAttribute("id", "video_time");
input_video_time.setAttribute("value", document.getElementById('time').innerHTML);
oForm.appendChild(input_video_id);
oForm.appendChild(input_video_time);
document.forms['addComment'].submit();
}
The last line submits the form to the correct page. It works fine. But I'd like to use ajax for submitting the form and I have no idea how to do this because I have no idea how to catch the form input values. anyone can help me?
Nobody has actually given a pure javascript answer (as requested by OP), so here it is:
function postAsync(url2get, sendstr) {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
// req.overrideMimeType("application/json"); // if request result is JSON
try {
req.open("POST", url2get, false); // 3rd param is whether "async"
}
catch(err) {
alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
return false;
}
req.send(sendstr); // param string only used for POST
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) // only if "OK"
{ return req.responseText ; }
else { return "XHR error: " + req.status +" "+req.statusText; }
}
}
alert("req for getAsync is undefined");
}
var var_str = "var1=" + var1 + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
// hint: encodeURIComponent()
if (ret.match(/^XHR error/)) {
console.log(ret);
return;
}
In your case:
var var_str = "video_time=" + document.getElementById('video_time').value
+ "&video_id=" + document.getElementById('video_id').value;
What about
$.ajax({
type: 'POST',
url: $("form").attr("action"),
data: $("form").serialize(),
//or your custom data either as object {foo: "bar", ...} or foo=bar&...
success: function(response) { ... },
});
You can catch form input values using FormData and send them by fetch
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) {
fetch(form.action,{method:'post', body: new FormData(form)});
console.log('We send post asynchronously (AJAX)');
e.preventDefault();
}
<form method="POST" action="myapi/send" onsubmit="send(event,this)">
<input hidden name="crsfToken" value="a1e24s1">
<input name="email" value="a#b.com">
<input name="phone" value="123-456-789">
<input type="submit">
</form>
Look on chrome console>network before 'submit'
You can add an onclick function to your submit button, but you won't be able to submit your function by pressing enter. For my part, I use this:
<form action="" method="post" onsubmit="your_ajax_function(); return false;">
Your Name <br/>
<input type="text" name="name" id="name" />
<br/>
<input type="submit" id="submit" value="Submit" />
</form>
Hope it helps.
Here is a universal solution that iterates through every field in form and creates the request string automatically. It is using new fetch API. Automatically reads form attributes: method and action and grabs all fields inside the form. Support single-dimension array fields, like emails[]. Could serve as universal solution to manage easily many (perhaps dynamic) forms with single source of truth - html.
document.querySelector('.ajax-form').addEventListener('submit', function(e) {
e.preventDefault();
let formData = new FormData(this);
let parsedData = {};
for(let name of formData) {
if (typeof(parsedData[name[0]]) == "undefined") {
let tempdata = formData.getAll(name[0]);
if (tempdata.length > 1) {
parsedData[name[0]] = tempdata;
} else {
parsedData[name[0]] = tempdata[0];
}
}
}
let options = {};
switch (this.method.toLowerCase()) {
case 'post':
options.body = JSON.stringify(parsedData);
case 'get':
options.method = this.method;
options.headers = {'Content-Type': 'application/json'};
break;
}
fetch(this.action, options).then(r => r.json()).then(data => {
console.log(data);
});
});
<form method="POST" action="some/url">
<input name="emails[]">
<input name="emails[]">
<input name="emails[]">
<input name="name">
<input name="phone">
</form>
It's much easier to just use jQuery, since this is just a task for university and you do not need to save code.
So, your code will look like:
function sendMyComment() {
$('#addComment').append('<input type="hidden" name="video_id" id="video_id" value="' + $('#video_id').text() + '"/><input type="hidden" name="video_time" id="video_time" value="' + $('#time').text() +'"/>');
$.ajax({
type: 'POST',
url: $('#addComment').attr('action'),
data: $('form').serialize(),
success: function(response) { ... },
});
}
I would suggest to use jquery for this type of requirement . Give this a try
<div id="commentList"></div>
<div id="addCommentContainer">
<p>Add a Comment</p> <br/> <br/>
<form id="addCommentForm" method="post" action="">
<div>
Your Name <br/>
<input type="text" name="name" id="name" />
<br/> <br/>
Comment Body <br/>
<textarea name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</div>
</form>
</div>
$(document).ready(function(){
/* The following code is executed once the DOM is loaded */
/* This flag will prevent multiple comment submits: */
var working = false;
$("#submit").click(function(){
$.ajax({
type: 'POST',
url: "mysubmitpage.php",
data: $('#addCommentForm').serialize(),
success: function(response) {
alert("Submitted comment");
$("#commentList").append("Name:" + $("#name").val() + "<br/>comment:" + $("#body").val());
},
error: function() {
//$("#commentList").append($("#name").val() + "<br/>" + $("#body").val());
alert("There was an error submitting comment");
}
});
});
});
I would like to add a new pure javascript way to do this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.
const formInputs = oForm.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(oForm.action,
{
method: oForm.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
As you can see it is very clean and much less verbose to use than XMLHttpRequest.
I am using the following script for validate my contact form.
//submission scripts
$('.contactForm').submit( function(){
//statements to validate the form
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById('e-mail');
if (!filter.test(email.value)) {
$('.email-missing').show();
} else {$('.email-missing').hide();}
if (document.cform.name.value == "") {
$('.name-missing').show();
} else {$('.name-missing').hide();}
if (document.cform.phone.value == "") {
$('.phone-missing').show();
}
else if(isNaN(document.cform.phone.value)){
$('.phone-missing').show();
}
else {$('.phone-missing').hide();}
if (document.cform.message.value == "") {
$('.message-missing').show();
} else {$('.message-missing').hide();}
if ((document.cform.name.value == "") || (!filter.test(email.value)) || (document.cform.message.value == "") || isNaN(document.cform.phone.value)){
return false;
}
if ((document.cform.name.value != "") && (filter.test(email.value)) && (document.cform.message.value != "")) {
//hide the form
//$('.contactForm').hide();
//show the loading bar
$('.loader').append($('.bar'));
$('.bar').css({display:'block'});
/*document.cform.name.value = '';
document.cform.e-mail.value = '';
document.cform.phone.value = '';
document.cform.message.value = '';*/
//send the ajax request
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
});
//waits 2000, then closes the form and fades out
//setTimeout('$("#backgroundPopup").fadeOut("slow"); $("#contactForm").slideUp("slow")', 2000);
//stay on the page
return false;
}
});
This is my form
<form action="mail.php" class="contactForm" id="cform" name="cform" method="post">
<input id="name" type="text" value="" name="name" />
<br />
<span class="name-missing">Please enter your name</span>
<input id="e-mail" type="text" value="" name="email" />
<br />
<span class="email-missing">Please enter a valid e-mail</span>
<input id="phone" type="text" value="" name="phone" />
<br />
<span class="phone-missing">Please enter a valid phone number</span>
<textarea id="message" rows="" cols="" name="message"></textarea>
<br />
<span class="message-missing">Please enter message</span>
<input class="submit" type="submit" name="submit" value="Submit Form" />
</form>
I need to clear the form field values after submitting successfully. How can i do this?
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
You can do this inside your $.post calls success callback like this
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
//clear fields
$('input[type="text"],textarea').val('');
});
use this:
$('form.contactForm input[type="text"],texatrea, select').val('');
or if you have a reference to the form with this:
$('input[type="text"],texatrea, select', this).val('');
:input === <input> + <select>s + <textarea>s
$('.contactForm').submit(function(){
var that = this;
//...more form stuff...
$.post('mail.php',{...params...},function(data){
//...more success stuff...
that.reset();
});
});
Simply
$('#cform')[0].reset();
it works: call this function after ajax success and send your form id as it's paramete. something like this:
This function clear all input fields value including button, submit, reset, hidden fields
function resetForm(formid) {
$('#' + formid + ' :input').each(function(){
$(this).val('').attr('checked',false).attr('selected',false);
});
}
* This function clears all input fields value except button, submit, reset, hidden fields
* */
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
example:
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
$('#alertt').fadeIn(2000);
$('#alertt').html( data );
$('#alertt').fadeOut(3000);
resetForm('userInf');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#userInf').submit( processForm );
})(jQuery);
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
</script>
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
if(data==<when do you want to clear the form>){
$('#<form Id>').find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
});
http://www.electrictoolbox.com/jquery-clear-form/
Set id in form when you submitting form
<form action="" id="cform">
<input type="submit" name="">
</form>
set in jquery
document.getElementById("cform").reset();
$('#formid).reset();
or
document.getElementById('formid').reset();
Vanilla!
I know this post is quite old.
Since OP is using jquery ajax this code will be needed.
But for the ones looking for vanilla.
...
// Send the value
xhttp.send(params);
// Clear the input after submission
document.getElementById('cform').reset();
}
just use form tag alone, like this :
$.ajax({
type: "POST",
url: "/demo",
data: dataString,
success: function () {
$("form")[0].reset();
$("#test").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$("#message").append(
"<img id='checkmark' src='images/check.png' />"
);
});
}
});
e.preventDefault();
});
Using ajax reset() method you can clear the form after submit
example from your script above:
const form = document.getElementById(cform).reset();
If you are using a form tag in your form. Then
$("#cform")[0].reset();
This code will work perfectly but in case you are not using any form tag then you can try to set an empty value to each input field Like this.
$('input[type="text"],textarea').val('');
I am having an infinite cycle using this jquery code, I know WHY but I dont know HOW to fix this:
<form id="submitme">
<input value="" name="n1" id="n1" type="text"/>
<input value="Send" type="button"/>
</form>
<script>
$('#submitme').bind( 'submit', function() {
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data == "true")
$('#submitme').submit();
});
});
</script>
The jQuery.validate plugin takes care of this and I would strongly recommend you using it:
$('#submitme').validate({
rules: {
n1: {
remote: {
url: 'validate.php',
type: 'post'
}
}
}
});
But if you don't want to use it another possibility is to use a global variable, like so:
$('#submitme').submit(function() {
if (!$.formSubmitting) {
var $form = $(this);
$.post('validate.php', { value: $('#n1').val() }, function (data) {
if (data == 'true') {
// set the global variable to true so that we don't enter
// the infinite loop and directly submit the form
$.formSubmitting = true;
$form.submit();
}
});
return false;
}
return true;
});
Just a remark: the button you have placed inside the form is not a submit button so clicking it will not trigger the submit handler. You should make it a submit button:
<input value="Send" type="submit" />
I am not a jQuery expert, but in Prototype, when you write an event handler for an action and you don't stop the default action, than it will be executed after all of your callback functionality was done. So by simply flipping the if-else statement you should be able to avoid a infinite loop:
$('#submitme').bind( 'submit', function(event) {
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data != "true")
// if validation has failed, prevent default action (submit)
event.preventDefault();
});
// if default action was not prevented it will be executed
})
I found this solution:
<form id="submitme">
<input value="" name="n1" id="n1" type="text"/>
<input value="Send" type="button"/>
</form>
<script>
$('#submitme').bind( 'submit', function() {
if ($.data( $('#submitme' ), 'validated'))
return true;
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data == "true") {
$.data( $('#submitme'), 'validated', true );
$('#submitme').submit();
}
});
return false;
});
</script>