I am using the code below from superluminary's answer to this question jQuery AJAX submit form to ajaxify all the forms on my site.
(function($) {
$.fn.autosubmit = function() {
this.submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(response) {
$(form).parent('.like-this').html("works");
$(form).parent('.dislike-this').html("works");
}).fail(function(response) {
console.log('Ajax form submit does not work!');
});
});
return this;
}
})(jQuery)
$(function() {
$('form[data-autosubmit]').autosubmit();
});
Then I add data-autosubmit to my form tag and the form submits using ajax.
E.g. <form action="like/post" method="post" data-autosubmit>
THE PROBLEM
In my image slider, which is based on this image slider, I have a form, which acts as a like button. The form works fine but the page reloads and the modal window closes on form submit. It does not use ajax, although I put data-autosubmit into the form tag.
The exact same form works fine (using ajax) at other places in my project.
THE SLIDER (the relevant part)
/*
* jQuery Slider Plugin
* Version : Am2_SimpleSlider.js
* author :amit & amar
*/
(function ($) {
jQuery.fn.Am2_SimpleSlider = function () {
//popup div
$div = $('<div class="product-gallery-popup"><div class="popup-overlay"></div><div class="product-popup-content"><div class="product-image"><img id="gallery-img" src="" alt="" /><div class="gallery-nav-btns"><a id="nav-btn-next" class="nav-btn next"></a><a id="nav-btn-prev" class="nav-btn prev"></a></div></div><div class="product-information"><p class="product-desc"></p><div class="clear"></div><hr><br><br><div class="like-image"><form action="" method="post" class="like-form" data-autosubmit></form><div class="liked"></div></div>X</div></div>').appendTo("body");
//on image click
$(this).click(function () {
$('.product-gallery-popup').fadeIn(500);
$('body').css({ 'overflow': 'hidden' });
$('.product-popup-content .product-image img').attr('src', $(this).find('img').attr('src'));
$('.product-popup-content .product-information p').html($(this).find('.image-description').html());
// In the like-image div is the form
$('.product-popup-content .product-information .like-image').html($(this).find('.like-image').html());
$Current = $(this);
$PreviousElm = $(this).prev();
$nextElm = $(this).next();
if ($PreviousElm.length === 0) { $('.nav-btn.prev').css({ 'display': 'none' }); }
else { $('.nav-btn.prev').css({ 'display': 'block' }); }
if ($nextElm.length === 0) { $('.nav-btn.next').css({ 'display': 'none' }); }
else { $('.nav-btn.next').css({ 'display': 'block' }); }
});
THE FORM
<!-- the image like button -->
<div class="like-image">
<?php if ($this->likedImages[$postImage->image_id]) { ?>
<!-- like the image -->
<div class="like-this">
<form action="<?= Config::get('URL');?>like/like_image" method="post" class="like-form" data-autosubmit>
<input type="hidden" name="image_id" value="<?= $postImage->image_id; ?>" />
<button type="submit" class="button like-button">Like</button>
</form>
</div><!-- /.like-this -->
<?php } else { ?>
<!-- dislike the image -->
<div class="dislike-this">
<form action="<?= Config::get('URL');?>like/unlike_image" method="post" class="like-form" data-autosubmit>
<input type="hidden" name="image_id" value="<?= $postImage->image_id; ?>" />
<button type="submit" class="button like-button">Dislike</button>
</form>
</div><!-- /.dislike-this-post -->
<?php } ?>
<div class="liked"></div>
</div><!-- /.like-image -->
Please let me know if you need to see any more code.
I would be very thankful for any kind of help!!
As I understood your code you need to add ajaxForm init.
Change this lines:
// In the like-image div is the form
$('.product-popup-content .product-information .like-image').html($(this).find('.like-image').html());
To this:
// In the like-image div is the form
var contentContainer = $('.product-popup-content .product-information .like-image');
contentContainer.html($(this).find('.like-image').html());
contentContainer.find('form').autosubmit();
Some explanation:
when you calling this code
$(function() {
$('form[data-autosubmit]').autosubmit();
});
selector 'form[data-autosubmit]' cant resolve your form since it not presented in document (form stored in variable). When you attaching form to document by setting html content to .like-image element, you must call autosubmit to initialize jQuery plugin on newly created form.
The reason it's not doing what you ask is because you havent told it to. Your javascript is a self invoking function that throws out a function, like a plugin. you would then need to use that function to tell it to submit the form.
$('form[data-autosubmit]').submit(e) {
$(this).autosubmit();
e.preventDefault(); //prevent actual form submission
}
Related
I'm using Codeigniter and having trouble on my button after I load my page using load function on jQuery.
reg_form.php loads first, then after saving data, it will load the page-content class to see the list of data but when I'm trying to go to reg_form.php again using the button, nothing happens.
JS is not working on the current loaded page
reg_form.php
<html>
<body>
<div class="page-content">
<label>Name:</label><br>
<input type="text" id="name">
<button id="save"></button>
</div>
</body>
</html>
reg_list.php
<html>
<body>
<div class="page-content">
<button id="reg_form"></button>
</div>
</body>
</html>
reg.js
$('#reg_form').click(function(){
$(".page-content").load('reg_form');
});
$('#save').click(function(){
var name = $('#ame').val();
$.ajax({
url:"gatepass/save",
method: 'POST',
data:{
name:name
},
success:function(data){
$(".page-content").load('reg_list');
}
});
});
Use below mentioned solution.
$(document).on('click','#reg_form',function(){
$(".page-content").load('reg_form');
});
$(document).on('click','#save',function(){
var name = $('#ame').val();
$.ajax({
url:"gatepass/save",
method: 'POST',
data:{
name:name
},
success:function(data){
$(".page-container").load('reg_list');
}
});
});
This will help you.
Tabs and events in the content that you add after the DOM loads should be defined using the .on() function as shown below use of .delegate() has been discontinued:
$(document).on(events,selector,data,eventhandler);
If for example you add the button below into the div after DOM loads and you want the button to say 'You clicked me' when clicked, the code would be:
$(function() {
$(document).on('click', '#justClickMe', function(e) {
alert('You clicked me');
})
$('#content').append('<button id="justClickMe">Just Click Me</button>');
});
<div id="content"><h3>New Content</h3></div>
I want to activate a loader class upon form validation using Hyperform.
It is not working.
When the user presses the create button:
The form should be validated.
If the form is valid it executes the loader by adding the is-active class that I've made.
I am using Hyperform because I need to validate the form on mobile Safari.
<!-- HTML -->
<div id="loader" class="loader loader-default" data-text="In Process"></div>
<button id="send" name="send" class="btn btn-create">create</button>
<script>
$("#send").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
console.log( "Succesful Request!" );
$("#loader").addClass("is-active");
}});
</script>
After validation with Hyperform:
//Script
<script>
input.addEventListener('valid', event => {
var d = document.getElementById("loader");
d.className ="loader loader-default";
});
</script>
I want to show a custom popup alert with dialog of jquery.
I have call function on form submit
<form name="form" method='post' action="user/purchase_user_tip" onSubmit="validateLogin();">
jquery code
<script type="text/javascript">
function validateLogin()
{
var session = 1;
if(session==1)
{
$('#dialog').dialog('open');
return false;
}
}
</script>
html dialog
<div id="dialog" title="Dialog Title" style="display:none"> Some text</div>
To make the #'dialog' id visible use:
$('#dialog').show();
To hide it again use:
$('#dialog').hide();
Another way is to use the jQuery UI Dialog as it is:
declare it (without display none)
open when needed
Moreover use the event prevent default and a different function definition:
function validateLogin(obj, e)
{
var session = 1;
if(session==1)
{
e.preventDefault();
$('#dialog').dialog('open');
}
}
$(function () {
$('#dialog').dialog({autoOpen: false});
});
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.min.css" rel="stylesheet"/>
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<form name="form" method='post' action="user/purchase_user_tip" onSubmit="validateLogin(this, event);">
<input type="submit" value="ClicMe">
</form>
<div id="dialog" title="Dialog Title"> Some text</div>
If you are looking to display the '#dialog' you should consider using this code
function validateLogin() {
var session = 1;
if (session == 1) {
$('#dialog').dialog('open');
return false;
}
}
I've got a form with a submit button on a form that opens up a nested php page within a div on my page.
All I want to do is hide the submit button, and instead replace this with clicking one of the divs and thus running a script called showBiog(key), which then passes key to the form for submitting.... help... ;-)
<script type="text/javascript">
$(function() {
// Handler for .ready() called.
$('#SubmitForm').submit(function( event ) {
$.ajax({
url: 'test2.php',
type: 'POST',
dataType: 'html',
data: $('#SubmitForm').serialize(),
success: function(content)
{
$("#DisplayDiv").html(content);
}
});
event.preventDefault();
});
});
</script>
HTML is:
<form id="SubmitForm" method="post">
<div id="SubmitDiv" style="background-color:black;">
<button type="submit" class="btnSubmit">Submit</button>
</div>
</form>
<div class="test" onClick="showBiog(1)"><p>1</p></div>
<div class="test" onClick="showBiog(2)"><p>2</p></div>
<div class="test" onClick="showBiog(3)"><p>3</p></div>
<div class="test" onClick="showBiog(4)"><p>4</p></div>
Just remove the button element, and do something like:
$('#myspecificdiv').on('click', function() {
$('#SubmitForm').submit();
}
You can hide the submit button and perform its click action in showBiog(key); just like
function showBiog(key){
//Your code
$('#submit_btn_id').click();
}
please put the javascript on document.ready
<script type="text/javascript">
$(document).ready(function() {
$('.class name').on('click',function() {
$('#SubmitForm').submit();
});
});
</script>
On my form, you have to select an item in order for the form to show. The problem I'm running into is that on submit, it hides the form. How can I correct that?
This is my script:
<script>
$(document).ready(function () {
$(".orderForm").hide();
$(".choice").each(function () {
$(this).click(function () {
$(".orderForm").show();
});
});
});
</script>
Here's part of the html:
<form method="post" class="form-horizontal">
<div class="choiceContainer">
<#choicesSection><#choice id="2098885" class="choice">
<label>
<div align="left">
<h3 class="choiceName">
<#choiceSelectionRadioButton />
<#choiceName>148PKI</#choiceName>
</h3>
<div class="orderForm">
</div>
</div></div>
<div class="btn" align="center"><#selectedPaymentOptionSubmitButton label="Continue"
class="continue"/></div>
I updated the script too.
Use sessionStorage (or an appropriate polyfill script) to persist a variable across page loads. (Note sessionStorage serialized the data so when getting the value it will no longer be true but the string "true")
$(document).ready(function () {
if(!sessionStorage.formSubmitted)
$(".orderForm").hide();
//Reset it for possibly another form submission
sessionStorage.removeItem('formSubmitted');
$(".choice").each(function () {
$(this).click(function () {
$(".orderForm").show();
});
});
$("form.form-horizontal").submit(function(){
sessionStorage.formSubmitted = true;
});
});