I am submitting a form in ajax. I used certain validation for input format like time and phone no validation etc. But it submits the form after validation. I did use preventDefault() to prevent form submission but it doesn't work.
$("#sche_inter_form").submit(function(e) {
if ($("#inter_name").val() === "") {
$("#inter_name").css({
"border-bottom": " 1px solid #dd4b39"
});
e.preventDefault();
}
if (($("#inter_date").val() === "") || (!(/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/).test($("#inter_date").val()))) {
$("#inter_date").css({
"border-bottom": " 1px solid #dd4b39"
});
e.preventDefault();
}
if (($("#inter_hr").val() === "") || (!(/^((0?[1-9])|(1[0-2]))(:|\s)([0-5][0-9])$/).test($("#inter_hr").val()))) {
$("#inter_hr").css({
"border-bottom": " 1px solid #dd4b39"
});
e.preventDefault();
}
if ($("#inter_mr").val() === "") {
$("#inter_mr").css({
"border-bottom": " 1px solid #dd4b39"
});
e.preventDefault();
}
e.preventDefault();
var candidate_id = $('#candidate_id').val();
var profile_id = $('#profile_id').val();
var date, time, inter_name, meridian, dataString;
var inter_name = $('#inter_name').val();
var date = $('#inter_date').val();
var time = $('#inter_hr').val();
var meridian = $('#inter_mr').val();
var dataString = 'inter_name=' + inter_name + '&inter_date=' + date + '&inter_time=' + time + '&inter_meridian=' + meridian + '&candidate_id=' + candidate_id + '&profile_id=' + profile_id;
$.ajax({
type: "POST",
url: "/schedule_interview",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: dataString,
cache: false,
success: function(data) {
alert("Interview Scheduled Successfully");
}
});
});
This is my form
<form id = "sche_inter_form">
<div class = "form-group">
<input type = "text" id = "inter_name" placeholder = "Name of interviewer" required></input>
</div>
<div class = "form-group">
<b><p id = "schedule_text">Interview Schedule session</p></b>
</div>
<input type="hidden" id="candidate_id"/>
<input type="hidden" id="profile_id"/>
<div class = "form-group form-inline">
<input type = "text" id = "inter_date" placeholder = "dd/mm/yyyy" required></input>
<input type = "text" id = "inter_hr" placeholder = "hh:mm" required></input>
<input type = "text" id = "inter_mr" placeholder = "AM/PM" required></input>
</div>
<div class = "form-group">
<input type = "submit" class ="btn btn-primary" value = "Schedule"></input>
</div>
</form>
You have to prevent default behavior of submit button.
Try with below code
$("#sche_inter_form").submit(function(e){
replace with
$(".btn-primary").click(function(e){
You can add 'id' attribute to your submit button and use in above code instead of 'class'.
inputs don't need closing tag. Remove </input> from your html and use e.preventDefault(); only once. If you want to prevent form submit in some condition use return false
$("#sche_inter_form").submit(function(e) {
e.preventDefault();
if ($("#inter_name").val() === "") {
$("#inter_name").css({
"border-bottom": " 1px solid #dd4b39"
});
}
if (($("#inter_date").val() === "") || (!(/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/).test($("#inter_date").val()))) {
$("#inter_date").css({
"border-bottom": " 1px solid #dd4b39"
});
}
if (($("#inter_hr").val() === "") || (!(/^((0?[1-9])|(1[0-2]))(:|\s)([0-5][0-9])$/).test($("#inter_hr").val()))) {
$("#inter_hr").css({
"border-bottom": " 1px solid #dd4b39"
});
}
if ($("#inter_mr").val() === "") {
$("#inter_mr").css({
"border-bottom": " 1px solid #dd4b39"
});
}
var candidate_id = $('#candidate_id').val();
var profile_id = $('#profile_id').val();
var date, time, inter_name, meridian, dataString;
var inter_name = $('#inter_name').val();
var date = $('#inter_date').val();
var time = $('#inter_hr').val();
var meridian = $('#inter_mr').val();
var dataString = 'inter_name=' + inter_name + '&inter_date=' + date + '&inter_time=' + time + '&inter_meridian=' + meridian + '&candidate_id=' + candidate_id + '&profile_id=' + profile_id;
$.ajax({
type: "POST",
url: "/schedule_interview",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: dataString,
cache: false,
success: function(data) {
alert("Interview Scheduled Successfully");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="sche_inter_form">
<div class="form-group">
<input type="text" id="inter_name" placeholder="Name of interviewer" required>
</div>
<div class="form-group">
<b><p id = "schedule_text">Interview Schedule session</p></b>
</div>
<input type="hidden" id="candidate_id" />
<input type="hidden" id="profile_id" />
<div class="form-group form-inline">
<input type="text" id="inter_date" placeholder="dd/mm/yyyy" required>
<input type="text" id="inter_hr" placeholder="hh:mm" required>
<input type="text" id="inter_mr" placeholder="AM/PM" required>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Schedule">
</div>
</form>
Related
I have a dropdown where I use ajax to fetch the select options.
<form asp-action="AdresWijzigen">
<input asp-for="KlantId" hidden />
<input asp-for="AdresType" hidden />
<input asp-for="OudStraat" hidden />
<input asp-for="OudHuisNummer" hidden />
<input asp-for="OudBus" hidden />
<input asp-for="OudPlaatsId" hidden />
<input asp-for="OudPlaatsNaam" hidden />
<div>
<label asp-for="NieuwStraat"></label>
<span asp-validation-for="NieuwStraat" class="text-danger"></span>
<input asp-for="NieuwStraat" />
</div>
<div>
<label asp-for="NieuwHuisNummer"></label>
<span asp-validation-for="NieuwHuisNummer" class="text-danger"></span>
<input asp-for="NieuwHuisNummer" />
</div>
<div>
<label asp-for="NieuwBus"></label>
<input asp-for="NieuwBus" />
</div>
<div>
<label>Postcode</label>
<input type="text" id="postcodeInput" name="postcodeInput" placeholder="Geef een postcode in" />
<input type="button" id="zoekGemeente" name="zoekGemeente" value="🔍" />
<p id="errorPostcode" class="text-danger" style="display:none"></p>
<div id="gemeenteSelect"></div>
</div>
<div>
<input type="submit" value="Adres wijzigen" class="btn btn-primary" />
</div>
</form>
<script>
$("#zoekGemeente").click(function () {
var url = "#Url.Action("FetchGemeenteObvPostcode", "Klant")";
var data = $("#postcodeInput").val();
var $postcodeControl = /^\d{4}$/;
if (data.match($postcodeControl)) {
$("#errorPostcode").css('display', 'none');
$.ajax({
type: "POST",
url: url,
dataType: "JSON",
data: { postcode: $("#postcodeInput").val() },
success: function (data) {
if (data.length < 1) {
$("#errorPostcode").css('display', 'inline-block');
$("#errorPostcode").text("Geen gemeente gevonden voor postcode " + $("#postcodeInput").val());
$("#gemeenteSelect").empty();
} else {
var g = '<select asp-for="NieuwPlaatsId">';
for (var i = 0; i < data.length; i++) {
g += '<option value="' + data[i].plaatsId + '">' + data[i].plaatsNaam + '</option>';
}
g += '</select>';
$("#gemeenteSelect").html(g);
}
}
})
} else {
$("#errorPostcode").css('display', 'inline-block');
$("#errorPostcode").text("Geldige postcode moet uit 4 cijfers bestaan");
$("#gemeenteSelect").empty();
}
})
</script>
[HttpPost]
public JsonResult FetchGemeenteObvPostcode(string postcode)
{
var gemeentes = klantenRepository.GetPlaatsenByPostcodes(postcode);
return Json(gemeentes);
}
//Valideer viewModel, als valid redirect naar WijzigenAdresBevestigen()
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AdresWijzigen(AdresWijzigenViewModel viewModel)
{
if (ModelState.IsValid)
{
return RedirectToAction(nameof(WijzigingAdresBevestigen),viewModel);
}
else
{
List<Plaats> plaatsen = new List<Plaats>();
plaatsen = _context.Plaatsen.ToList();
ViewData["NieuwAdres"] = plaatsen;
return View(viewModel);
}
}
// Redirect to page that requests confirmation
public async Task<IActionResult> WijzigingAdresBevestigen(AdresWijzigenViewModel viewModel)
{
var nieuwPlaats = await _context.Plaatsen.FindAsync(viewModel.NieuwPlaatsId);
Console.WriteLine(nieuwPlaats);
ViewData["NieuwPlaatsNaam"] = nieuwPlaats.PlaatsNaam;
return View(viewModel);
}
The fetch works fine, and the html select option value gets filled with the correct id's. However, when I submit the form, the option value that is filled in using ajax does not get filled into the model that is passed to the controller.
ViewData["NieuwPlaatsNaam"] = nieuwPlaats.PlaatsNaam;
^ this is the line that returns a "Object reference not set to an instance of an object" error on submit
Am I missing something?
Solved by adding the <select asp-for=...> tag in the HTML directly, as it seems that the asp-for doesn't work when added using Javascript (as pointed out by #PeterB in the comments).
<div>
<label>Postcode</label>
<input type="text" id="postcodeInput" name="postcodeInput" placeholder="Geef een postcode in" />
<input type="button" id="zoekGemeente" name="zoekGemeente" value="🔍" />
<p id="errorPostcode" class="text-danger" style="display:none"></p>
**<select id="gemeenteSelect" asp-for="NieuwPlaatsId" style="display:none"></select>**
</div>
....
if (data.length < 1) {
$("#errorPostcode").css('display', 'inline-block');
$("#errorPostcode").text("Geen gemeente gevonden voor postcode " + $("#postcodeInput").val());
$("#gemeenteSelect").css('display', 'none');
} else {
var g = '';
for (var i = 0; i < data.length; i++) {
g += '<option value="' + data[i].plaatsId + '">' + data[i].plaatsNaam + '</option>';
}
$("#gemeenteSelect").css('display', 'inline-block');
$("#gemeenteSelect").append(g);
}
....
I'm trying to do validation for my form. I want to make it so if any item with class "required" is empty the form won't be submitted. Right now this is the case only for the first item in the class. For example, I have 3 inputs with class "required" - name, surname, address. The form is sent when I fill in only name, but surname and address are still empty.
Similar problem with $('.required').addClass('error'); - it should have a red border only in the empty field, but it has it on all the fields with "required" class. Is there a way to fix it?
$(function() {
$('#form').on('submit', function(e) {
e.preventDefault();
if ($('.required').val() === '') {
$('#add').addClass('error');
$('.required').addClass('error');
$('#text').html("Fill in the form.");;
} else {
$.ajax({
type: "post",
url: 'php/php.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function() {
document.getElementById("text").innerHTML = "success";
document.getElementById("add").style.border = "2px solid green";
},
error: function() {
document.getElementById("text").innerHTML = "error";
document.getElementById("add").style.border = "2px solid red";
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p id="text">Placeholder</p>
<form id="form" method="POST" action="php/php.php">
<input type="text" name="Name" id="name" class="required"><br>
<ol>
<li>
<input type="number" name="x1" class="required">
<input type="text" name="xa1" class="required">
<be>
</li>
<li>
<input type="number" name="x2">
<input type="text" name="xa2"><br>
</li>
<input type="submit" name="Add" id="add">
</form>
$('.required') return a collection of jQuery DOM element, so you need to loop through this collection. Try this solution
$(function () {
$('#form').on('submit', function (e) {
e.preventDefault();
let alllfine = true;
$('.required').each(function () {
if ($(this).val() == '') {
$('#text').html("Fill in the form.");
$('#add').addClass('error');
$(this).addClass('error');
$(this).css('border', '1px solid red');
alllfine = false;
} else {
$(this).css('border', '1px solid black');
}
})
if (alllfine) {
$.ajax({
type: "post",
url: 'php/php.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function () {
document.getElementById("text").innerHTML = "success";
document.getElementById("add").style.border = "2px solid green";
},
error: function () {
document.getElementById("text").innerHTML = "error";
document.getElementById("add").style.border = "2px solid red";
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p id="text">Placeholder</p>
<form id="form" method="POST" action="php/php.php">
<input type="text" name="Name" id="name" class="required"><br>
<ol>
<li>
<input type="number" name="x1" class="required">
<input type="text" name="xa1" class="required">
<be>
</li>
<li>
<input type="number" name="x2">
<input type="text" name="xa2"><br>
</li>
<input type="submit" name="Add" id="add">
</form>
You need to test each of the fields returned
const $req = $('.required');
const valid = $req.filter(function() {
const thisValid = this.value.trim() !== "";
$(this).toggleClass('error',!thisValid);
return thisValid }).length === $req.length;
if (valid) {
// ajax here
}
But why not just use required attribute?
$(function() {
$('#form').on('submit', function(e) {
// we will only see this if required fields are filled in
console.log("ajax here")
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p id="text">Placeholder</p>
<form id="form" method="POST" action="php/php.php">
<input type="text" name="Name" id="name" class="required"><br>
<ol>
<li>
<input type="number" name="x1" required>
<input type="text" name="xa1" required>
</li>
<li>
<input type="number" name="x2">
<input type="text" name="xa2"><br>
</li>
</ol>
<input type="submit" name="Add" id="add">
</form>
I am trying to implement a Contact from with custom Captcha using PHPmailer. The contact form works fine. The PHPmailer works fine as well. To avoid a lot of spam letters, I decided to implement custom Captcha, the problem is that the emails go anyway captcha is correct or incorrect.
<h4 class="sent-notification"></h4>
<form id="myForm">
<p>
<label>Name<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="name" type="text" name="name" required>
</p>
<p>
<label>Company<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="subject" type="text" name="company" required>
</p>
<p>
<label>Email<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="email" type="email" name="email" required>
</p>
<p class="full">
<label>Message<span style="color:#ff0000; margin-left:5px;">*</span></label>
<textarea id="body" name="message" rows="5" required></textarea>
</p>
<div class="contain">
<input type="text" id="capt" readonly="readonly">
<div id="refresh"> <img src="assets/img/icons/refresh.png" alt="refresh" width="50px" onclick="cap()"></div>
<input type="text" id="textinput" placeholder="Refresh to type Captcha" required>
<button onclick="validcap()">Check</button>
</div>
<p>
<button class="full" onclick="sendEmail()" value="Send An Email">Submit</button>
</p>
</form>
Script for PHPmailer
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
var textinput = $("#textinput");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body) && isNotEmpty(textinput)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val(),
textinput: textinput.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('.sent-notification').text("Message Sent Successfully");
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() == "") {
caller.css('border', '1px solid red');
return false;
} else
caller.css('border', '');
return true;
}
</script>
Script for Captcha
<script type="text/javascript">
function cap() {
var alpha=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V'
,'W','X','Y','Z','1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var a=alpha[Math.floor(Math.random()*62)];
var b=alpha[Math.floor(Math.random()*62)];
var c=alpha[Math.floor(Math.random()*62)];
var d=alpha[Math.floor(Math.random()*62)];
var e=alpha[Math.floor(Math.random()*62)];
var f=alpha[Math.floor(Math.random()*62)];
var sum=a + b + c + d + e + f;
document.getElementById("capt").value=sum;
}
function validcap() {
var string1 = document.getElementById('capt').value;
var string2 = document.getElementById('textinput').value;
if (string1 == string2){
alert("Form is validated Succesfully");
return true;
}
else {
alert("Please enter a valid captcha");
return false;
}
}
</script>
I want to send an email after submitting a form in Laravel. For complete the send mail process Laravel needs sometimes(5-10 seconds). In that duration (5-10 seconds) I want to show a loader gif. While the mail is send the gif will disappear and a successful message will show.
Here is my form
<div class="book-appointment">
<img src="images/loader.gif" id="gif" style="display: block; margin: 0 auto; width: 100px; visibility: hidden;">
<h2>Make an appointment</h2>
<form action="#" method="post" style="margin-top: 3rem;">
<div class="left-agileits-w3layouts same">
<div class="gaps">
<p>Patient Name</p>
<input type="text" name="Patient Name" placeholder="" required=""/>
</div>
<div class="gaps">
<p>Phone Number</p>
<input type="text" name="Number" placeholder="" required=""/>
</div>
<div class="gaps">
<p>Email</p>
<input type="email" name="email" placeholder="" required="" />
</div>
<div class="gaps">
<p>Age</p>
<input type="text" name="age" placeholder="" required="" />
</div>
</div>
<div class="right-agileinfo same">
<div class="gaps">
<p>Select Date</p>
<input id="datepicker1" name="Text" type="text" value="" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = 'yy/mm/dd';}" required="">
</div>
<div class="gaps">
<p>Time</p>
<input type="text" id="timepicker" name="Time" class="timepicker form-control" value="">
</div>
<div class="gaps">
<p>Department</p>
<select class="form-control">
<option></option>
<option>Cardiology</option>
<option>Ophthalmology</option>
<option>Neurology</option>
<option>Psychology</option>
<option>Dermatology</option>
</select>
</div>
<div class="gaps">
<p>Gender</p>
<select class="form-control">
<option></option>
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
<div class="clear"></div>
<input type="submit" value="Make an appointment">
</form>
</div>
My script
$('#add').click(function(event){
$('#gif').css('visibility', 'visible');
var patient_name = $('#patient_name').val();
var patient_number = $('#patient_number').val();
var patient_email = $('#patient_email').val();
var patient_age = $('#patient_age').val();
var patient_gender = $('#patient_gender').find(":selected").val();
var service_id = $('#service_id_search').find(":selected").val();
var schedule_time_id = $('#schedule_time_id').find(":selected").val();
var date = $('#datepicker1').val();
if(patient_name == '' || patient_number == '' || patient_email == '' || patient_age == '' || patient_gender == '' || service_id == '' || schedule_time_id == '' || date == '')
{
alert('Empty input field exist');
}
else if(isNaN(patient_number))
{
alert('Please insert numbers in Patient Number field');
}
else if(isNaN(patient_age))
{
alert('Please insert numbers in Age field');
}
else
{
$.get( 'confirm_appointment', {'patient_name': patient_name, 'patient_number': patient_number, 'patient_email': patient_email, 'patient_age': patient_age, 'patient_gender': patient_gender, 'service_id': service_id, 'schedule_time_id': schedule_time_id, 'date': date, '_token':$('input[name=_token]').val()}, function( data )
{
// console.log(data);
$('#exampleModal .bg-agile .book-appointment h2').remove();
$('#exampleModal .bg-agile .book-appointment form').remove();
trHTML = '';
if(data > 0)
{
trHTML += "<h2> Your appointment is successfully submitted </h2>";
}
else
{
trHTML += "<h2> No </h2>";
}
trHTML += "<center><a href='/'><button class='btn btn-secondary btn-lg' style='padding: 16px 20px 20px 20px; color: #fff; margin-top:20px;'>Go Back to Homepage</button></a></center>";
$('#exampleModal .bg-agile .book-appointment').append(trHTML);
// console.log(data);
// $("#report").load(location.href + " #report");
});
}
});
I have already see this article [Show loading gif after clicking form submit using jQuery but not working...
Anybody help please ?
Showing a div while sending an ajax request, You can use ajaxStop() and ajaxStart() together. here is an example.
var $loading = $('#yourloadingdiv').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
Hope this helps.
you could use in this way
//start actions
$('#your-loader').show();
$.post(endpoint, options, function(response){
$('#your-loader').hide();
}).fail(function(){
$('#your-loader').hide();
});
Add id both form and image.
Now inside javascript $('#add').click(function(event){}) function do the following
$('#appointment-form').hide();
$('#gif').show();
While successfully send the mail, just hide the gif id lnside the ajax
$('#gif').hide();
Here is my full code
$('#add').click(function(event){
$('#appointment-form').hide();
$('#gif').css('margin-top','80px');
$('#gif').show();
var patient_name = $('#patient_name').val();
var patient_number = $('#patient_number').val();
var patient_email = $('#patient_email').val();
var patient_age = $('#patient_age').val();
var patient_gender = $('#patient_gender').find(":selected").val();
var service_id = $('#service_id_search').find(":selected").val();
var schedule_time_id = $('#schedule_time_id').find(":selected").val();
var date = $('#datepicker1').val();
if(patient_name == '' || patient_number == '' || patient_email == '' || patient_age == '' || patient_gender == '' || service_id == '' || schedule_time_id == '' || date == '')
{
alert('Empty input field exist');
}
else if(isNaN(patient_number))
{
alert('Please insert numbers in Patient Number field');
}
else if(isNaN(patient_age))
{
alert('Please insert numbers in Age field');
}
else
{
$.get( 'confirm_appointment', {'patient_name': patient_name, 'patient_number': patient_number, 'patient_email': patient_email, 'patient_age': patient_age, 'patient_gender': patient_gender, 'service_id': service_id, 'schedule_time_id': schedule_time_id, 'date': date, '_token':$('input[name=_token]').val()}, function( data )
{
$('#exampleModal .bg-agile .book-appointment h2').remove();
$('#exampleModal .bg-agile .book-appointment form').remove();
trHTML = '';
if(data > 0)
{
trHTML += "<h2 style:'margin-top'> Your appointment is successfully submitted </h2>";
}
else
{
trHTML += "<h2> No </h2>";
}
trHTML += "<center><a href='/'><button class='btn btn-secondary btn-lg' style='padding: 16px 20px 20px 20px; color: #fff; margin-top:20px;'>Go Back to Homepage</button></a></center>";
$('#gif').hide();
$('#exampleModal .bg-agile .book-appointment').append(trHTML);
});
}
});
Why is this script not loading at runtime or after I activate the submit button? I pulled it from a larger script and it seems it should run adhoc, but the variables do not appear in the console after pageload and the form does not submit. I have confirmed jquery is loaded properly before hand. Any one have any idea here?
edit: Moved the script to the bottom of the page, now it runs but Im receiving a
Uncaught SyntaxError: Unexpected token <
Not sure if I should make a new thread or leave this open, whats the preferred protocol?
$('form.sidebar-form').submit(function(e) {
e.preventDefault();
var $form = $(this);
var email = $.trim( $form.find('input[name="emailAddress"]').val() );
var $response = $form.find('.form-response');
// Loading Animation
var iter = 1;
var interval = 500;
var timeout, loading;
loading = function() {
var base = '• ';
var text = ' ';
for(var i = 1; i <= iter; i++) {
text = text + base;
}
$response.html(text);
if( iter === 3 ) {
iter = 0;
} else {
iter++;
}
timeout = setTimeout(loading, interval);
};
timeout = setTimeout(loading, interval);
// Check Email Address
var emailReg = /^([\w-\.\d\+]+#([\w-\d]+\.)+[\w-]{2,6})?$/;
if( !emailReg.test( email ) || email == '' ) {
clearTimeout( timeout );
$response.html('<span class="error">Please enter a valid email address</span>');
return;
}
// Eloqua Form Action
var elqAction = 'https://s1224369867.t.eloqua.com/e/f2';
// Post Data
var postData = {
elqFormName : 'var-gameserver-0315',
elqSiteId : 'hidden',
elqCampaignId : '',
emailAddress : email,
preferredLanquage : 'English',
singleCheckbox10 : 'on',
hiddenField : 'var-Gameserver'
};
$.ajax({
cache: false,
data: postData,
dataType: 'jsonp',
headers: { 'cache-control': 'no-cache' },
type: 'POST',
url: elqAction
}).always(function(data, status) {
clearTimeout( timeout );
if( status === 'success' || status === 'parsererror' ) {
$response.html('<span class="success">Thanks for your interest in var</span>');
} else {
$response.html('<span class="error">There was a problem communicating with our server</span>');
}
});
});
// HTML
<div class="sidebar">
<p>Please fill out the from below.</p>
<form class="sidebar-form">
<label for="emailAddress">Email Address<span style="">*</span></label>
<input id="field0" name="emailAddress" type="text" value="<eloqua type='emailfield' syntax='EmailAddress' />" />
<label for="firstName">First Name</label>
<input id="field1" name="firstName" type="text" value="<eloqua type='emailfield' syntax='FirstName' />" />
<label for="lastName">Last Name</label>
<input id="field2" name="lastName" type="text" value="<eloqua type='emailfield' syntax='LastName' />" />
<label for="title">Title</label>
<input id="field3" name="title" type="text" value="<eloqua type='emailfield' syntax='Title1' />" />
<label for="company">Company<span style="">*</span></label>
<input id="field4" name="company" type="text" value="<eloqua type='emailfield' syntax='Company' />" />
<label for="Phone">Phone<span style="">*</span></label>
<input id="field5" name="Phone" type="text" value="<eloqua type='emailfield' syntax='Business_Phone1' />" />
<input type="submit" value="Submit" class="form-submit" style="font-size: 100%; height: 24px; width: 100px" />
</form>
<div class="form-response"></div>
</div>
Have you tried putting you code in a
$( document ).ready(function() {
... your code here ...
});
It looks like the div with class .form-response is not in your form tag.
This line of code
var $response = $form.find('.form-response');
should be
var $response = $('.form-response');
Here is the JSBin.