Submitting form with Ajax - javascript

So I'm completely lost on how to submit a form with Ajax. I'm fairly new to Javascript and hopefully I'm not in over my head.
When I click submit on my form, nothing happens on my page, not in my SQL database where the info should be stored (double checked process form too).
Here's the code if anyone's willing to help:
Javascript:
$(document).ready(function() {
$('#form').submit(function() {
$.ajax({
url: "../process.php",
type: "post",
data: $(this).serialize()
});
});
});
HTML:
<form name="contact" method="post" action="" id="form">
<span id="input">
<input type="text" name="first" maxlength="50" size="30" title="First Name" class="textbox">
<input type="text" name="last" maxlength="80" size="30" title="Last Name" class="textbox">
<input type="text" name="email" maxlength="80" size="30" title="Email" class="textbox">
<textarea name="request" maxlength="1000" cols="25" rows="6" title="Request"></textarea>
</span>
<input type="submit" value="Submit" class="submit">
</form>

$('#form').submit(function(e) {
e.preventDefault(); //prevents the page from refreshing
var $this = $(this); // cache $(this) for later use
$.ajax({
url: "../process.php",
type: "post",
data: $this.serialize()
});
});
Also could be to do with the dataType property. Or various other things.

I use input type button instead submit button. I validate form field when user click button using click event.When validation pass then call ajax.
something like this,
<input type="button" value="Submit" class="submit">
jQuery(function(){
jQuery('.submit').click(function(){
if(validatemyform()){
//call ajax here
}
});
});

Related

Ajax submit redirects to new page (should not)

I can't figure out why I'm not able to properly do the ajax magic with this code. It just redirects to a new page as the server handle the request. I tried put a console.log("test"); in the jquery function, but it's never called. So I'm guessing the form submit never go through my ajax but directly to the server.
$("#startTest").submit(function(e)
{
console.log("test"); //This is never called
e.preventDefault();
$.ajax(
{
url : 'handler',
type: "POST",
data : $(this).serialize(),
success:function(data)
{
alert(data);
},
error: function()
{
alert("failure");
}
});
});
<form id="startTest" method="POST" action="handler">
<input type="hidden" name="answer" value="startTest">
<input type="text" name="firstname" value="" placeholder="Navn" id="navn" autocomplete="off"><br>
<input type="submit" name="submit" value="Start test">
</form>
Empty your form action. If your form has an action then when you submit your script follows that action. But you want to achieve that process via ajax so you don't fill action tag.Something like this
<form id="startTest" method="POST" action="">
<input type="hidden" name="answer" value="startTest">
<input type="text" name="firstname" value="" placeholder="Navn" id="navn" autocomplete="off"><br>
<input type="submit" name="submit" value="Start test">

Google spreadsheet website form jQuery script block the sending of

I have my form in html. I copied action, entry keys and hidden inputs from orginal Google Form.
<form id="Gform" role="form" action="https://docs.google.com/forms/d/MY-FORM-KEY/formResponse" method="POST" target="_self" onsubmit="">
<input type="text" pattern="^[a-zA-Z][a-zA-ZążźćśęółbńĄŻŹĆŃŚĘÓŁ ]{4,40}$" name="entry.1028663680" value="" id="entry.1028663680" dir="auto" title="What is Your city" class="form-control" placeholder="City" required>
<input type="text" pattern="^[a-zA-Z][a-zA-ZążźćśęółbńĄŻŹĆŃŚĘÓŁ ]{5,40}$" name="entry.1220908348" value="" id="entry.1220908348" dir="auto" title="Your complete name" class="form-control" placeholder="Your name" required>
<input type="tel" name="entry.623688995" value="" id="entry.623688995" dir="auto" title="" class="form-control" placeholder="phone" required>
<input type="email" name="entry.1564973803" value="" id="entry.1564973803" dir="auto" title="" class="form-control" placeholder="email" required>
<input type="hidden" name="entry.383122401" value="WEBSITE" id="entry.383122401" dir="auto" title="" class="form-control" placeholder="E-mail" required>
<input type="hidden" name="draftResponse" value="[,,"-9139933475238999509"]
">
<input type="hidden" name="pageHistory" value="0">
<input type="hidden" name="fbzx" value="-9139933475238999509">
<button type="submit" name="submit" id="sendData" class="btn btn-default">Submit</button>
</form>
I have te jQuery script, which display confirm:
<script type="text/javascript">
function sendContactForm(){
$("#Gform").fadeOut();
$("#form-container").append('<p class="confirmer">Thanks!<br>Your email was sent.</p>');
};
$('#Gform').submit(function () {
sendContactForm();
return false;
});
</script>
When i delete this script, form is sending, and save to google, but after click submit, I am redirecting to google "Thank You" page. I want to no redirect and display confirm just like in script. How to fix this problem ?
try to use AJAX to acomplish your task, when you will use asynchronous function, there won't be reloading page and you will send data behind the scene. In data object enter all input values, in done() and fail() functions define what to do when you recieve response. Good Luck:)
$('#formID').submit(function(e){
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/d/1PrgHQALlz0WrvwjhGpLrtIgD5aQ1x-8HrOubkxTLNKs/formResponse",
type: "POST",
data: {
'entry.111': $('#entry_111').val(),
'entry.222': $('#entry_222').val(),
// all data from form
}
}).done(function(data){
yourAction(data);
}).fail(function(data){
failAction(data);
});
});
Comment the return false in the code above:
$('#Gform').submit(function () {
sendContactForm();
//return false;
});
Or just delete this line.
What this is script is doing is: subscribing to the submit event and canceling it.
Do you want to do something else?

Submit 2 forms at once

I want to submit both forms after click 2nd form's submit button.
The hardest part is that action is pointing to a php file with which send an e-mail to the client. I do not want to get 2 e-mails.
Both form data should reach that php file at the same time.
this is 1st form:
<form class="generalForm" id="form1" action="reservationSend.php" method="post">
<input id="datepicker-example3" type="text" name="datepicker-example3" value="Check In">
<input id="datepicker-example2" type="text" name="check_out" value="Choose Out">
<select name="RoomType">
<option selected="selected" value="0">Room Type</option>
<option value="Deluxe">Deluxe</option>
<option value="Family">Executive</option>
<option value="Conference">Conference</option>
</select>
</form>
This is the second form:
<form id="form2" class="generalForm" method="post" action="reservationSend.php" onsubmit="return submitForm()">
<input type="text" name="name" placeholder="Your Name" />
<input type="text" name="email" placeholder="Your email" />
<input type="text" name="tp" placeholder="Your Phone Number" />
<input type="text" name="Country" placeholder="Your Country" />
<textarea name="message" placeholder="Your Message"></textarea>
<input type="submit" name="submit" value="submit">
</form>
My javascript, myjscript.js:
function submitForm() {
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
Example submitting a form with AJAX & jQuery.
$('#formID')
.on('submit', function(e){
e.preventDefault(); //disable default submit action
var postData = {
'name' : $('input[name="name"]').val(),
'email' : $('input[name="email"]').val()
//etcetera
};
$.post(
'reservationSend.php',
postData,
callBack(returnData){
doStuffWith(returnData);
//add callback functionality
},
'json' //or any other datatype. In this case postData is a JS object, which gets submitted as JSON string
);
//You could even trigger the submission of another form here:
$('#otherForm')
.trigger('submit');
//This will trigger the submission of #otherForm
});
$('#otherForm')
.on('submit', function(e){
e.preventDefault();
//logic for form submission.
});
You can find documentation on the jQuery AJAX methods here. You'll also find serialize() and serializeArray() there. 2 Methods which can turn a form into a JSON string.

Close pop up form once submitted

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!');
}
});
});

Pass data to a FORM and auto submit it

The thing I'm trying to have is a JQuery/JavaScript code that will automatically pass some data from facebook to a form (basically the form doesn't need to be shown). so the first part is ready (the part that pulls the data from facebook).
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxxxx', status: true, cookie: true, xfbml: true});
};
FB.Event.subscribe('auth.login', function(response) {
if (response.session) {
FB.api({
method: "fql.query",
query: "SELECT name,email FROM user WHERE uid = " + response.session.uid
}
Now i need to insert the name and the email to the inputs with name="name" and name="email" and auto submit the form.
Thanks in advance!
EDIT: here is the form:
<form method="post" class="af-form-wrapper" action="http://www.aweber.com/scripts/addlead.pl" >
<input type="hidden" name="meta_web_form_id" value="XXXXXXXX" />
<input type="hidden" name="listname" value="XXXXXX" />
<input type="hidden" name="meta_adtracking" value="XXXX" />
<input type="hidden" name="meta_message" value="1" />
<input id="awf_field-22176678" type="text" name="name" class="text" value="" tabindex="500" />
<input class="text" id="awf_field-22176679" type="text" name="email" value="" tabindex="501" />
<input name="submit" class="submit" type="submit" value="Submit" tabindex="502" />
<div class="af-clear">
</form>
EDIT 2: I need to do something like this just simplified with jQuery:
<?php
$formcode = '<form method="post" action="http://www.aweber.com/scripts/addlead.pl" >
<input type="hidden" name="meta_web_form_id" value="864136470" />
<input type="hidden" name="listname" value="fbu-ppv-mmoney1" />
<input type="hidden" name="meta_adtracking" value="FB_Ultralizer_PPV" />
<input type="hidden" name="meta_message" value="1" />
<input id="awf_field-22176678" type="text" name="name" class="text" value="" tabindex="500" />
<input class="text" id="awf_field-22176679" type="text" name="email" value="" tabindex="501" />
<input name="submit" class="submit" type="submit" value="Submit" tabindex="502" />
</form>
'; ?>
<script type="text/javascript">
customar_formcode="$formcode";
customar_formcode=customar_formcode.replace("{email}", user.email);
customar_formcode=customar_formcode.replace("{name}", user.name);
document.getElementById(\'form\').submit();
</script>
Use Jquery's POST to send the data without the need for the markup for a form and using auto submits:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
EDIT:
If you have already got the form setup in the DOM you should just fill it in with JavaScript and submit it with JavaScript
To change the input values use Jquery like so:
$('input[name$="name"]').val('value');
once all the inputs are set to how you want them you can submit the form using this:
if you have the ID form on your form then you can use code like
$('#form').submit();
Hope this helps
with jquery you can pass all data of form at once with something like:
var data = $(#formID).serialize();

Categories

Resources