Jquery script not loading at runtime edit: unexpected token - javascript

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.

Related

Contact Form Sending message even if captcha not correct

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>

How to get value result from the same form?

How can I take value results from this form?
<form name="forma" method="post" action="index.php" id="dunja" >
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" />
</p>
</form>
And, JS is:
function sakupiPodatke(form){
var delovi = [];
var elementi = form.elements;
for(var i=0; i<elementi.length; i++){
var element = elementi[i];
var naziv = encodeURIComponent(element.name);
var vrednost = encodeURIComponent(element.value);
delovi.push(naziv + "=" + vrednost);
}
return delovi.join("&");
}
var teloZahteva = sakupiPodatke(document.forma);
console.log(teloZahteva);
also Php file is simple:
<?php
$ime = $_POST["txtIme"];
$email = $_POST["txtEmail"];
?>
so...my question is how to read variable "teloZahteva" from JS in console.log?
Your code is running when the page first loads, before the user has had a chance to fill in the form. So it will display empty values in the console.
Put the code in an event listener that runs when the user clicks the submit button.
document.getElementById("dunja").addEventListener("submit", function(e) {
e.preventDefault();
var teloZahteva = sakupiPodatke(e.target);
console.log(teloZahteva);
});
function sakupiPodatke(form) {
var delovi = [];
var elementi = form.elements;
for (var i = 0; i < elementi.length; i++) {
var element = elementi[i];
var naziv = encodeURIComponent(element.name);
var vrednost = encodeURIComponent(element.value);
delovi.push(naziv + "=" + vrednost);
}
return delovi.join("&");
}
<form name="forma" method="post" action="index.php" id="dunja">
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" />
</p>
</form>
This displays the form values in the console instead of sending the form to PHP.
After my code I wrote this code and it says:
Uncaught ReferenceError: createXHR is not defined
function formPost(url, form, callback){
var xhr = createXHR();
var data = sakupiPodatke(form);
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
var status = xhr.status;
if ((status >= 200 && status < 300) || status === 304){
callback(xhr.responseText);
}else{
alert("Greskica!");
}
}
};
xhr.send(data);;
}
function procesOdgovora(odgovor){
alert(odgovor);
}
formPost("index.php", document.forma, procesOdgovora);
<form name="forma" method="post" action="index.php" id="dunja" >
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" onclick="handleSubmit()" />
</p>
</form>
handleSubmit(){
var ime =getElementById('ime').value;
var mail =getElementById('mail').value;
}

JQuery HTML form validation still triggers email with blank entries

I have an HTML form with three mandatory fields in. I don't want the form to submit the AJAX call if they are empty.
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid = true;
if( $('input[name="Name"]').val() == '' || $('input[name="Email"]').val() == '' || $('input[name="Phone"]').val() == '') {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
<form id="contact" name="contact" method="post" action="">
<label for="Name">Name: *</label>
<input type="text" name="Name" id="name" />
<input name="robotest" type="hidden" value="" />
<label for="Position">Position:</label>
<input type="text" name="Position" id="position" />
<label for="Company">Company:</label>
<input type="text" name="Company" id="company" />
<label for="Address">Address:</label>
<input type="text" name="Address" id="address" />
<label for="Email">Email: *</label>
<input type="text" name="Email" id="email" />
<label for="Email">Phone number: *</label>
<input type="text" name="Phone" id="phone" />
<label for="Event_Subject">What is the subject of the event?:</label>
<input type="text" name="Event_Subject" id="subject" />
<label for="Event_Date">What is the date of the event?:</label>
<input type="text" name="Event_Date" id="date" />
<label for="Additional_info">Additional Information:</label>
<br />
<textarea name="Additional_info" rows="20" cols="20" id="info"></textarea>
<input id="formsubmitted" type="submit" name="submit" value="submit" class="submit-button" />
</form>
This does give the popup box if you try and fill it in empty, but I have received an email with all blank fields.
How is the user getting past the validation and managing to send the form through blank?
More than likely you've not popped in a preventDefault() in there, so the form is doing a normal (non-AJAX) post after your function ends. What's the method/action on your form? Perhaps there doesn't need to be an action at all?
Try this:
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
} else {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
As Jigar pointed out, you can shorten the code by assigning an initial value to the valid variable and removing else block:
var valid = false;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
}

need help with nested jquery function

Please find my code below. My problem is that I the inner jQuery.get() doesn't get executed. Could some one help me out with this?
jQuery(document).ready(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var zipCode = $("input#name").val();
if (zipCode == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var key = 'ac9c073a8e025308101307';
var noOfDays = 5;
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=' + zipCode + '&format=json&num_of_days=' + noOfDays + '&key=' + key;
alert(url);
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
}); }, 'jsonp')();
});
});
My html form looks like
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
I'd really appreciate any pointers.
Thanks!
The problem you are experiencing is that you dont do anything to stop your form from being submitted, thus it submits the form before it gets a chance to get the data from the worldweatheronline.com.
Change your click handler to be like this:
$(".button").click(function(event) {
event.preventDefault();
Here is my completed sample code that works the way you want it to:
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type='text/javascript'>
jQuery(document).ready(function() {
$('.error').hide();
$(".button").click(function(event) {
event.preventDefault();
// validate and process form here
$('.error').hide();
var zipCode = $("input#name").val();
if (zipCode == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var key = 'ac9c073a8e025308101307';
var noOfDays = 5;
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=' + zipCode + '&format=json&num_of_days=' + noOfDays + '&key=' + key;
alert('first'+url);
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ){
return false;
}
});
}, 'jsonp');
});
});
</script>
</head>
<body>
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
</body>
</html>
Turn on Fiddler or Firebug and watch the HTTP call go out. You'll see the HTTP error message there. Also, turn on your console in Chrome or Firefox to see a potential JavaScript error.
Part of the problem could be the extra set of parentheses after your .get() function call. You have:
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
}); }, 'jsonp')();
It should be:
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
});
}, 'jsonp');
Im going to go out on a limb and guess that (based on the url 'http://www.worldweatheronline.com/feed/weather.ashx?q=' ) that you are attempting to perform an AJAX request to an external site. This violates Same Domain Policy and will fail silently.

Hide/clear input field with prototype

I have the following script:
if (Object.isUndefined(Axent)) { var Axent = { } }
Axent.SelfLabeledInput = Class.create({
initialize: function() {
var labelSelector = arguments[0] || 'label';
$$(labelSelector).findAll(function(l) {return (l.readAttribute('for') !== null)}).each(function(l){
l.hide();
$(l.readAttribute('for'))._value = l.innerHTML;
if ($(l.readAttribute('for')).value.empty()) {
$(l.readAttribute('for')).value = $(l.readAttribute('for'))._value
}
$(l.readAttribute('for')).observe('blur',function(e){if(Event.element(e).value == '') Event.element(e).value = Event.element(e)._value;});
$(l.readAttribute('for')).observe('focus',function(e){if(Event.element(e).value == Event.element(e)._value) Event.element(e).value = '';});
});
}
});
And the following form :
<form name="comform" action="#" method="post" id="commentform">
<div class="input">
<p>
<label for="comment">Type your comment here...</label>
<textarea name="comment" id="comment" rows="8" cols="10" class="" ></textarea>
</p>
</div>
<div class="input">
<p>
<label for="author">Name (required)</label>
<input type="text" name="author" id="author" size="22" class=""/>
</p>
</div>
<div class="input">
<p>
<label for="email">Email (gravatar enabled) (required)</label>
<input type="text" name="email" id="email" size="22" class=""/>
</p>
</div>
<div class="input">
<p>
<label for="url">Website (optional)</label>
<input type="text" name="url" id="url" size="22" />
</p>
</div>
<div class="submit">
<input type="submit" name="submit" id="sub" value="Leave comment" />
<input type="hidden" name="comment_post_ID" id="hidden" value="">
</div>
</form>
<script type="text/javascript">
//<![CDATA[
new Axent.SelfLabeledInput('#commentform label');
//]]>
</script>
I want to write a function from this script such that when I press the submit on this form, and an input field is focused, it hides/clears it, so it doesn't get submitted to the database.
This works with the latest Prototype lib. I don't know any JavaScript, so I need your help. I'm using this form for my WordPress comments area.
I finally got it to work! Here's the final code if someone else wants to run it:
if (Object.isUndefined(Axent)) { var Axent = { } }
Axent.SelfLabeledInput = Class.create({
initialize: function() {
var labelSelector = arguments[0] || 'label';
$$(labelSelector).findAll(function(l) {return (l.readAttribute('for') !== null)}).each(function(l){
l.hide();
var el = $(l.readAttribute('for'));
el._value = l.innerHTML;
if (el.value.empty()) {
el.value = el._value
}
el.observe('blur',function(e){if(Event.element(e).value == '') Event.element(e).value = Event.element(e)._value;});
el.observe('focus',function(e){if(Event.element(e).value == Event.element(e)._value) Event.element(e).value = '';});
$(el.form).observe( 'submit', (function(thisel) { return function(e) {
if( thisel.value == thisel._value ) { thisel.value = '' }
}})(el));
});
}});
You don't have to worry, labels won't get submitted.
This script will remove the labels from the DOM on submit tho. It has to be run after the DOM is loaded (well, at least the form) and if your form elements are inside the labels they will disappear too!
document.getElementById( 'commentform' ).onsubmit = function() {
var labels = this.getElementsByTagName( 'label' );
while( labels[0] ) {
labels[0].parentNode.removeChild( labels[0] );
}
return true;
}
This is not a prototype script. It's Plain Old Javascript.
The elements are pre-filled with the label text. On focus the default text disappears and reappears on blur if the element is still empty.
You could try this. I don't use prototype, so it's a guess in places.
if (Object.isUndefined(Axent)) { var Axent = { } }
Axent.SelfLabeledInput = Class.create({
initialize: function() {
var labelSelector = arguments[0] || 'label';
$$(labelSelector).findAll(function(l) {return (l.readAttribute('for') !== null)}).each(function(l){
l.hide();
var el = $(l.readAttribute('for'));
el._value = l.innerHTML;
if (el.value.empty()) {
el.value = el._value
}
el.observe('blur',function(e){if(Event.element(e).value == '') Event.element(e).value = Event.element(e)._value;});
el.observe('focus',function(e){if(Event.element(e).value == Event.element(e)._value) Event.element(e).value = '';});
$(el.form).observe( 'submit', (function(thisel) { return function(e) {
if( thisel.value == thisel._value ) { thisel.value = '' }
}})(el));
});
}

Categories