How to check if submitting form with jQuery if successful? - javascript

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>

Related

Multiple file upload using jquery serialization works only at the second call

I experience a strange problem:
Form ajax call with multiple files and form values works perfect, but only on the second call. First call ends up the the success: function(result) "else" condition. Second call works perfect and sends all data to the php. So I hit the submit button once and it shows up an empty error box and I hit the submit button again and everything works perfect.
How is that possible and how to solve that?
UPDATE #1: Found workaround, but not the solution. It works when I put if (result==="") { $(".form-application").submit(); } below the success function. But thats very dirty! ... and it upload all files twice! :-(
PROBLEM SOLVED David Knipe provided the solution!! Thank you so much!!
JQUERY:
$(".form-application").submit(function(e) {
e.preventDefault();
$("#btnSubmit2").text("Please wait...");
$("#btnSubmit2").attr("disabled", true);
var files = $('#files')[0].files;
var form = $(this);
var error='';
var formData = new FormData(this);
grecaptcha.ready(function() {
grecaptcha.execute('6Le4Qb0UAAAAAHUPcsmVYIk7zc4XCsiBnf6oE-fP', {action: 'create_comment'}).then(function(token) {
$('<input>').attr({
type: 'hidden',
value: token,
name: 'token'
}).appendTo('form');
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
error += "Invalid " + count + " Image File"
}
else
{
formData.append("files[]", document.getElementById('files').files[count]);
}
}
if(error == '')
{
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: formData,
processData: false,
contentType: false,
success: function(result) {
if (result == "0") {
$("#btnSubmit2").text("Thank you!");
$("#btnSubmit2").attr("disabled", true);
$(".output_message").text("");
$(':input','.form-application')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
$(".output_message").append("<div class='alert alert-success alert-dismissible fade show' role='alert'>We have received your application!</div>");
} else {
$(".output_message").text("");
$(".output_message").append("<div class='alert alert-danger alert-dismissible fade show' role='alert'>"+result+"</div>");
$("#btnSubmit2").attr("disabled", false);
$("#btnSubmit2").text("try again");
}
}
});
}
else
{
alert(error);
}
});
});
return false;
});
HTML:
<form class="form-application" id="applicationform" method="post" action="https://<?PHP echo $_SERVER['HTTP_HOST']; ?>/include/process-application.php" enctype="multipart/form-data">
<input type="hidden" name="crsf" value="<?=$_SESSION['crsf']?>"/>
<input type="hidden" name="crsf-expire" value="<?=$_SESSION['crsf-expire']?>"/>
<div class="space40"></div>
<h6>Name</h6>
<input name="name" type="text" class="form-control" placeholder="Your Name">
<div class="space30"></div>
<h6>Email</h6>
<input name="email" type="text" class="form-control" placeholder="Your Email Address">
<div class="space30"></div>
<h6>Instagram Name</h6>
<input name="instagram" type="text" class="form-control" placeholder="Your Instagram Name">
<div class="space30"></div>
<h6>City & Country</h6>
<input name="from" type="text" class="form-control" placeholder="Where do you live?">
<div class="space30"></div>
<h6>Tell us more about you</h6>
<textarea name="message" class="form-control" rows="3" placeholder="Write some details about you, so we know you better."></textarea>
<div class="space30"></div>
<h6>Upload some photos of yourself</h6>
<div class="file-field">
<div class="btn btn-aqua">
<input name="files" id="files" type="file" accepts="image/*" multiple>
</div>
<div class="file-path-wrapper">
</div>
<div class="space20"></div>
</div>
</div>
<div class="col-12 text-center">
<button id="btnSubmit2" type="submit" class="btn btn-full-rounded btn-aqua">Submit Application</button>
<div class="space10"></div>
<span class="output_message"></span>
</div>
</form>
PHP Script /include/process-application.php
<?PHP
echo "0";
?>
OK, I think I've figured this out. $('<input>').attr(...); sets the token attribute on a new <input> element. But this is after var formData = new FormData(this);, so the token doesn't get included in formData. Then I guess you get an authentication error, and I guess it does the authentication before it even gets to the PHP part. It would just be a HTTP401 response with no body, hence "". But then, on the second attempt, the <input> has already been created with the correct token, and this ends up being used to authenticate.
Either keep onsubmit or action. Remove action from form tag, it will work

Add image uploading function inside this existing ajax code

My code here works fine except image uploading. It inserts all data in database .
<input type="file" name="image2" class="file" id="imgInp"/>
But after adding file type input in php it is showing
Notice: Undefined index: image2 in C:\xampp\htdocs\upload\submit.php on line 18
How can I add image uploading function in my existing code.
<div id="form-content">
<form method="post" id="reg-form" enctype="multipart/form-data" autocomplete="off">
<div class="form-group">
<input type="text" class="form-control" name="txt_fname" id="lname" placeholder="First Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_lname" id="lname" placeholder="Last Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_email" id="lname" placeholder="Your Mail" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="txt_contact" id="lname" placeholder="Contact No" required />
</div>
// here is the problem
<input type="file" name="image2" class="file" id="imgInp"/>
//here is the problem
<hr />
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
// submit form using $.ajax() method
$('#reg-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'submit.php',
type: 'POST',
data: $(this).serialize() // it will serialize the form data
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...'); });
});
</script>
submit.php
<?php
$con = mysqli_connect("localhost","root","","table" ) or die
( "unable to connect to internet");
include ("connect.php");
include ("functions.php");
if( $_POST ){
$fname = $_POST['txt_fname'];
$lname = $_POST['txt_lname'];
$email = $_POST['txt_email'];
$phno = $_POST['txt_contact'];
$post_image2 = $_FILES['image2']['name']; // this line shows error
$image_tmp2 = $_FILES['image2']['tmp_name'];
move_uploaded_file($image_tmp2,"images/$post_image2");
$insert =" insert into comments
(firstname,lastname,email,number,post_image) values('$fname','$lname','$email','$phno','$post_image2' ) ";
$run = mysqli_query($con,$insert);
?>
You can use FormData, also I suggest you can change the elements id of the form, now all of them have ('lname') Try this with your current:
In yout HTML, put an ID to your file input
<input type="file" name="image2" id="name="image2"" class="file" id="imgInp"/>
And change the id of the other input.
In your JavaScript:
var frmData = new FormData();
//for the input
frmData.append('image2', $('#image2')[0].files[0]);
//for all other input
$('#reg-form :input').each(function(){
if($(this).attr('id')!='image2' ){
frmData.append($(this).attr('name'), $(this).val() );
}
});
$.ajax( {
url: 'URLTOPOST',
type: 'POST',
data: frmData,
processData: false,
contentType: false
}).done(function( result ) {
//When done, maybe show success dialog from JSON
}).fail(function( result ) {
//When fail, maybe show an error dialog
}).always(function( result ) {
//always execute, for example hide loading screen
});
In your PHP code you can access the image with $_FILE and the input with $_POST
FormData() works on the modern browsers.If you want for older browser support use malsup/form plugin
Your Form
<form method="post" action="action.php" id="reg-form" enctype="multipart/form-data" autocomplete="off">
Javscript
<script type="text/javascript">
var frm = $('#reg-form');
frm.submit(function (ev) {
var ajaxData = new FormData(frm);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: ajaxData,
contentType: false,
cache: false,
processData:false,
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
In php extract($_POST) to get all input data and $_FILE for files

Form submission works with html but not javascript at the same time

I want to achieve that the user can search on the website and then filter his search results by clicking on a link (which triggers javascript) so he gets people instead of articles. In terms of database and PHP it works, but when I try to submit this code:
<form id="searchform" class="navbar-form" role="search" method="post" action="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="<?php if(isset($searchterm)) { echo $searchterm; } ?>">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
... with this code:
function submit() {
document.getElementById("searchform").submit();
}
this is what I use to communicate with my database initially, the url leads to a PHP function that returns the users. (works)
The following code only gets submitted with HTML button, but not with the link which will submit the form through javascript.
$("#searchform").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url : "/search/people",
data : form.serialize(),
dataType : "json",
success : function(data){
if(data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});
I get no results in the console when I press the link, BUT with the search bar button (html) I get something in the console.
So what I want to do is with the second link in this code:
<div class="list-group">
sounds
<a id="people" onclick="submit()" href="#" class="list-group-item">people</a>
requests
</div>
I will submit the javascript that part is not working.
Any suggestions on what I can try?
Here's a working example of your code:
https://jsfiddle.net/jonva/x99nxz0h/1/
It seems perfectly fine.
<form id="searchform" class="navbar-form" role="search" method="post" action="/echo/json">
abc
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
$("#searchform").submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "/echo/json",
data: form.serialize(),
dataType: "json",
success: function(data) {
if (data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});

How do I make a success alert appear after correct submission in javascript

I want to show the user a form sent correctly alert message with javascript using bootstraps built in alerts.
When I run the code I get the object array of the values (inspecting the page at console log). what I want to do is after it is sent, to display a success alert (if it is a success).
there is test4.sj which contains the javascript code and then there is main.php which is the code for the form.
The code that I have so far is in the snippet.
$('form.ajax').on('submit', function() {
var that = $(this),
type = that.attr('action'),
data = {};
that.find('[name]').each(function(index, value) {
//console.log(value);
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data);
/* $.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
})*/
return false;
})
<body>
<form method="post" class="ajax">
<div>
<input name="name" type="text" placeholder="Your name" required>
</div>
<div>
<input name="lName" type="text" placeholder="Your Last Name">
</div>
<div>
<textarea name="message" placeholder="Your Message"></textarea>
</div>
<input type="submit" value="Send">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</body>
Just add hidden alert panel and show it on AJAX success.
HTML:
<form method="post" class="ajax">
<div class="alert alert-success js-alert hidden" role="alert">
Form was successfully sent!
</div>
...
<div>
<input name="name" type="text" placeholder="Your name">
</div>
...
<button type="submit" class="btn js-btn">Send</button>
</form>
JS:
$('form').on('submit', function( event ) {
var $form = $( this );
event.preventDefault();
$('.js-alert').addClass('hidden');
$('.js-btn').button('loading');
$.ajax({
url: '/someurl',
type: 'POST',
data: $form.serialize(),
success: function(response){
$('.js-alert').removeClass('hidden');
$('.js-btn').button('reset');
}
});
});
Check the fiddle:
https://jsfiddle.net/xw63db57/1/
you can use ajax jqXHR status and statusCode and based up on that you can write the alert code
success(data, textStatus, jqXHR){
var statusCode = jqXHR.status;
var statusText = jqXHR.statusText;
}

Google Form Response not working from the website

I'm using a Google Form's value to integrate with my website where I want to submit the form and store data in google sheet as form responses. I'm using AJAX to redirect to another page instead of google form submit page. But whenever I'm trying to submit it's redirecting to my page accurately but datas are not saved in google sheet. Here are my codes,
<strong>Full Name</strong>
<input type="text" name="Fullname" class="form-control" id="Fullname" />
<strong>Email Address</strong>
<input type="text" name="Email" class="form-control" id="Email" />
<strong>Subject</strong>
<input type="text" name="Subject" class="form-control" id="Subject" />
<strong>Details</strong>
<textarea name="Details" rows="8" cols="0" class="form-control" id="Details"></textarea><br />
<button type="button" id="btnSubmit" class="btn btn-info" onclick="postContactToGoogle()">Submit</button>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function postContactToGoogle() {
var email = $('#Email').val();
var fullname = $('#FullName').val();
var subject = $('#Subject').val();
var details = $('#Details').val();
$.ajax({
url: "https://docs.google.com/forms/d/abcdefgh1234567xyz/formResponse",
data: {
"entry_805356472": fullname,
"entry_1998295708": email, "entry_785075795":
subject, "entry_934055676": details
},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
window.location.replace("Success.html");
},
200: function () {
window.location.replace("Success.html");
}
}
});
}
</script>
How can I save the data in google sheet? Am I missing something in my code? Need this help badly? Thanks.
You can directly copy the form from google view form page like shown in the demo, and then do the following changes in the AJAX call as shown below.
And now once you submit data it is visible in google forms, view responses.
$(function(){
$('input:submit').on('click', function(e){
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/d/18icZ41Cx3-n1iW7yTOZdiDx9a6mySWHOy9ryd1l59tM/formResponse",
data:$('form').serialize(),
type: "POST",
dataType: "xml",
crossDomain: true,
success: function(data){
//window.location.replace("youraddress");
//console.log(data);
},
error: function(data){
//console.log(data);
}
});
});
});
<div class="ss-form"><form action="https://docs.google.com/forms/d/18icZ41Cx3-n1iW7yTOZdiDx9a6mySWHOy9ryd1l59tM/formResponse" method="POST" id="ss-form" target="_self" onsubmit=""><ol role="list" class="ss-question-list" style="padding-left: 0">
<div class="ss-form-question errorbox-good" role="listitem">
<div dir="auto" class="ss-item ss-text"><div class="ss-form-entry">
<label class="ss-q-item-label" for="entry_1635584241"><div class="ss-q-title">What's your name
</div>
<div class="ss-q-help ss-secondary-text" dir="auto"></div></label>
<input type="text" name="entry.1635584241" value="" class="ss-q-short" id="entry_1635584241" dir="auto" aria-label="What's your name " title="">
<div class="error-message" id="1979924055_errorMessage"></div>
<div class="required-message">This is a required question</div>
</div></div></div>
<input type="hidden" name="draftResponse" value="[,,"182895015706156721"]
">
<input type="hidden" name="pageHistory" value="0">
<input type="hidden" name="fvv" value="0">
<input type="hidden" name="fbzx" value="182895015706156721">
<div class="ss-item ss-navigate"><table id="navigation-table"><tbody><tr><td class="ss-form-entry goog-inline-block" id="navigation-buttons" dir="ltr">
<input type="submit" name="submit" value="Submit" id="ss-submit" class="jfk-button jfk-button-action ">
</td>
</tr></tbody></table></div></ol></form></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
If you go to your form on Google and click on 'View Live Form', and then view source on the form, you'll see that the fields you want to upload have aname in the form entry.12345678; the id is in the form entry_12345678. You need to use the name value. Try this:
<script>
function postContactToGoogle() {
var email = $('#Email').val();
var fullname = $('#FullName').val();
var subject = $('#Subject').val();
var details = $('#Details').val();
$.ajax({
url: "https://docs.google.com/forms/d/abcdefgh1234567xyz/formResponse",
data: {
"entry.805356472": fullname,
"entry.1998295708": email,
"entry.785075795": subject,
"entry.934055676": details
},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
window.location.replace("Success.html");
},
200: function () {
window.location.replace("Success.html");
}
}
});
}
</script>

Categories

Resources