jquery on() not registering first click - javascript

I am having strange behaviour when using jquery.on().
Basically, just trying to create a newsletter signup form (can be dynamically generated and not there on initial DOM load) and pass the details through in Ajax but it is not registering the first click on the submit button meaning that to successfully submit, the user has to click twice (only seeing the success message and 'subscribe' post on 2nd click).
The html:
<div class="newsletter-widget grid-item masonry-brick">
<input name="Email" type="email" placeholder="Please enter your email" required />
<input type="submit" value="Subscribe" class="newslettersubmit"/>
and the javascript (in document ready);
var newsletterFocus = $('.newsletter-widget').find('input[type=submit]');
$(document).on('submit', newsletterFocus, function (e) {
e.preventDefault();
var newsletterLinks = newsletterFocus;
DD.newsletter.behavior(newsletterLinks);
});
and the functions within an object that are called;
DD.newsletter = {
behavior: function (item) {
item.click(function (e) {
e.preventDefault();
var where = $('.newsletter-widget').find('input[type=submit]').parents('section').attr('id');
var email = $(this).siblings('[name$=Email]'),
emailVal = email.val();
DD.newsletter.subscribe(email, emailVal, where);
});
},
subscribe: function (self, email, where) {
$.ajax({
type: "POST",
data: '{"email":"' + email + '", "method":"' + where + '"}',
url: '/Subscriber/Subscribe',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
self.val(response);
},
failure: function (msg) {
self.val(msg);
}
});
},});
I've tried using 'click' as the action for on() but this registers an event on each click and i get thousands of forms submitted!
Any help appreciated!

Change the div container to a form element:
<form class="newsletter-widget grid-item masonry-brick">
You'll want to register the submit event to the form, not the input field. Here's a quick refactor of your form submission:
$(document).on('submit', '.newsletter-widget', function (e) {
e.preventDefault();
DD.newsletter.behavior(); //Submit the form via AJAX
});
If you wanted to hook this up to your behavior method, just unwrap the click:
behavior: function () {
var where = $('.newsletter-widget').find('input[type=submit]').parents('section').attr('id');
var email = $(this).siblings('[name$=Email]'),
emailVal = email.val();
DD.newsletter.subscribe(email, emailVal, where);
}

The first click on the button will cause the behaviour click event handler to be bound to the button. Bind the behaviour directly instead of in the click event handler.
Replace this:
var newsletterFocus = $('.newsletter-widget').find('input[type=submit]');
$(document).on('submit', newsletterFocus, function (e) {
e.preventDefault();
var newsletterLinks = newsletterFocus;
DD.newsletter.behavior(newsletterLinks);
});
with:
DD.newsletter.behavior($('.newsletter-widget input[type=submit]'));

It should probably (I think) be something like this:
DD.newsletter = {
behavior: function (item) {
var where = $(item).parents('section').attr('id');
var email = $(item).siblings('[name$=Email]'),
var emailVal = email.val(); // why were you declaring this without 'var'?
DD.newsletter.subscribe(email, emailVal, where);
},
subscribe: function (self, email, where) {
$.ajax({
type: "POST",
data: '{"email":"' + email + '", "method":"' + where + '"}',
url: '/Subscriber/Subscribe',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
self.val(response);
},
failure: function (msg) {
self.val(msg);
}
});
},});

Related

Uncaught TypeError is not a function

I have a form that I'm trying to submit via ajax and I'm having some issues that I don't understand.
So I have the following function defined at the top of my main.js:
function formSubmit() {
var valid = true;
$(this).find('input, select, textarea').each(function(index, el) {
if(valid)
{
if($(el).is(':hidden'))
{
$(el).removeAttr('required');
}
if(!el.checkValidity())
{
valid = false;
//el.focus();
}
}
});
if (!valid)
return; // not ready to submit
var options = {
url: document.location.origin + 'update.php',
type: 'post',
dataType: 'json',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
error: showError // post-submit callback
};
// bind form using 'ajaxForm'
$(this).ajaxSubmit(options);
};
Later in my main.js I have the following line that is run when I click a button:
$('#contact-form').formSubmit();
Also in my main.js I have:
$('body').on('change', '#contact-form', formSubmit);
In my HTML:
<form name="contact" id="contact-form">
<input type="text" name="name" value="" required>
<input type="hidden" name="page" value="contact">
</form>
When I run the $('#contact-form').formSubmit(); line, I get the error:
Uncaught TypeError: $(...).formSubmit is not a function
However, when I simply edit the name field (triggering the "on change" line) it updates and runs the function just fine.
What am I missing?
EDIT: It looks like the outcome I'm looking for is not apparent, probably because I'm not super familiar with javascript.
What I was trying to do was have a button that ran the formSubmit() function such that the $(this) element in that function was the form element.
I thought I could just run $('#contact-form').formSubmit() to do that but apparently not?
How would I go about running the formSubmit() function such that $(this) in that function refers to the element with an id of '#contact-form'?
Replace
$('#contact-form').formSubmit();
With
$('#contact-form').submit();
https://api.jquery.com/submit/
Try on submit.
$('#contact-form').submit(function(){
}
Since you are using jQuery, try something like this:
+function ($) {
$.fn.formSubmit = function() {
var valid = true;
$(this).find('input, select, textarea').each(function(index, el) {
if(valid)
{
if($(el).is(':hidden'))
{
$(el).removeAttr('required');
}
if(!el.checkValidity())
{
valid = false;
//el.focus();
}
}
});
if (!valid)
return this; // not ready to submit
var options = {
url: document.location.origin + 'update.php',
type: 'post',
dataType: 'json',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
error: showError // post-submit callback
};
// bind form using 'ajaxForm'
$(this).ajaxSubmit(options);
return this;
}
}(jQuery);
That way, you should be able to use it like this: $("#contact-form").formSubmit();

Ajax function not being hit in submitHandler

Form validation works, but I can't get the Ajax call to fire correctly. The submitHandler is being reached, but the Ajax call isn't. I have included a Fiddle at the bottom, but obviously you can't fire ajax calls from there.
$(".player-code, .submit").hide();
//VALIDATION
$(function () {
$("#form").validate({
rules: {
playerClass: {
required: true
}
},
submitHandler: function () {
var accountNumber = $(".accountNumber").val();
var domain = $(".domain").val();
var playerClass = $(".playerClass").val();
var dataString = accountNumber + playerClass;
//Save Form Data........
$.ajax({
type: "POST",
dataType: "json",
url: "/",
contentType: "application/json",
data: dataString,
success: function () {
$(".player-code").show();
$('.render-info').html("<div class='alert alert-success'>You've successfully built your player code</div>");
},
failure: function () {
$('.render-info').html("<div class='alert alert-failure'>Submission Error</div>");
}
});
}
});
});
jQuery.validator.addMethod("domainChk", function (value, element, params) {
if (this.optional(element)) return true;
var regExp = new RegExp("^(?!www\\.|http:\/\/www\.)(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$");
return regExp.test(value);
}, "Valid hostname required for player code");
jQuery.validator.addClassRules({
domainChk: {
domainChk: true
}
});
$('input[type="text"]').on('click keyup blur', function () {
if ($('#form').valid()) {
$(".submit").show();
} else {
$(".submit").hide();
}
});
//PREPOPULATE ACCOUNT FROM QUERY STRING
var url = window.location.href;
var regex = /=.*/; // match '=' and capture everything that follows
var accountId = url.match(regex);
$(".accountNumber").val(accountId).remove("=");
//
jsFiddle: Link
There is no failure: option for $.ajax(). If you want to see any errors that happen in the ajax call, then use error: to capture the error.
To make form submit you should use
<button class="btn btn-default submit" type="submit">Submit</button>
instead of <div class="btn btn-default submit">Submit</div>
submitHandler will be called only on native form submit.
Fiddle

How to show php passed results to ajax without refreshing

I want to do is when a user type an email to the inputbox ajax will pass the value automatically to php.
My problem is the result only show if I try to refresh the page
html:
<input type="text" id="email" name="email" />
script:
$(document).ready(function(){
var countTimerEmailName = setInterval(
function ()
{
emailName();
}, 500);
var data = {};
data.email = $('#email').val();
function emailName(){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
});
You can try with:
Because you dont need declare function in ready() and you need yo get the email value after any change. Now you only get the value when the page is ready.
function emailName( email ){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: 'email=,+email,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
$(document).ready(function(){
$('#email').change(function(e) {
emailName( this.val());
});
});
You're handling it wrong. jQuery has particular events to do these things.
Take this for example:
$(document).ready(function(){
$(document).on('keyup', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
It will look what is in the below input field as the user types. (which is what I presume you're trying to do?)
<input type="text" id="email" name="email" />
Example
You could simply remove that console.log() and replace it with your ajax request. (The above example will run as the user types.)
Alternatively you could use change() like this:
$(document).ready(function(){
$(document).on('change', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
Which will run after the value of the text box has changed. (When the user clicks out of the text box or moves somewhere else on the page.)
Example

How to manage an event unload

I want to insert in my page an event that trigger when the window close or change except that in the case that has been triggered by a submit button of a particular submit which bring in an analogus page. I tried the follow but it doesn't work. (prova is the name of submit).
$(window).bind("unload", function (event) {
alert('1');
if (event.target.tagName != "prova") {
alert('2');
var postData = {
'chat_message': "I left"
};
$.ajax({
type: "POST",
dataType: "json",
url: base_url + "chat/ajax_add_message/" + chat_id + "/" + user_id,
data: postData,
success: function (data) {
get_messages();
}
});
}
});
Do you really have HTML element with tag "prova" ?
event.target.tagName != "prova"
Maybe you need to check className or id?

.ajax() refreshes the page after ENTER is hit

I am using ajax to update the db with a new folder but it refreshes the page after ENTER is hit.
on my form I have onkeypress="if(event.keyCode==13) savefolder();"
here is the javascript code that I have: what it does basically is after you hit enter it calls the function savefolder, savefolder then sends a request through ajax to add the folder to the db. Issue is it refreshes the page... I want it to stay on the same page.
any suggestions? Thank you
<script>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
// ajax request to add the folder
jQuery.ajax({
type: 'get',
url: 'addfolder.php',
data: 'foldername=' + foldername + '&foldercolor=' + foldercolor,
beforeSend: function() { alert('beforesend');},
success: function() {alert('success');}
});
return false;
}
</script>
This is working:
<form>
<input type="submit" value="Enter">
<input type="text" value="" placeholder="search">
</form>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
jQuery.ajax({
type: 'get',
url: '/echo/html/',
//data: 'ajax=1&delete=' + koo,
beforeSend: function() {
//fe('#r'+koo).slideToggle("slow");
},
success: function() {
$('form').append('<p>Append after success.</p>');
}
});
return false;
}
jQuery(document).ready(function() {
$('form').submit(savefolder);
});
http://jsfiddle.net/TFRA8/
You need to check to see if you're having any errors during processing (Firebug or Chrome Console can help). As it stands, your code is not well-formed, as the $(document).ready() is never closed in the code you included in the question.
Simply stop the propagation of the event at the time of the form submission
jQuery(document).ready(function($) {
$("#whatever-form-you-are-pulling-your-values-from").submit(function(event) {
var foldername = $('#foldername').val();
var foldercolor = $('#foldercolor').val();
event.stopPropagation();
// ajax request to add the folder
$.ajax({
type: 'get',
url: '../addfolder.php',
data: 'ajax=1&delete=' + koo,
beforeSend: function() { fe('#r'+koo).slideToggle("slow"); },
success: function() { }
});
});
Since by default on a form the enter button submits the form, you need to not only handle this with your own code, but cancel the event after.
Try this code instead:
onkeypress="if(event.keyCode==13) {savefolder(); return false;}"
The onkeypress event will that the return value of the javascript and only continue with it's events if it returns true.

Categories