Reputation: 99
I have this form:
<form method="post" action="/cart" id="ajax">
{...}
<div>
{{ product.option | hidden_option_input }}
</div>
<button name="submit" type="submit" title="add to cart">Add to Cart</button>
</form>
The form is being loaded to the page via ajax, and its action page also preloaded via ajax in a different link in the navbar. I'd like to submit the form but prevent it from opening a new page when submitted. How can I go about this? I've tried:
<a href="/cart" class="new_popup mfp-ajax" onclick="this.parentNode.submit();return false;">Add to Cart</a>
to replace the button, but even though I've attempted to negate the default behavior with "return false;" it still reloads a new page on click. I can see the linked popup window just before the new page load, but it does not submit until the new page appears. I believe it's because the form is being loaded via ajax when a user clicks the link to it, therefore I cannot attach a script to it specifically because until it's on screen, it does not technically exist.
Upvotes: 0
Views: 55
Reputation: 44088
If I understand your question, you would like to just update a portion of the current page. If so, you will have to use AJAX for this:
Keep the "submit" button but make it a standard button and give it an id such as "submit":
<button id="submit" name="submit" title="add to cart">Add to Cart</button>
Then your JavaScript would handle the click event on the button as follows:
$(function() {
let submit = $('#submit');
submit.click( function() { //
submit.prop('disabled', true); // prevent a re-submission
var form = $('#ajax');
var request = $.ajax({
url: form.attr('action'), // get the action from the form
type: form.attr('method'), // get the method from the from
dataType: 'html', // the assumption is that we are dealing HTML here
data: form.serialize()
});
request.done(function(ajaxResult) {
// update the DOM with the results
$('#some_div').html(ajaxResult); // replace contents of <div id="some_div"></div> with new html
submit.prop('disabled', false); // re-enable the submit
});
});
});
You have to arrange for the results sent back to be just the HTML that is required to be updated.
Update
Since responding, you have added a comment with a link that suggests I may have misunderstood your intent. The phrase you used, "submit the form but prevent it from opening a new page when submitted" definitely can lead one to my original interpretation.
Upvotes: 1