I had implemented a preview button and a save button in a profile page, submitting a form to two different pages. One with the code to save data, and one where is a fake page that show the informations as the original page will show.
This is the code
<form id="personal-information-form" method="post" enctype="multipart/form-data">
<!--Some code to recollect info -->
<script type="text/javascript">
function submitForm(action)
{
document.getElementById('personal-information-form').action = action;
document.getElementById('personal-information-form').setAttribute("target", "_blank");
document.getElementById('personal-information-form').submit();
}
</script>
<p><input type="submit" name="preview-info" class="my-buttons" onclick="submitForm('url_to_preview')" value="Preview" >
<span><input type="submit" name="save-info" class="my-buttons" value="Save"></span></p>
</form>
If I click once on one of the two buttons, all work fine.
If I click in the preview first and then in the save button, the save button don't save the info, instead show me the preview page. Why? How can I solve it?
When you click the Preview button you are permanently setting the action attribute of the form to the preview URL.
Generally I would prefer to do something like this with AJAX rather than with form hackery, but you could amend your current solution like this:
function submitForm(action, target) {
var form = document.getElementById('personal-information-form');
var originalTarget = form.target;
var originalAction = form.action;
form.setAttribute("target", target || "_self");
form.action = action;
form.submit();
form.target = originalTarget;
form.action = originalAction;
return false;
}
This will restore the current action and target after submitting. (Haven't tested; let me know how this goes).
Then your onclick for the Preview button should say submitForm('url_to_preview', '_blank').
Related
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:
Add to Cart
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.
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.
I have two php pages. In the first.php page user choose orders and a div is filling with this content, no problem. And there is a confirm button to confirm these list. When the user click this button, second.php page should be opened and the contents of the div should be displayed on that page. This is my html code for the first.php div and confirm button.
<form method="post">
<div class="col-md-5" id="orderList">
<h3 align="centre">Order List</h3>
</div>
</form>
<form role="form" method="post" action="second.php">
<div id="firstConfirmButton">
<button type="submit" name="firstConfirmButton" id="firstConfirmButton" class="btn btn-primary btn-lg">Confirm</button>
</div>
</form>
This is the javascript code to post the contents to second.php. First alert is working fine but second alert is not.
$("#firstConfirmButton").click(function() {
var content = $('#orderList').html();
alert(content);
$.post("second.php", { html: content})
.done(function(data) {
alert(data);
$('#confirmForm').empty().append(data);
});
});
Second.php page has the confirForm div and I want to display the contents in this.
<div id="confirmForm"> </div>
Where is the problem?
Your button is a submit button, so if you don't cancel the default event, the form will be submitted the regular way as well.
You need to capture the event and cancel it:
$("#firstConfirmButton").click(function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code
Or in modern versions of jQuery:
$("#firstConfirmButton").on('click', function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code
You submit the form to the page second.php by using the POST method, so the data can be retrieved from the second page by using this PHP code:
var_dump($_POST);
So basically, the data is stored within the $_POST array.
Regarding your second question. You need to avoid that you submit the default form if you first need to grab a value form a Javascript. You can do that by something like that:
$("#firstConfirmButton").click(function(e) {
var data = $('#orderList').html();
e.preventDefault();
//...
}
This will avoid that your submit button submits the form without adding the desired POST data to it.
I have a page where Ajax updates the feed every once in a while. Under each post there's a textarea for a reply. JQuery/Ajax can post the reply to the database without any problems when the textarea is active. I press the submit button and everything goes well.
However, if I click somewhere else on the page and the textarea becomes inactive, the submit button doesn't work anymore like it should: it submits the form to root and doesn't run the Ajax function.
Can you figure out what's wrong in my code? Thank you for your help!
There are as many forms as there are messages on the pages. The forms look like this:
<form class="reply-form">
<textarea id="reply-11123" name="comment" class="plain-editor"></textarea>
<input type="submit" class="submit" value="Reply" />
<input type="hidden" value="URL HERE" name="url" />
</form>
Ajax code (at <head>) looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.reply-form').on('submit', function (event) {
event.preventDefault();
var $form = $(this),
message_data = $form.find('textarea[name="comment"]').val(),
url = $form.find('input[name="url"]').val();
var postData = {};
var prefix = 'data';
postData[prefix + '[message]'] = message_data;
var posting = $.post(url, postData);
});
}
</script>
If your forms are being added to the page dynamically then you need a different event binding that will attach itself to all current and future forms. The current binding you have is called a direct binding, but what you really need is a delegated binding. A different usage of on() will give you that:
$(document).on('submit', 'form.reply-form', function (event) {
...
});
I have the following code:
Html:
<form action="/" id="mainForm" method="get">
<input type="text" name="val1" />
<button id="cmdSubmit">Submit</button>
</form>
<button id="cmdSubmit2">Submit 2</button>
Javascript:
$("#cmdSubmit2").bind('click', function () {
Submit2();
});
var Submit2 = function() {
var form = $("#mainForm").clone();
form.attr("action", "/testing");
form.submit();
}
What I'm trying to do is dynamically change the action attribute of a form with javascript and then submit it (to a different url).
What I expect to happen (in JsFiddle) is that clicking the submit button should load the jsfiddle home page, and clicking the Submit2 button should load a 404 page since the /testing url doesn't exist.
This works fine in chrome (28.0.1500.95), but does not work in Firefox (23.0.1) or IE for that matter(10.0.9200.16660).
None of these browser show any errors in the console either - I'm stumped. Any ideas?
JSFiddle
EDIT: I do actually have to clone the form, forgot to mention that. Also, this works fine in Safari (v5.1.7).
You need to somehow insert it in the DOM :
function Submit2() {
var form = $("#mainForm").clone();
form.attr("action", "/testing");
form.hide().appendTo('body');
form.submit();
}
fiddle
Works for me (FF 23.0)
You don't need to clone() the form. Try this:
var Submit2 = function() {
var form = $("#mainForm");
form.prop("action", "/testing");
form.submit();
}
Updated fiddle
I'm using Javascript to change a form's URL when you submit the form. If that URL contains a hash string (#), then Internet Explorer ignores it and just submits to the part of the html before that. Firefox and Chrome are fine.
Demonstration:
<script type="text/javascript">
function changeURL() {
var myform = document.getElementById('myform');
myform.setAttribute("action", "page2.html#hello");
return false;
}
</script>
<form id="myform" action="page1.html" method="get" onsubmit="changeURL()">
<input type="submit">
</form>
If I change the method to a "post" then it's fine. If I use a "get", IE lands on page2.html but without the #hello in the URL.
This happens regardless of if I use jquery or only javascript, tried each of the following:
myform.action = "page2.html#hello";
myform.attr("action", "page2.html#hello");
myform.get(0).setAttribute("action", "page2.html#hello");
Any suggestions (assume that I have to keep the method as a 'get', and that I must use a hash in the URL, and that I must use Javascript to change this action dynamically)?
Testing on my own in IE8 reveals that it does insist that the hash (#hello) come after the query string (?foo=bar) in a URL. Sadly, your form doesn't do this for you and there's no way to force it to do so when submitting the form.
Try encoding the hash in the form instead:
<script type="text/javascript">
function changeURL() {
var hidden = document.createElement('input');
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "hash");
hidden.setAttribute("value", "hello");
var myform = document.getElementById('myform');
myform.setAttribute("action", "page2.html");
myform.appendChild(hidden);
// return false;
}
</script>
<form id="myform" action="page1.html" method="get" onsubmit="changeURL()">
<input type="submit">
</form>
And at the top of page2.html, extract it back out:
<script type="text/javascript">
var qs = window.location.search.substring(1);
var qsarr = qs.split("&");
for (var i=0; i<qsarr.length; i++) {
var tarr = qsarr[i].split("=");
if (tarr[0]==="hash") {
window.location.hash = tarr[1];
}
}
</script>
I believe that IE just behaves differently with the hash and I don't think it is is meant to be used in this manor.
No javascript in the following will produce the same results...displays in FF and not in IE
<form action="#test" method="get">
<input type="text" value="test" />
<input type="submit" />
</form>
At least you know it's not a javascript problem. I lied about the question mark lol oops.
In the end we decided we could just update window.location.href to go to the new location rather than submit the form. This might seem like an odd answer, but actually the way we were handling our form meant this wasn't a problem to do. i.e. we were disabling all our form fields (hence no querystring being appended to the URL normally), then generating one of several different SEO-friendly style URLs based on what the form fields contained, then updating the form action and submitting the form. So now we do all that but don't bother submitting the form, just change the page location.