Submit a form with associated Live Event - javascript

I'm developing an web application using asp.net MVC and jQuery. I have in my page 10 forms and I'm using jQuery (live events) to do a async submit them. Something like this:
Everything works fine, but I need to format a Div with an image and when user clicks on this div I need to submit the form, but... the form is not executing the async operation like the submit button. It's executing default behavior...
My div is something like this:
My Script:
$("#jobs form").live('submit', function() {
$.post($(this).attb('action'), $(this).serialize(), function(result) {
//get and format result in my content divs...
});
});
My HTML:
<div id="jobs">
<% foreach(var job in Model) { %>
<form ...>
<!-- hide this button -->
<input type='submit' class='hide' id='mysubmitButton_<%=job.Id%>' />
<!-- need to submit this form -->
<div class='buttonImage' onclick="$('#mysubmitButton_<%=job.Id%>').click();"></div>
</form>
<% } %>
</div>
How can I set in 'onclick' to do a assync submit like the Submit Button in my page?
I don't know how to format this button, So I'm using an div or a hyperlink...
Thanks

Firstly, you have $.post($(this).attb('action'), .... This won't work -- the function is attr, so you need $.post($(this).attr('action'), .... Even better would be to avoid the jQuery object and use $.post(this.action, ....
For your submit image, the following code should work:
$('.buttonImage').live('click', function(){
$(this).closest('form').submit();
});
This will find the parent form and call the submit action on it, which should trigger the handler you defined in your question.
Just to note that it doesn't appear that you are preventing the default action occuring. You need to call your live method on the form like this:
$("#jobs form").live('submit', function(e) {
e.preventDefault();
// do the rest of your code
}
This prevents the default submit action occuring.

Related

gtag Linker not working on JS form.submit()

I used correct google tagging to enable cross-domain tracking. When the form is submitted by clicking on submit button the ?ga=... will be added to the destination URL but, it won't be added if I trigger the submit event by JS.
Code is as follows:
<head>
<script>
//All other common JS code exist
gtag('set', 'linker', {
'domains': ['example.com'],
'decorate_forms': true
});
gtag('config', 'UA-...');
</script>
</head>
<body>
<form method="POST" action="https://example.com/a/b">
<button type="submit">Submit</button>
</form>
<button id="bt">Click to submit form using JS</button>
<script>
$(document).on('click', '#bt', function(e){
$('form').submit();
});
</script>
</body>
If I add submit button to form and click on it directly the destination will be something like https://example.com/a/b?_ga=.... However, when I submit the form via JS, destination URL is just like the form action without GA appendix.
I have to note that I'm using gtag and not GTM.
It can be solved in two different ways:
Method 1
We can change the submit trigger to a click trigger on the submit button. Don't know why but, it solves the issue :)
$(document).on('click', '#bt', function(e){
$('form button[type="submit"]').trigger('click');
});
Method 2
We can handle anything we want in the submit event instead of the click event on some other button other than submit.
$(document).on('submit', 'form', function(e){
//Do your stuff and handle the event
return true;
});
Although the problem seems to be solved, the main question still exists and it seems it is pointing to a potential bug for gtag or jquery form.submit(). Therefore, if you can provide any solution or answer for the open question, go ahead and publish your post and I'll make your answer as a correct one.

What is the proper way to submit a form with JS and still post all form data successfully?

I'm working with an embedded app on our dev site and when I click the submit button inside the iframe, I am triggering a manual submission event on another form (not in an iframe) on that page. If I manually click the submit button for the form, my data posts and everything works correctly. However, I want to eliminate an extra user click and submit the external form automatically when a user submits the other form inside the iframe.
I've got everything working correctly on a base level. When a user clicks the submit button in the iframe, I am using JQuery to grab values from inside the iframe and set values in this external form. Using the jquery 'submit()' event, I am then able to submit that external form. The problem is, the page refreshes and the data doesn't go anywhere. If I remove the 'submit()' event and manually click the submit button, the form posts and in this case, adds a product with custom data to the product cart.
As a proof of concept, this is my 'iframed' HTML.
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Proof of Concept</h1>
<p>Total cost: $<span id="cust_price">222.22</span> plus shipping.</p>
<p>Quote number: <span id="quot_num">1546751962211</p>
<form method="POST" enctype="multipart/form-data" id="newQuoteForm">
<button type="submit" class="btn btn-primary" name="new-app-btn">Add to Cart</button>
</form>
</body>
<footer>
</footer>
</html>
Here is my on-page form that is OUTSIDE the iFrame.
<form method="POST" enctype="multipart/form-data" id="outer-quote-form" action="/checkout/">
<label class="quote_number">Quote Number:
<input type="text" id="quote_number" name="quote_number" value="">
</label>
<label class="custom_price">price:
<input type="text" id="custom_price" name="custom_price" value="">
</label>
<button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button>
</form>
Then, I have JQuery working to grab the iframed values and puts them in the exterior form. Afterwards, it fires a 'submit()' event on that form.
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("#outer-quote-form").submit();
return true; //return false prevents submit
});
});
</script>
Except when the jquery submit() event fires, the form appears to submit and the page refreshes but no data is posting as it does when I manually submit the form. Is there an extra step here or a better way to fire the form submit with post data?
Edit: Adding the PHP function that isn't firing on jquery submit() for context.
if (isset($_POST['ws-add-to-cart'])) {
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
global $woocommerce;
global $product;
$product_id = 138;
$woocommerce->cart->add_to_cart($product_id);
}
header("Location:https://www.devsite.com/checkout/");
}
The reason for the form not submitting because you are submitting the whole form without the submit button which is <button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button> which you have declared in php to get a post request like this
if (isset($_POST['ws-add-to-cart'])) {...
When you call submit(); on the form via the get method, you see '/new-quote/?quote_number=1546751962211&custom_price=222.22'
but where's ws-add-to-cart, it's not submitting and that's the reason why php isn't getting your request
The fix will be to add .click() on the submit button instead of submitting the form
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementsByName("ws-add-to-cart").click();
}
</script>
Or in your script in case you want to use jquery, this is the fix
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("button[name=ws-add-to-cart]").click();
return true; //return false prevents submit
});
});
</script>
This is definitely the answer and sorry for my stupidity, i didn't pay required attention before
try removing return true from your js code
if that doesn't work, try changing the <form method="POST" to <form method="GET" to debug the values in the url just for checking that the form actually fires up with values
Alternative method: Old school method
code for page OUTSIDE the Iframe
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementById("outer-quote-form").submit();
}
</script>
code for the Iframe file
<script type="text/javascript">
$('#newQuoteForm').on('submit', function(event) {
var Page = window.parent;
var allVals = {
price:$('#cust_price').text(),
num:$('#quot_num').text()
}
Page.enterVals(allVals);
event.preventDefault();
});
</script>
Explanation
window.parent refers to the parent window where the iframe is loaded on, with reference to this we can trigger functions that are in the parent window so by this, we created a variable and added the information which is sent by the function enterVals() to the window
The enterVals() function just puts the values and submits the form without any jQuery.
What is the proper way to submit a form with JS?
This might not be the 'best' way to submit a form with js but is cross-browser which is good

How to avoid form submission in case of error?

I have the form like below
<form id="myform" class="form-horizontal" class="collapse in">
<fieldset>
<!-- form fields are here -->
<div class="form-actions">
<button class="btn btn-inverse" id="search" name="search" data-loading-text="Searching...">Search</button>
</div>
</fieldset>
</form>
And I use the following code to act once button is pressed:
$("#search").click(function() {
try {
// some javascript with syntax error is here
} finally {
return false; // don't submit form automatically
}
});
But if my javascript contains syntax errors, then the form is submitted regardless of try .. finally. How can I fix that? The form should be never submitted automatically.
Set the button type to "button".
button: The button has no default behavior. It can have client-side
scripts associated with the element's events, which are triggered when
the events occur.
<button type="button"...>Search</button>
The form won't submit at all if that is the case until you tell it to explicitly submit via Javascript.
See HTML5 specs for this simple solution. http://www.w3.org/TR/2011/WD-html5-20110525/the-button-element.html#attr-button-type
Set the action of the form to something that isn't correct, like action="error.html". Then as the final step in the form submit process, dynamically set the action to the correct link.
You can also make the button not submit at all, and submit the form manually:
$('#myForm').submit();
Use event.preventDefault at the beginning of the event and trigger the submit yourself.
$("#search").click(function(event) {
event.preventDefault();
// some javascript with syntax error is here
var foo = "bar";
alert(foobar); // ERROR
// if syntax error occurs in this scope, the form won't submit
$(this).closest("form")[0].submit();
});
DEMO
$("#search").click(function(e) {
e.preventDefault();
try {
// some javascript with syntax error is here
} finally {
return false; // don't submit form automatically
}});
on the click function, prevent the default action. Then if the code does pass, then manually call the submit
$('#myForm').submit();

MVC3: Clicking a submit button to submit a form does not render partial view

Ok here is the deal: Im using BeginRouteForm to submit a search. Anyway, when the button is not set to submit and I click the button, it runs the search just fine and it behaves as it should, meaning that the content is rendered properly. When the button IS set to a type of submit and the button is clicked, the content that is returned is simply some text and the HTML is not rendered at all.
It is important to note that the controller is attempted to return a partial view that is using javascript to replace some of the content using ajax (this means the content type is 'text/javascript').
Controller Method:
public ActionResult Search()
{
[Do Some Work]
return JsView("Index.js");
}
JsView("Index.js") just sets the content type to 'text/javascript' and returns the partial view that coincides with the parameter that was passed
Form Snippit:
<div style="float:right;">
#using (Html.BeginRouteForm(ControllerActionName, SearchRouteValues, FormMethod.Get, new { id = "worklistSearch" }))
{
<input type="text" placeholder="Search Cases" id="SearchCriteria" name="SearchCriteria" value="" />
<input class="search image-button no-text filter" value="Filter" id="worklist-search-button" />
}
</div>
PS: I seem to need to make the button a type of submit in order to get the form to submit using the enter key.
I would like to know how I can make this work so that it renders the view properly and allows me to click the submit button.
Based on your description, it appears that you want to capture the submit event for your form, then make your AJAX call to your controller. If this is what you want, you then need to prevent the submit event from propagating, so that no POST occurs.
Using jquery, do something like this:
$("form").submit(function() {
// make AJAX submission to controller
// process JS returned from controller
// stop submit event from propagating
return false;
});

Handle submit of a form that inside of a included jsp with jQuery?

I use:
...
$('#form').submit(function(e) {
...
<div id="list">
<jsp:include page="list.jsp" />
//form was here
</div>
...
to handle my form's submit and it works. I can handle my form's submit.
However I moved my form into the list.jsp but I think that it can't recognize it inside of an jsp file so I can't handle my form's submit. I want that ability within list.jsp too.
What should I do?
Based on the code provided, it looks like you are trying to attach the event to the form before it's rendered. Wrap the event binding in an onready function.
$(function(){
$("#form").submit(function() {
...
});
});
If this is what you are doing, make sure that the form rendered by the jsp include has an id="form".

Categories

Resources