Can't submit my form twice with ajax - javascript

Hey everyone, I have some problems with a (I think simple) form submitting with ajax.
The first time the user submit the form, everything goes OK: The content of the div changes and the php is processed. But if there is no match in my DB it will return "f" and the javascript will write back an unusable form that can't be re-submitted with ajax.
The HTML:
<div class="maincontainer" id="login">
<form id="loginform" onsubmit="void login();return false;">
<input name="username" type="text" class="textboxinput" id="username" autocomplete="off" />
<input name="password" type="password" class="textboxinput" id="password" autocomplete="off" />
<input type="submit" name="button" class="button" id="button" value="Login" />
</form>
</div>
The Javascript:
function login(){
//Change the box content to "Logging in"
$("#login").html("<p style='line-height:170px;text-align:center;width:100%;margin:0px;padding:0px;'>Logging in</p>");
//Get the values of the username and password field
var username = $('#username').val();
var password = $('#password').val();
//Make the ajax request
$.ajax({
datatype: "text",
type: "POST",
url: "process.php",
data: "username=" + username + "&password=" + password,
success: function (m) {
//If there's no match, rewrite the form in the div
if ( m == "f"){
content= " <form id='loginform' onsubmit='void login();return false;'><input name='username' type='text' class='textboxinput' id='username' autocomplete='off' /><input name='password' type='password' class='textboxinput' id='password' autocomplete='off' /><input type='submit' name='button' class='button' id='button' value='Login' /> <p style='font-size:small;'>Login failed, please try again</p></form>";
$("#login").html(content);
}
}
});
};
EDIT
I didn't find the problem but I did find a solution which is not to erase my form, only hide it
HTML:
<div class="maincontainer" id="login">
<div id="errorbox"></div>
<form id="loginform" onsubmit="return login();">
<input name="username" type="text" class="textboxinput username" id="username" value="username" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value='username'" autocomplete="off" />
<input name="password" type="password" class="textboxinput password" id="password" value="password" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value='password'" autocomplete="off" />
<input type="submit" name="button" class="button" id="button" value="Login" />
<div id="errorshow">RegisterForgot your login infos?</div>
</form>
</div>
Javascript:
function login(){
var username = $('#username').val();
var password = $('#password').val();
//Do security checks here
$("#loginform").hide();
$("#errorbox").html("<p class='logloading'>Logging in</p>");
$.ajax({
datatype: "text",
type: "POST",
url: "login.php",
data: "username=" + username + "&password=" + password + "&method=js",
success: function (m) {
if ( m == "f"){
$("#errorbox").html("");
$('#username').val("");
$('#password').val("");
$("#loginform").show();
$("#errorshow").html("<p class='errormsg'>Wrong username/password combination</p>");
$("#username").focus();
}
else{
window.location = m;
}
}
});
return false;
};
Oh, and I should thank everybody that commented here (and posted) every info helped me a bit.

Just a fix, not an explicit answer to your original question.
I'd use
data: $('#form_id').serialize()
instead of manually doing all of this:
data: "username=" + username + "&password=" + password,
What happens when the user submits a space? Your query breaks.
Just make sure the username box has a name of username and the password box follows the same pattern.
EDIT
This code is a bit odd:
onsubmit='void login();return false;'
Instead of manually inputting this, try this code (just delete that part and insert this):
$('#loginform').live('submit', function(e) {
login();
e.preventDefault()
});

I think I ran into this problem a while back as well.
A plausible workaround would be to put the login function on the onclick of the submit button instead (and have that return false as well)

Related

How to check if submitting form with jQuery if successful?

I have following codes as form, and I wanted to check if the form is been successfully submitted.
I was wondering how I can check on the console. I want to check if the form is been successfully submitted so I can display another form.
<form id="signup" data-magellan-target="signup" action="http://app-service-staging.com" class="epic_app-signup" method="POST">
<div class="grid__column " style="width: 100%;">
<input type="text" name="first_name" placeholder="Name" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="password" placeholder="Password" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="confimred-password" placeholder="Confirmed password" />
</div>
<div class="grid__column " style="width: 100%;">
<input type="date" name="startdate" id="startdate" min="2019-12-16">
</div>
</div>
<button type="submit" class="grid__column" style="width: 50%;"></button>
</div>
</div>
</div>
</form>
and the script,
$('.epic_app-signup').on('submit', function(e) {
e.preventDefault();
var formData = $('.epic_app-signup').serializeArray();
var jsonData = {};
formData.forEach(function(item, index) {
jsonData[item.name] = item.value;
});
console.log('data\n', jsonData);
$.ajax({
url: 'http://app-service-staging.com/api/auth/register',
type:'POST',
data: jsonData,
contentType: 'application/json'
}).done(function(data, textStatus, jqXHR) {
if (textStatus === 'success') {
}
});
});
});
you can do this by various ways currently you are not using ajax request if you want to achieve this without ajax let follow these steps
when user click on submit button your form is submitted received form information(you define the path in action attribute where form submitted) after processing successfully redirect toward a new form
second solution use jquery ajax request
//first form
<form action='test.php' id='form_1' method='post'>
<label>Full Name</label>
<input type='text' name='full_name'>
<input type='submit'>
</form>
//second form
<form action='test.php' id='form_2' method='post' style='display:none'>
<label>Father Name</label>
<input type='text' name='father_name'>
<input type='submit'>
</form>
use jquery cdn
<script src='https://code.jquery.com/jquery-git.js'></script>
<script>
$("#form_1").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert("form submitted successfully");
$('#form_1').hide();
$('#form_2').show();
},
error:function(data){
alert("there is an error kindly check it now");
}
});
return false;
});
</script>

Submitting form with ajax and formspree using VuesJS

I'm trying to submit a form using formspree I get two different errors. When I try to submit the form after I refresh the page I get an error on a new page saying
Cannot POST /Contact
When I go back and try to submit the form again I get an error in the console saying:
POST https://formspree.io/sheabathandbody#mail.com 400 () jquery.min.js:4
send # jquery.min.js:4
ajax # jquery.min.js:4
(anonymous) # main.js:8
dispatch # jquery.min.js:3
r.handle # jquery.min.js:3
I've used this method/code to submit my forms before so i don't know what the problem could be
Contact.vue form
<form id="contact" name="contact-form" method="post" action = "">
<fieldset>
<input placeholder="Your name" name="name" type="text" id="name" tabindex="1" required="required">
</fieldset>
<fieldset>
<input placeholder="Your Email Address" name="email" id="email" type="email" tabindex="2" required="required">
</fieldset>
<fieldset>
<input placeholder="Your Phone Number (optional)" type="tel" tabindex="3">
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." tabindex="5" name="message" id="message" required="required"></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="submit_btn" >Submit</button>
</fieldset>
</form>
Here's my main.js
(function($) {
$(window).on("load", function() {
// Contact form
var form = $("#contact");
form.submit(function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: "https://formspree.io/sheabathandbody#mail.com",
method: "POST",
data: $(this).serialize(),
dataType: "json",
beforeSend: function() {
form.prepend(
form_status
.html(
'<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>'
)
.fadeIn()
);
}
}).done(function(data) {
form_status
.html(
'<p class="text-success">Thank you for contacting us. We will be in touch.</p>'
)
.delay(3000)
.fadeOut();
});
});
});
})(jQuery);
Guess this has nothing to do with VueJS since it does not use at all vue in that chunks of code you shared, this is pure jQuery.
Said that, the problem sending the form was because you were not listening correctly to submit event.
form.on('submit', function () { ... })
On the other hand, ajax call is not working correctly; you should check documentation of formspree.io and correct it.
Check next code
$(document).ready(function() {
// Contact form
var form = $("#contact");
form.on('submit', function(event) {
alert('Hola hola. This is working now!');
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: "https://formspree.io/sheabathandbody#mail.com",
method: "POST",
data: $(this).serialize(),
dataType: "json",
beforeSend: function() {
form.prepend(
form_status
.html(
'<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>'
)
.fadeIn()
);
}
}).done(function(data) {
form_status
.html(
'<p class="text-success">Thank you for contacting us. We will be in touch.</p>'
)
.delay(3000)
.fadeOut();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact" name="contact-form" method="post" action="">
<fieldset>
<input placeholder="Your name" name="name" type="text" id="name" tabindex="1" value="blah" required="required">
</fieldset>
<fieldset>
<input value="email#email.com" placeholder="Your Email Address" name="email" id="email" type="email" tabindex="2" required="required">
</fieldset>
<fieldset>
<input value="123123123" placeholder="Your Phone Number (optional)" type="tel" tabindex="3">
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." tabindex="5" name="message" id="message" required="required">Damn</textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="submit_btn">Submit</button>
</fieldset>
</form>
You can create a method for example postNow.
methods: {
postNow() {
const link = "https://formspree.io/sheabathandbody#mail.com"
var data = new FormData();
data.append('_replyto',this.email)
data.append('message',this.message)
this.axios.post(link,data , {
headers: {
'Accept': 'application/json',
},
// body: data,
}).then(res =>{
console.log("response ===" ,res)
this.email = "" ;this.message=""; //don't forget to create your data
}).catch(err =>{
console.log(err)
});
}
},
And in your template you can use the simple HTML form with few tweaks ofc,
<form #submit.prevent="postNow" method="POST" >
<label>
Your email:
<input type="email" name="_replyto" v-model="email" />
</label>
<label>
Your message:
<textarea name="message" v-model="message"></textarea>
</label>
<button type="submit">Send</button>
</form>

Validate form, check if user exists, register them. All with Ajax

My javascript is inside an html file called register.html.
The user submits the form. This should then trigger the $('input[name="createacc"]').click(function (e) AJAX then sends those 4 variables to checkuser.php. Checkuser.php should then check to see if the username exists. If it does exist, it should echo 0. If it does not exists, it should echo 1. Register.html then checks to see what checkuser.php echoed. If the echo was "0" then, then an alert box should appear saying username unavailable. If the echo was "1" or anything else, register.html should run $("#registerform").submit(); which then does the php script. This should all happen without leaving the register.html page.
I check chrome's built in debugger and I see that if the account exists checkuser.php writes back 0 and if the account doesn't it writes back 1. But for some reason nothing else happens. The account does not register nor do I get an alert box saying the username is unavailable
here is my register.html
<form ata-parsley-validate name="registerform" id="registerform" action="register.php" method="post">
<p>
<label for="firstname">First Name:</label>
<input name="firstname" id="firstname" maxlength="32" type="text" placeholder="Optional" />
</p>
<p>
<label for="username" id="usernameText">Username:</label>
<input data-parsley-pattern="^[A-Za-z0-9_]{3,15}$" data-parsley-length="[3, 15]" name="username" id="username" maxlength="32" type="text" data-parsley-error-message="Username needs to be between 3 and 15 characters. Case sensitive. No special characters allowed." required/>
</p>
<p>
<label for="password1">Password:</label>
<input name="password1" id="password1" data-parsley-pattern="^[A-Za-z0-9_-]{5,25}$" data-parsley-length="[5, 25]" type="password" data-parsley-equalto="#password2" data-parsley-error-message="Passwords must match. Needs to be between 5 and 25 characters. Case sensitive. No special characters allowed." required/>
</p>
<p>
<label for="password2">Confirm Your Password:</label>
<input name="password2" id="password2" data-parsley-length="[5, 25]" data-parsley-error-message="Passwords must match. Needs to be between 5 and 25 characters. Case sensitive. No special characters allowed." data-parsley-pattern="^[A-Za-z0-9_-]{5,25}$" type="password" data-parsley-equalto="#password1" required/>
</p>
<p>
<label for="email">E-Mail:</label>
<input data-parsley-trigger="change" name="email" id="email" maxlength="1024" type="email" required/>
</p>
<p>
<input type="submit" id="submit" class="submit" name="createacc" value="Register" />
</p>
</form>
Here is my javascript
<script>
$(document).ready(function () {
$('input[name="createacc"]').click(function (e) {
var username = $('input[name="username"]').val();
var firstname = $('input[name="firstname"]').val();
var password1 = $('input[name="password1"]').val();
var email = $('input[name="email"]').val();
e.preventDefault();
$.ajax({
type: 'POST',
data: {
username: username,
firstname: firstname,
password1: password1,
email: email
},
url: 'checkuser.php',
success: function (data) { //Receives the data from the php code
if (data === "0") {
alert("Username Unavailable");
} else {
$("#registerform").submit();
alert("Account successfuly created");
}
},
error: function (xhr, err) {
console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
console.log("responseText: " + xhr.responseText);
}
});
});
});
</script>
Update - I have fixed parts of my code through the help of others below me. My only issue now is that $("#registerform").submit(); doesn't do anything
You are trying to return and JSON not setting
header('Content-type: application/json');
Decide whether you want to pass plaintext or json. Your string might be now "0", not 0
Try
if (data === '"0"') {
I think the problem is in your success.you have written If it does exist, it should echo 0. If it does not exists, it should echo 1.you should use:
success: function (data) { //Receives the data from the php code
if (data == '"0"') { //register if user exists.
$("#registerform").submit();
} else {
alert("Username Unavailable");
}

iFrame passing information to Ajax and triggering the submit button in the Ajax

I'm having a problem where the Ajax is not triggering the respected event.
I have two forms, one visible and one hidden.
In the visible form, the user can enter an email address.
When the user clicks the submit button of the visible form, the default submit is prevented, and through Ajax the email is validated.
If the email address is not valid, an error message will appear.
If the email address IS valid, the submit button of the hidden form should be clicked using JS (in the ajax-success function).
Here is more code for reference:
HTML
Visible Form
<form accept-charset="utf-8" id="contactForm1" style="margin-top:;" action="https://app.getresponse.com/add_contact_webform.html?u=IzDa" method="post">
<input class="wf-input wf-req wf-valid__email" type="text" name="email" data-placeholder="yes" id="email" value="Enter Your Email Here"
onfocus="if (this.value == 'Enter Your Email Here') {this.value = '';}"
onblur="if (this.value == '') {this.value = 'Enter Your Email Here';}"
style="margin-top:0px;" />
<br />
<input type="submit" class="wf-button" name="submit1" value=" " style="display:inline !important; margin-top:-10px !important;" />
</form>
Hidden Form
<form method="post" id="aweber" class="af-form-wrapper" action="http://www.aweber.com/scripts/addlead.pl">
<div style="display:none;">
<input type="hidden" name="meta_web_form_id" value="947846900" />
<input type="hidden" name="meta_split_id" value="" />
<input type="hidden" name="listname" value="awlist3599001" />
<input type="hidden" name="redirect" value="http://www.aweber.com/thankyou.htm?m=default" id="redirect_37ecf313df3b6f27b92c34c2c00ef203" />
<input type="hidden" name="meta_adtracking" value="ibb_test" />
<input type="hidden" name="meta_message" value="1" />
<input type="hidden" name="meta_required" value="email" />
<input type="hidden" name="meta_tooltip" value="" />
</div>
<div id="af-form-947846900" class="af-form"><div id="af-body-947846900" class="af-body af-standards">
<div class="af-element">
<label class="previewLabel" for="awf_field-66127140">Email: </label>
<div class="af-textWrap"><input class="text" id="awf_field-66127140" type="text" name="email" value="" />
</div><div class="af-clear"></div>
</div>
<div class="af-element buttonContainer">
<input name="submitaw" id="submitaw" class="submitaw" type="submit" value="Submit" tabindex="501" />
<div class="af-clear"></div>
</div>
</div>
</div>
<div style="display:none;"><img src="http://forms.aweber.com/form/displays.htm?id=nCzsHCxsnAwM" alt="" /></div>
</form>
JS
Ajax for visible form
$('#contactForm1').click(function(e) {
e.preventDefault();
var email = $('#email').val();
var self = this;
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'check.php',
data: {
email: email
},
success: function (data) {
if (data.status == 'success') {
self.submit();
} else {
alert('The e-mail address entered is not valid.');
}
}
});
});
So here's how the scenario would be:
User enters email address, and clicks the submit button.
Ajax-call checks whether it's a valid email.
If the email is valid, the Ajax success function of the visible form
first sets the email value of the hidden form
and then triggers the submit button of the hidden form
As said before, STEP 3 isn't working.
use complete instead success
$('#contactForm1').click(function(e) {
e.preventDefault();
var email = $('#email').val();
var self = this;
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'check.php',
data: {
email: email
},
complete: function(data) {
if (data.status == 'success') {
self.submit();
} else {
alert('The e-mail address entered is not valid.');
}
}
});
});

Sending values to the action script continuously. How to do that?

I want to repeatedly send values of username and password to the php script. How do I do this ? Like to send the values to the action script, we use submit button but how can I send the values automatically to the script and that too continuously ?
<form method="post" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
Using the jQuery form plugin you can do the following:
setInterval(function() {
$('form').ajaxSubmit();
}, 1000);
Another solution is to target the form to an iframe so if you submit the form, it doesn't reload the page:
HTML:
<form id="myform" method="post" action="processor.php" target="frm">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
<iframe name="frm" id="frm"></iframe>
JS:
var form = document.getElementById('myform');
setInterval(function() {
form.submit();
}, 1000);
try something like this
JAVASCRIPT
<script language=javascript>
var int=self.setInterval(function(){send_data()},1000);
function send_data()
{
document.getElementById('my_form').submit()
}
</script>
HTML
<form method="post" id="my_form" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
</form>
<form id="myform" method="post" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
<script type="text/javascript">
var count=100,i=0;
for(i=0;i<count;i++) {
document.getElementById('myform').submit();
}
</script>
This will submit the form 100 times
Use Ajax, it's really easy with jQuery. To send the form data to the processor.php script:
var sendForm = function () {
$.ajax({
type: 'post',
url: 'processor.php',
dataType: 'JSON',
data: {
username: $('#username').val(),
password: $('#password').val()
},
success: function (data) {
// do something with the answer from server?
},
error: function (data) {
// handle error
}
});
}
So, sendForm is a function that sends the form data to the server. Now, wee need to set a timer that will invoke it repeatedly:
window.setInterval(sendForm, 1000); // sends form data every 1000 ms
You may you $.post or $.get or $.ajax request repeatedly to send continuous request.
$(document).ready(function(){
setInterval(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+username+"&password="+password;
$.post('login.php',dataString,function(response){
//your code what you want to do of response
alert(response);
});
}, 1000);
});
and html code is like following
<form method="post" action="processor.php">
<input type="username" value="suhail" id="username"/>
<input type="password" value="secret_code" id="password"/>
<input type="submit" />
</form>
This is a full HTML file doing what you want, read the comments.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form method="post" action="processor.php">
<input type="username" id="username" value="suhail" />
<input type="password" id="password" value="secret_code" />
<input type="submit" />
</form>
<script>
function send_request(username, password) {
var dataString = 'username='+username+"&password="+password;
$.post('login.php',dataString,function(response){
// You can check if the login is success/fail here
console.log(response);
// Send the request again, this will create an infinity loop
send_request(username, password);
});
}
// Start sending request
send_request($('#username').val(), $('#password').val());
</script>
Try this,
JS:
$(document).ready(function(){
var int=self.setInterval(function(){statuscheck()},1000);
function statuscheck()
{
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type:"post",
url:"processor.php",
dataType: "html",
cache:false,
data:"&username="+username+"&password="+password,
success:function(response){
alert(response);
}
});
}
});
HTML:
<form method="post" action="processor.php">
<input type="username" value="suhail" id="username"/>
<input type="password" value="secret_code" id="password"/>
<input type="submit" />
</form>

Categories

Resources