Dynamic form not submitting (jQuery) - javascript

I'm creating a simple task manager app with PHP, MySQL, & jQuery. I'm adding a feature that will allow users to add a task by clicking a "new task" button, typing into a text field and hitting enter. This is the jQuery I have:
function add_task() {
// Add the "add new task" button
$("<span class='add-new'>Add new item</span>").appendTo(".sub-phase");
// String for the input form
var task_form = '<form class="add-new-task" autocomplete="off"><input type="text" name="new-task" placeholder="Add a new item..." /></form>';
// Display form on button click
$('.add-new').click(function() {
$(task_form).appendTo($(this).parent());
});
// Post results
$('.add-new-task').submit(function(){
var new_task = $('.add-new-task input[name=new-task]').val();
if(new_task != ''){
$.post('includes/add-tasks.php', { task: new_task }, function( data ) {
$('.add-new-task input[name=new-task]').val('');
$(data).appendTo('.task-list').hide().fadeIn();
});
}
return false;
});
}
If I have the form hardcoded in the index.php file, this functionality works as expected. But if the form is created in jQuery like I have it here, then nothing happens on submit. I've searched around but haven't been able to find a solution that works.
Any advice is much appreciated! Thank you.

The issue is that you're not delegating the event. You've setup a submit handler on page load, but not for dynamically created elements.
Change:
$('.add-new-task').submit(function(){
To:
$(document).on('submit', '.add-new-task', function(){
Now the event handler is bound to the document and will trigger for any element on the page with .add-new-task regardless of whether or not it was dynamically created.
Also, of note, you should avoid binding to document where possible, and instead, should bind to the closest static parent element.

Please check the fiddle here - http://jsfiddle.net/kunaldethe/TQa97/
Here jQuery 1.7.2 is used and as answered by Ohgodwhy,
$(document).on('submit', '.add-new-task', function(){
is used instead of
$('.add-new-task').submit(function(){
In the Javascript Console (F12), you can see the request is sent. (Obviously we don't have the next page, so the request is not completed.)
If you use the jQuery with version less then 1.7.2, the code breaks.
Let us know, the environment you are using.

Related

Switch from iframe "AJAX" to proper AJAX

This is legacy code.
I'm working on a project where we're using iframes to simulate AJAX.
Basically, we're using the target attribute to submit the <form> in an iframe, resulting in the request not opening a new tab. Also, we echo a <script></script> in the response from the PHP, and the result is executed since it populates the iframe.
Here's an example of such <form> :
<form id="form_to_submit" method="POST" action="ajax/createUser" target="iframe_name">
<input type="text" name="input_to_send">
<button type="button" onclick="$('#form_to_submit').submit()">Submit With Onclick!</button>
</form>
Nowadays, not only this looks evil, but it has one (perhaps others) huge pitfall. If one request is made through this process, and the client goes somewhere, and then goes back in his browser history, it'll send the request again.
To fix this last problem, there are many solutions. I think the one I prefer the most is to use real AJAX instead of iframes. Now, in theory, I could change every single form in the source code to make it use AJAX, but I know I won't have 1 straight week of work just for this purpose.
I'm looking for a "quick" way to intercept these requests before they're sent to the iframe, and send them with AJAX instead.
So far, I tried to target <form> tags which have a target="iframe_name" and listen to the submit event to then send the request again with a same method/URL/data.
$('form[target=iframe_name]').on('submit', function (event) {
event.preventDefault(event);
var url = $(this).attr('action'),
datas = $(this).serialize();
$.post(url, datas).done(function (response) {
eval($(response).text());
});
});
But that only works if they're submitted through a real click on a submit button. I'd say 95% of these cases are submitted through onclick tags which will .submit() the forms, and in these cases, the submit event won't trigger it appears.
I'm stuck, any idea ?
Note : I'm tagging jquery only to let you know it's available to be used, even though the question is still relevant with any lib/framework of JS.
You can actually remove the onclick attributes just by doing a general jQuery action on document ready:
<script>
$(document).ready(function() {
var getButton = $('form').find('button');
getButton.prop('onclick',null);
// put listener script here for new form submit (using ajax)...
});
</script>
This piece of code just does a general lookup on the page for all forms, finds the buttons, then removes the onclick attribute. Once you do this the form should not submit anymore with that inline javascript.
I would suggest this be temporary as you incrementally change the forms over time to natively work using the jQuery listener (like the other 5% of forms you have created with no onclick).

Contact Form 7 AJAX Callback

Been searching around on this for a while and can't come up with any documentation to outline what i want to achieve.
I'm using wordpress and the Contact Form 7 plugin, all is working perfectly, what i want to achieve is to run some particular javascript upon form submit, i know we can use "on_sent_ok:" in the additional settings, but this only performs if the form is actually submitted.
What i'd like to do is to do some other javascript when the form doesn't submit ok, which throws the user back to the section which didn't validate.
I can use the following code to run after 1.7s of the form submit being clicked, however it's a bit sloppy as if the user was running with a slow connection, there's potential this could run before the form is submitted properly.
$('.wpcf7-submit').click(function() {
setTimeout(function() {
if ($('.fs1 input,.fs1 textarea').hasClass('wpcf7-not-valid')) {
$('.pop-up-form').removeClass('pustep2').removeClass('pu-closing');
$('.form-step').hide();
$('.fs1').show();
}
if ($('.fs2 *').hasClass('wpcf7-not-valid')) {
alert('error on page 2 - take user back to the area with issues')
}
}, 1700);
});
Is there any particular function or hook i can use to run JS when the form AJAX has completed?
Thanks!
In version 3.3 new jQuery custom event triggers were introduced:
New: Introduce 5 new jQuery custom event triggers
wpcf7:invalid
wpcf7:spam
wpcf7:mailsent
wpcf7:mailfailed
wpcf7:submit
You can use wpcf7:invalid like the example below:
$(".wpcf7").on('wpcf7:invalid', function(event){
// Your code here
});
Given the variety of responses on this topic the plugin developer seems to change their mind about how this should work every 5 minutes. Currently (Q1 2017) this is the working method:
document.addEventListener( 'wpcf7mailsent', function( event ) {
alert( "Fire!" );
}, false );
And the valid events are:
wpcf7invalid — Fires when an Ajax form submission has completed
successfully, but mail hasn’t been sent because there are fields with
invalid input.
wpcf7spam — Fires when an Ajax form submission has
completed successfully, but mail hasn’t been sent because a possible
spam activity has been detected.
wpcf7mailsent — Fires when an Ajax
form submission has completed successfully, and mail has been sent.
wpcf7mailfailed — Fires when an Ajax form submission has completed
successfully, but it has failed in sending mail.
wpcf7submit — Fires
when an Ajax form submission has completed successfully, regardless
of other incidents.
Sauce: https://contactform7.com/dom-events/
Sometimes it may not work, as Martin Klasson pointed out, only 'submit' event works, most probable because it's triggered by a form and bubbles up to the selected object. Also as I can understand, now events have other names, like "invalid.wpcf7", "mailsent.wpcf7", etc. In short, this should work:
jQuery('.wpcf7').on('invalid.wpcf7', function(e) {
// your code here
});
More detailed explanation here: How to add additional settings on error in Contact form 7?
This code works since 5.8.x version:
$('.wpcf7').on('wpcf7invalid wpcf7spam wpcf7mailsent wpcf7mailfailed', function () {
// your code here
});
I had quite a go at this, and I found that when only the Submit event works, it means that there is a js problem / conflict in your theme.
If it's a custom theme you built, make sure jQuery and jQuery migrate are both loaded, in this order, and that the Contact form 7 js is also loaded in the footer.
Make sure you have wp_head, and wp_footer in your php templates.
For DOM events to work, your form must be in Ajax mode. If the page reloads upon submission, forget about DOM events. If you have the form ID showing up in the URL, same thing. My form was initially not in Ajax mode because the Contact Form JS was not loaded, and jQuery Migrate either.
The form must behave exactly like shown on this page for the DOM events to be fired properly. Once you have that, it should be working.
I've tested this with jQuery 3.3.1 and Migrate 3.0.1 and the following event listener worked:
document.addEventListener( 'wpcf7mailsent', function( event ) {
console.log('mail sent OK');
// Stuff
}, false );
To check if your theme is the culprit, test your form using Wordpress' default theme, if it works, you know the issue is on your end and not so much in the dev's doc!
I tried to implement the dom event behavior in wordpress contact form 7 plugin as described here, but after trying numerous methods which are given as fixes in different forums I implemented a method of my own.
I m describing the method here below. The method involves some steps which are listed below:
Creating the contact form
Scripting for the contact form to capture event triggers and form data
Loading the script
1. Creating the contact form
<label> Your name
[text* cform7-name id:cform7-name autocomplete:name] </label>
<label> Your Number
[tel* cform7-contact id:cform7-contact] </label>
<label> Course You are interested (Press Ctrl + Select to select Mutiple)
[select* cform7-courses id:cform7-courses multiple "JAVA" "Python" "C#" "Others"] </label>
<label> Your message (optional)
[textarea cform7-submit id:cform7-message] </label>
[submit id:cform7Submit "Submit"]
Above is a sample script with ids so that we can easily retreive those elements from DOM tree using JS. [You can modify the field ids as your need]
2. Scripting for the contact form to capture event triggers and form data
document.addEventListener('DOMContentLoaded', function() {
var frmButton = document.getElementById('cform7Submit');
frmButton.addEventListener( 'click', function( event ) {
var data = {
name: document.getElementById('cform7-name').value,
contact: document.getElementById('cform7-contact').value,
courses: document.getElementById('cform7-courses').value,
comment: document.getElementById('cform7-message').value
};
event.preventDefault();
console.log('Event Data ', event);
console.log('Data ', data);
}, false );
}, false);
Save the above script in wordpress deployment directoty. In my case I placed the script in the root deployment directory itself(<worpress-root-directory>) and saved the file as cform7.js.
Ex: /var/www/wordpress-site/cform7.js
After finishing this we need to load the script.
3. Loading the script
function cform7_script() {
wp_enqueue_script( 'cform7-js', '/cform7.js');
}
add_action('wp_enqueue_scripts', 'cform7_script');
Place the above code in the <worpress-root-directory>/wp-includes/functions.php file
That's done! On clicking the form submit button(cform7-submit) you must see the data logged in the console.

Submit Form in DNN, typical answer not working

I am trying to submit a mailchimp form from within my DNN (DotNetNuke) site. Typically, you just remove the form tags and put some javascript in the onclick event of the submit button...like here. This works and you can see as such here.
But, I am using this popup module, as I want this form to pop up when someone comes to the site. And in this configuration it does not work. It will submit the form to the designated URL, but no form data is passed. This page is here.
A couple of observations:
When you view the page source, the popup form is within the form tags, yet a this.form returns null in the script.
When you inspect the submit button element in Chrome, you see that the html form is then OUTSIDE the form tags.
So maybe there is some javascript with this popup module that is moving the DOM element on page load???
I created a js function to call on the input button submit; code is as follows:
function submitSubscription(clickedElement){
$form = $('body').find('form');
$form.attr('action', 'http://InciteResults.us2.list-manage1.com/subscribe/post?u=6d82b6a028c94cc75005eb4fe&id=1c7ceabac4');
$form.submit();
}
Note: in this function clickedElement.form is returning null.
Because your content is not in a <form>, you're going to put it inside a <form> in order for your script to work. You can either dynamically create a <form> element, or move your content back inside the main <form> when you submit. Try something like this:
function submitSubscription(clickedElement){
var $form = $('<form></form>', { action: 'http://InciteResults.us2.list-manage1.com/subscribe/post?u=6d82b6a028c94cc75005eb4fe&id=1c7ceabac4' });
$('#mc_embed_signup').wrap($form);
$form.submit();
}

form submit - IE access denied - same domain

SCRIPT5: Access denied
jquery.min.js, line 3 char 3769
I'm getting this error by simple form submit only in IE
$("#icon_upl").click(function(){ //icon_upl is button which open dialog
$("[name=icon]").click();
});
$("[name=icon]").change(function() { //icon is hidden file input
$("[name=upload_icon]").submit();
});
I sending that form to hidden iframe which is at the same domain.
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;display:none;"></iframe>
<form name="upload_icon" action="upload_icon.php" method="post" enctype="multipart/form-data" target="upload_target">
submit input doesn't help
I dont get it cuz if i try to send another form that works fine
If you are triggering the select files dialog via JS then you will get an access denied error when submitting the form. IE does not allow this. You will have to ask user to click on input type file directly
More details here
https://github.com/valums/file-uploader/issues/118#issuecomment-1387612
You can try styling the input type file though
http://www.quirksmode.org/dom/inputfile.html
I had similar HTML and jQuery code and encountered the same issue (i.e. 'Access is denied.' JavaScript error in Internet Explorer), which I managed to resolve by taking pointers from this (great) answer.
In your instance:
Change the #icon_upl <button>/<input> to a <label> and make use of the tag's accessibility features by setting the for attribute on it to point to your <input name="icon" type="file"> element.This effectively makes your click() event handler redundant. However, clicking the <label> in Firefox does not seem to trigger the file <input> dialog so you'll need to perform a browser test and still have the click() event handler if the browser is Mozilla-based.
In order for it to work, you'll need to make sure that your file <input> is not hidden by setting its position to be absolute and moving it off-screen.
i have found an other way to do this ...
I have make test and i found it work after 2 or 3 click on the submit button.
i have try some solution but found this by my self.
this is only for ie.
note i dont use the jquery submit method because they handle the error.
function Submit() {
try {
$('#FormName')[0].submit();
} catch (e) {
setTimeout(function () { Submit(); }, 50);
}
}
ps. sorry for my bad english, this is not my first language.
You can make a direct event firing on hidden input field because you can't catch it. It is possible to bind event with it and trigger it via another.
for example:
// binding event to hidden field
$('input[name=icon]:hidden').on('click', function() {
alert('Hidden triggered');
});
// some button/ or else
// some_target is any valid selector you can use
$('some_target').on('click', function() {
$('input[name=icon]:hidden').click(); // triggering click on hidden field will alert 'Hidden triggered'
});
Note: But its not clear from your post that if you have already something like this or not.
It seems to be impossible
You cannot read the "value" of the element as it holds the filename.
You can't fire up the file selection menu via JS.
You can't fire submit of the file uploader control via JS.
from getting access is denied error on IE8
//Access Denied Issues is usually for IE.
var lblTrigger= document.getElementById('lblTrigger');
lblTrigger.onclick = function(){
var form = document.getElementById('form1');
form.fxSubmit();
}
var form = document.getElementById('form1'); //form with upload control
var upctrl = document.getElementById('file_1'); //file upload control
form.fxSubmit = function() {
var upctrl = document.getElementById('file_1'); //file upload control
if (upctrl.files){
var form = document.getElementById('form1');
form.submit();
}else{
document.body.submit = true;
}
}
function fxSubmit(){
if (document.body.submit){
var form = document.getElementById('form1');
setTimeout(function(){fxSubmit()},50);
form.submit();
return;
}
setTimeout(function(){fxSubmit()},1000);
}
setTimeout(function(){fxSubmit()},1000);

jQuery onclick pass post variables and reload page

Can I pass post variables and reload a page on clicking an hyperlink?
To be clear I have something like this.
Click
If javascript is enabled,
I think I can use "event.preventDefault()" to suppress passing as GET variable.
So now onclick, name should be passed as post variable instead of get.
If javascript is disabled,
Then the above should work.
You could do it, by creating a new form element, pointing it at the href and calling .submit() on it.
<a class="postlink" href="test.php?name=test">Click</a>
<script type="text/javascript">
$('.postlink').click(function() {
var form= document.createElement('form');
form.method= 'post';
form.action= this.protocol+'//'+this.hostname+this.pathname;
$.each(this.search.slice(1).split(/[&;]/g), function() {
var ix= this.indexOf('=');
if (ix===-1) return;
var input= document.createElement('input');
input.type= 'hidden';
input.name= decodeURIComponent(this.slice(0, ix));
input.value= decodeURIComponent(this.slice(ix+1));
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
return false;
});
</script>
Or you could just do an AJAX request instead and reload() the page afterwards if you prefer.
However, I'm not sure why you'd want to do this. What use is a link that's usually POSTed, except when it's not? (Not just when JS is disabled/unavailable or when it's a search engine, but also when the user middle-clicks the link or tries to right-click-bookmark it or whatever.)
If all you want is something that behaves like a button to submit a POST form, better to actually use a real form and submit button, and then use CSS to restyle it to look like a link if that's what you want it to look like.
Very good hint....
I was first trying to send the form data via an Ajax Post call and reloading the page afterwards, but it was not working properly:
var biq_select_val = jQuery('#biq_search_select').val();
jQuery.post(window.location.href,
{ biq_amazon_item_list_search: biq_select_val},
function() {window.location.reload();}
);
Now I am using just a:
jQuery('#biq_amazon_item_list_search_form').submit();
and it is working fine.
I have some 10 links on a page. When user clicks on those links ajax-reload must take place.
To be clear I have something like this.
one
Two
If javascript is enabled,
Onclick, ajax load must take place.
If javascript is disabled, Then the above should work.
Basically I am using name to limit some values of my search page.

Categories