magento form submit handler - javascript

We have a magento site that is using the WebForms2 plugin and ends up using something like the following generated code for a form:
HTML
<form action="http://example.com/magento/index.php/webforms/index/iframe" method="post" name="webform_2" id="webform_2" enctype="application/x-www-form-urlencoded" class="webforms-lg-test" target="webform_2_iframe">
<input type="hidden" name="submitWebform_2" value="1"/>
<input type="hidden" name="webform_id" value="2"/>
<div id="fieldset_0" class="fieldset fieldset-0 ">
<ul class="form-list">
<li class="fields ">
<div id="field_11" class="field type-text webforms-fields-11 webforms-fields-name">
<label id="label_field11" for="field11">Name</label>
<div class="input-box">
<input type='text' name='field[11]' id='field11' class='input text ' style='' value="" />
</div>
</div>
</li>
</ul>
</div>
<div class="buttons-set">
<p class="required">* Required Fields</p>
<button type="button" class="button" id="webform_2_submit_button" onclick="webform_2_submit()" title="submit">
<span>
<span>Submit</span>
</span>
</button>
<span class="please-wait" id="webform_2_sending_data" style="display:none;">
<img src="http://example.com/magento/skin/frontend/default/default/images/opc-ajax-loader.gif" alt="Sending..." title="Sending..." class="v-middle"/>
<span id="webform_2_progress_text">Sending...</span>
</span>
</div>
</form>
JS
var webform_2 = new VarienForm('webform_2', 0);
var webform_2_submit = function(){
var form = webform_2;
if(form.validator && form.validator.validate()){
form.submit();
$('webform_2_submit_button').hide();
$('webform_2_sending_data').show();
}
};
The tricky part is that we have an additional tool that works with all forms. Previously we just had it hook into the forms submit handler, but this particular method that Magento/WebForms uses, does not trigger the submit handler.
An example of our tool's code:
var forms = document.getElementsByTagName('form');
for(i=0; i<forms.length; i++) {
forms[i].addEventListener('submit', function() {
alert('form submitted');
}
}
We were also using a jQuery approach, but pared it down to reduce dependancies. It also did not work.
$('form').on('submit', function(e) {
alert('form submitted');
});
Question
Is there something specific in Magento that I could use with this implementation that I could hook into instead of a standard submit handler? Or a different/better way to observe a form's submit handler?

Using Prototype I was able to override the existing submit handler.
VarienForm.prototype.submit = VarienForm.prototype.submit.wrap(function($super, url) {
//-- your code can go before OR after the default form behavior
//-- include this if you want to include the previous submit behavior
$super(url);
return false;
});

Related

How to stop my page from reseting after the page is submited

I have a code, who helps me switch between forms, however, when I submit the form, the page will reset and display first(default) tab again. Could anyone help me understand how I can make it so the tab I submit the form from stays there if the submision fails or even if the submision was successfull?
Forms are switching using a little JS code and are submited from a PHP POST method form.
Please find the code below:
Javascript responsible for switching between tabs:
function onTabClick(event) {
let activeTabs = document.querySelectorAll('.active');
// deactivate existing active tab
for (let i = 0; i < activeTabs.length; i++) {
activeTabs[i].className = activeTabs[i].className.replace('active', '');
}
// activate new tab
event.target.parentElement.className += 'active';
document.getElementById(event.target.href.split('#')[1]).className += 'active';
}
const elements = document.getElementsByClassName('nav-tab-element');
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', onTabClick, false);
}
CSS:
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
And here is the HTML forms:
<body>
<header>
<h1 class="main-header">
Add a New Product
</h1>
</header>
<main>
<ul id="nav-tab" class="nav">
<li class="active">
<a class="nav-tab-element" href="#books">Books</a>
</li>
<li>
<a class="nav-tab-element" href="#dvds">DVD's</a>
</li>
<li>
<a class="nav-tab-element" href="#furniture">Furniture</a>
</li>
</ul>
<form method="POST">
<div class="tab-content active" id="books">
<div class="book-tab">
<input type="text" name="sku" placeholder="test form for books" autocomplete="off">
</div>
<div class="btn">
<input type="submit" value="Submit">
</div>
</div>
</form>
<form method="POST">
<div class="tab-content " id="dvds">
<div class="dvd-tab">
<input type="text" name="sku" placeholder="test form for DVD" autocomplete="off">
</div>
<div class="btn">
<input type="submit" value="Submit">
</div>
</div>
</form>
<form method="POST">
<div class="tab-content " id="furniture">
<div class="furniture-tab">
<input type="text" name="sku" placeholder="test form for furniture" autocomplete="off">
</div>
<div class="btn">
<input type="submit" value="Submit">
</div>
</div>
</form>
</main>
<script src="main.js"></script>
</body>
Clicking submit submits the form data to the page given in the action attribute in form. If you don't put this attribute in (as you have not done) the default is to submit to the current page.
To fix the issue you have, I would suggest that rather than using vanilla form submit, you do you submission via ajax. Making an ajax call is quite simple in jQuery, so I recommend you look into that.
There is an event that is triggered when you send a form. You can prevent your page to reload doing the following:
event.preventDefault()
you can find more about here: https://www.w3schools.com/jsref/event_preventdefault.asp
or here https://www.w3schools.com/jquery/event_preventdefault.asp
All you have to do is add event.preventDefault() to the first line of your onTabClick(event) function. After you preventDefault you can run whatever logic you want right there.
The way vanilla html/js interact is: On form submission, the page attempts to send the info to a server and then it refreshes to update with new information. The rise of SPAs has shifted the desired behavior, and you need to override the browser default behavior to stop the refresh.
Adding Ajax/Axios would work as most of those API libraries have built in functions to override the default, but it is not necessary.

Submit form on change of dropdown list in Semantic UI?

I would like to submit form when an element is selected - skipping pressing the submit button.
I tried using onchange="this.form.submit()", but it's not working here.
This is the code:
<form action="" method="get">
<div class="ui floating dropdown labeled search icon button dd">
<input type="hidden" name="nutr_code">
<span class="text">Select nutrient</span>
<div class="menu">
<div class="item" data-value="ca">Calcium</div>
<div class="item" data-value="fe">Iron</div>
<div class="item" data-value="mg">Magnesium</div>
<div class="item" data-value="zn">Zinc</div>
</div>
</div>
<br><br>
<input type="submit" value="Show results">
</form>
Because you are using GET method you can redirect with javascript by constructing the url yourself.
$('.ui.dropdown').dropdown({
'onChange': function (value, text, $choice) {
location.href = 'http://example.com/?nutr_code=' + value;
}});
Second option is changing the input field 'nutr_code' with the value from the callback as shown above
$('input[name="nutr_code"]').val(value);
and submit the <FORM/> from js.
$('form').submit();
EDIT:
Example of second option.
$('.ui.dropdown').dropdown({
'onChange': function (value, text, $choice) {
// Uncomment if semantic is not updating the input before submit.
//$('input[name="nutr_code"]').val(value);
$('form').submit();
}});
You need to define action in form tag or add some method to submit button
<input type="submit" value="Show results" onclick="someFunction()">
You need to define someFunction() too if you follow this way. Thanks
You Can Use Jquery
$(document).ready(function(){
$("input[name='nutr_code']").on('input',function(e){
$("input[type='submit']").trigger( "click" );
});
});

Trouble with binding events to Bootstrap 3 (button.js) button radios

I'm having trouble getting the correct value from a segmented control I made with the radio button component of button.js in Twitter Bootstrap 3. When I bind a click event to the segmented control that runs $.serialize() on the parent form, it return the unchecked value of the radio button along with all the other correct values from the other inputs.
I suspect it might be related to the fact that I can't bind this event directly to the segmented control's input. When I tried to bind the event directly to the input I didn't get a response back, so I bound it to the label.
Here's an example of the problem in a fiddle: https://jsfiddle.net/stevekas/9w94pL4o/
<form id="form">
<div id="radios">
<div class="radio">
<label class="major-category">
<input facet="exclusive" type="radio" name="hipsum" value="hashtag" />hashtag</label>
</div>
<div class="radio">
<label class="major-category">
<input facet="exclusive" type="radio" name="hipsum" value="farm-to-table" />farm-to-table</label>
</div>
<div class="radio">
<label class="major-category">
<input facet="exclusive" type="radio" name="hipsum" value="gastropub" />gastropub</label>
</div>
</div>
<!--/ #radios -->
<div id="segmented-control" class="btn-group btn-group-justified" data-toggle="buttons">
<label class="btn btn-default active">
<input type="radio" name="segmented-control" id="roof" value="roof" autocomplete="off" checked />roof</label>
<label class="btn btn-default">
<input type="radio" name="segmented-control" id="party" value="party" autocomplete="off" />party</label>
</div>
<!--/ #segmented-control -->
</form>
<script>
$('.radio input').on('click', function () {
var data = $('#form').serialize();
});
$('#segmented-control label').on('click', function () {
var data = $('#form').serialize();
});
</script>
It probably happens because the click for the label is processed before the click for the input (the label is higher in the DOM tree).
You can force debug to be called after all the events have been processed using setTimeout() without any delay, like this:
$('#segmented-control label').on('click', function () {
setTimeout(function() {
debug();
}, 0);
});
This works because setTimeout() enqueues a new event, which will be run after all the current pending ones.

Issues getting CasperJS to upload image to file field - tried CasperJS fill() and PhantomJS uploadFile()

I'm trying to use CasperJS to upload images to a web-form.
My form looks something like this:
<form action="" method="POST" enctype="multipart/form-data" class="form-vertical">
...
<legend>Campaign Banner</legend>
<div class="control-group image-field ">
<label class="control-label">Now Large</label>
<div class="controls">
<div class="file-field"><input id="id_now_large_image" name="now_large_image" type="file"></div>
<div class="image-preview"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group image-field ">
<label class="control-label">Now Medium</label>
<div class="controls">
<div class="file-field"><input id="id_now_medium_image" name="now_medium_image" type="file"></div>
<div class="image-preview"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group image-field ">
<label class="control-label">Now Small</label>
<div class="controls">
<div class="file-field"><input id="id_thumbnail_image" name="thumbnail_image" type="file"></div>
<div class="image-preview now-small"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
The submit button looks like this:
<div class="form-actions">
<button type="submit" class="btn btn-small ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text">Save changes</span></button>
</div>
I've put a Gist of the full HTML here: https://gist.github.com/victorhooi/8277035
First, I've tried using CasperJS's fill method:
this.fill('form.form-vertical', {
'now_large_image': '/Users/victor/Dropbox/CMT Test Resources/Test Banners/Default Banners/now_large.jpg',
}, false);
this.click(x('//*[#id="content-wrapper"]//button/span'));
I also did a this.capture(), and I saw that the file field had been filled in:
I'm not using the fill method's inbuilt submit, but I'm clicking on the submit button myself:
this.click(x('//*[#id="content-wrapper"]//button/span'));
I then do another capture, and I can see that the form has been submitted:
However, the image doesn't seem to have been uploaded at all.
I've also tried using PhantomJS's uploadFile() method:
this.page.uploadFile('input[name=now_large_image]', '/Users/victor/Dropbox/CMT Test Resources/Test Banners/Default Banners/now_large.jpg');
and then clicking on the submit button as well.
Same issue - the form field gets filled in - however, the image itself doesn't seem to get submitted.
Any ideas on how I can get the images to upload correctly here?
Since you are filling and submitting successfully, try a Wait command on the click.
casper.then(function() {
//+++ form fill here
//waits 1 sec
this.wait(1000, function() {
this.click(x('//*[#id="content-wrapper"]//button/span'));
});
});
Try this.
casper.thenOpen('about:blank', function(){
this.evaluate(function(){
var action = 'upload.php'
var html = '<form action="'+action+'" method="post" enctype="multipart/form-data">'
html += '<input type="file" name="files[]" multiple="multiple">'
html += '<button type="submit">Submit</button>'
html += '</form>'
document.write(html)
})
this.fill('form',{
'files[]': 'file.txt'
}, true)
this.waitFor(function(){
var uri = casper.evaluate(function(){
return document.documentURI
})
if ( 'about:blank' === uri ){
return false
}
return true
})
})

How to simulate the action in a form when submit?

first: always is the same action.
two: the form has multiple "CSS SUBMITS" like
<form action="/myaction" method="POST">
<a id="foo1" name="foo1" href="#" role="form_button">submit1!</a>
<a id="foo2" name="foo2" href="#" role="form_button">submit2!</a>
<a id="foo3" name="foo3" href="#" role="form_button">submit3!</a>
<input type="submit" id="canfoo" name="canfoo" value="I can process this"/>
</form>
<script>
$('a[role=form_button], div[role=form_button], span[role=form_button]').bind( 'click', function(){ $('form').submit(); } );
</script>
how can I do in /myaction this:
if ($_POST['foo1']) { action; return; } // :(
if ($_POST['foo2']) { action; return; } // :(
if ($_POST['foo3']) { action; return; } // :(
if ($_POST['canfoo']) { action; return; } // THIS WORKKKKKSS!!
How can I do to foo1, foo2, foo3 to work?
(I use jQuery like:
$('a[role=form_button], div[role=form_button], span[role=form_button]').bind( 'click', function(){ $('#actiontodo').val(this.id); $('form').submit(); } );
), then, in the other side (action),
I do:
IF ($_POST['ACTIONTODO'] == "foo") { action; return; }
BUT, I DON'T LIKE THIS SOLUTION! I WANT THE <A behave as well as <input type="submit"
Thank you very much for your help!
You shouldn't give priority to visual over usability, that's a huge mistake. Anyway, you can stylize any button/input to suit your needs without any problem, just grab a good CSS tutorial.
Don't reinvent the wheel.
You can use any element you want to trigger a .submit() event.
http://api.jquery.com/submit/
For example, this form:
<form id="targetForm" action="/myaction">
<input type="text" value="Oh hai!"/>
</form>
Can be submitted by the following jQuery:
$('#targetForm').submit();
However, you can style buttons and input fields without too much trouble in CSS.
Update:
I'd agree with Ben that you should reconsider doing form submissions this way.
For multiple submission triggers..
So if you have multiple triggers you need a hidden field to record this information for POST.
Something like this will do the trick...
<form id="targetForm" action="/myaction">
<input type="text" name="myText" value="Oh hai!"/>
<input type="hidden" name="whichTrigger" value="default" />
</form>
And then each trigger would do ...
$('#whichTrigger').val("myTriggerName"); // A different value for each one of course.
$('#targetForm').submit();
I solved this problem as is:
<form action="/myaction" method="POST">
<div id="foo1" name="foo1" href="#" role="form_button"><button type="submit">submit1!</button></div>
<div id="foo2" name="foo2" href="#" role="form_button"><button type="submit">submit2!</button></div>
<div id="foo3" name="foo3" href="#" role="form_button"><button type="submit">submit3!</button></div>
<input type="submit" id="canfoo" name="canfoo" value="I can process this"/>
</form>
!!!!!!!!!!!!!!!!!!! THANKS!

Categories