Post a form and put results in a div - javascript

I can't get my form to submit correctly using jquery. I have tried using the tips here: https://api.jquery.com/jQuery.post/ and http://api.jquery.com/submit/ but can't figure out what I am missing to have the form submit and return the results to the div instead of reloading the page. It is supposed to call an external php page to get processed and return the results.
<script>
// On click "button.submit"
$("input[id^=formsubmit]").submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
$.get( "functions.php?do=adminmenu", function( data ) {
$( \".contentarea\" ).html( data );
});
return false;
});
</script>
<form action="#" name="submitForm">
<input type="textbox" name="test">
<input type="submit" value="Save Settings" id="formsubmit">
</form>
<div class="contentarea"></div>

Try to wrap your code inside DOM ready handler $(function() {...}); to make sure your DOM elements have been properly loaded.
Also, you can remove return false here as well as there's no need to escape the $(".contentarea" ) using \. So try this code:
$(function () {
$("input[id^=formsubmit]").submit(function (event) {
// Stop form from submitting normally
event.preventDefault();
$.get("functions.php?do=adminmenu", function (data) {
$(".contentarea").html(data);
});
});
});

The problem is that you're not passing the data to the php file. Furthermore you have not specified the type of data handled. And if you want to use POST you should use $.post(); and not $.get();
Try it like this: I've changed the function from .get to .post, added the data you want to send to the php file and specified a data type.
<script>
$(document).ready(function () {
$('#formsubmit').click(function () {
$.post("functions.php?do=adminmenu",{test_val:$('#test_input').value},function (data) {
$('.contentarea').html(data);
},"json");
});
});
</script>
<input id="test_input" type="text" value="">
<input id="formsubmit" type="submit" value="Save Settings">
<div class="contentarea"></div>
Last point: What is the php file returning? Is it only a string or what? Depending on this you need to modify the function writing the returned content in the '.contentarea'.
And by the way: When submitting the information via AJAX you don't need a form around it, as it just creates the need to escape the default behaviour when submitting a form.
If it still doesn't work let me know, I'll help you.

Related

how to execute first php function than javascript function onclicking/submiting a submit button

i have this input field:
<input type="submit" name="rregjistro" value="Rregjistro Tani Te Dhenat" onclick="openmodal()" >
I want first to execute POST script in PHP and than to open a modal popup using a javascript function.
Can you please help me!
Thanks in advance!
It is not possible to click using PHP because form submission is the action on the client's side, i.e in your browser. Events in the browser like this can be executed by javascript or other client language.
<form ... >
<input type="submit" name="rregjistro" value="Rregjistro" />
<!-- remove onclick attribute for now -->
</form>
<div id="myResult"></div>
<script>
$(function(){
$("input[name=rregjistro]").click(function(){
// url needs to belong to your domain
$.ajax({url: "/your_url_path", success: function(result){
$("#myResult").html(result);
open();
}});
});
});
</script>
You would still need to start with a javascript function first.
In jquery that would be something like that:
function open() {
$.post('http://url', $('#form').serialize(), function() {
alert('popup goes here');
})
)

Form submission recognition: works only when a textarea is active. What do I do wrong?

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) {
...
});

jquery form sometime did normal html post

javascript:
(function(){
$('form').ajaxForm({
beforeSend:function(){
$('.bar').width('0%');
$('#output').empty();
},
uploadProgress:function(event, position, total, percentComplete){
$('.progress').show();
$('.bar').width('0%');
},
complete:function(xhr){
$('.progress').hide();
$('.bar').width("100%");
$('#output').html(xhr.responseText);
}
});
})();
$("#upload").change(function(){
$("form").submit();
});
html:
<form method="POST" action="upload_ajax.php" name="upload" enctype="multipart/form-data">
<input id="upload" name="image" type="file">
</form>
I have an input-file use jquery.form.js post to php and output the message on div if php detect any problem with upload file.
I test few time, it works fine but sometime if i try to click & select image very fast. it become normal post. I place this from inside of a pop-box and using jquery to load() another page. therefor I will need to make sure the form will not run the normal html post.
is any way to solve this problem?
I haven't replicated the issue but you could try preventing the default action for the input being triggered by including preventDefault either just on the change event and also on the keyup event.
$("#upload").change(function(event){
event.preventDefault();
$("form").submit();
})
.keyup(function(event) {
event.preventDefault();
});

Infinite form submit with $(document).ready

i want to create a post form it'll get data from my url and post it to my database.
When i clicked the "Add" buton its working fine but when i try to add with $(document).ready function, I'm getting infinite loop. (My goal is submitting form every time i execute the file)
I've no knowlage about jquery and Im using this code:
<script type="text/javascript">
$(document).ready(function () {
document.forms["form1"].submit();
});
</script>
How can I get rid off infinite loop?
I'm guessing your form does not have action-attribute, hence it posts to itself. Add action attribute to the page you want to post to:
<form action="mypage.html"....
You will have to use cookie to store first load information and check it before submitting form. Set the expire time as per your project requirement. Before using jQuery cookie, you have add cookie plugin after jQuery library.
jQuery Cookie: jQuery Cookie plugin.
<script type="text/javascript">
$(document).ready(function () {
if (! $.cookie("cookieName")){
document.forms["form1"].submit(); // do your stuff
$.cookie("cookieName", "firstSet", {"expires" : 7}); // set cookie now
}
});
</script>
Hope will help!
Can you try?
$(document).one("ready",function(){
// submit form here
});
Use below code.
<form action="yourformname.html" method="post" enctype="multipart/form-data">
</form>
<input type="submit" value="Submit">
If there is any file upload control, then use enctype in form tag.
Maybe a flag can do the job.
var flag = true;
$(document).ready(function(){
if(flag){
// submit code here
flag = false;
}
});
Inside your form paste this line,
<input type="hidden" name="ispost" value="0" id="ispost">
And in jQuery add this, your issue will be resolved
<script type="text/javascript">
$(document).ready(function() {
if($('#ispost').val() != 'submit')
{
$('#ispost').val('submit');
$('#form1').submit();
}
});
</script>

How to prevent form from submitting multiple times from client side?

Sometimes when the response is slow, one might click the submit button multiple times.
How to prevent this from happening?
Use unobtrusive javascript to disable the submit event on the form after it has already been submitted. Here is an example using jQuery.
EDIT: Fixed issue with submitting a form without clicking the submit button. Thanks, ichiban.
$("body").on("submit", "form", function() {
$(this).submit(function() {
return false;
});
return true;
});
I tried vanstee's solution along with asp mvc 3 unobtrusive validation, and if client validation fails, code is still run, and form submit is disabled for good. I'm not able to resubmit after correcting fields. (see bjan's comment)
So I modified vanstee's script like this:
$("form").submit(function () {
if ($(this).valid()) {
$(this).submit(function () {
return false;
});
return true;
}
else {
return false;
}
});
Client side form submission control can be achieved quite elegantly by having the onsubmit handler hide the submit button and replace it with a loading animation. That way the user gets immediate visual feedback in the same spot where his action (the click) happened. At the same time you prevent the form from being submitted another time.
If you submit the form via XHR keep in mind that you also have to handle submission errors, for example a timeout. You would have to display the submit button again because the user needs to resubmit the form.
On another note, llimllib brings up a very valid point. All form validation must happen server side. This includes multiple submission checks. Never trust the client! This is not only a case if javascript is disabled. You must keep in mind that all client side code can be modified. It is somewhat difficult to imagine but the html/javascript talking to your server is not necessarily the html/javascript you have written.
As llimllib suggests, generate the form with an identifier that is unique for that form and put it in a hidden input field. Store that identifier. When receiving form data only process it when the identifier matches. (Also linking the identifier to the users session and match that, as well, for extra security.) After the data processing delete the identifier.
Of course, once in a while, you'd need to clean up the identifiers for which never any form data was submitted. But most probably your website already employs some sort of "garbage collection" mechanism.
Here's simple way to do that:
<form onsubmit="return checkBeforeSubmit()">
some input:<input type="text">
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
var wasSubmitted = false;
function checkBeforeSubmit(){
if(!wasSubmitted) {
wasSubmitted = true;
return wasSubmitted;
}
return false;
}
</script>
<form onsubmit="if(submitted) return false; submitted = true; return true">
The most simple answer to this question as asked: "Sometimes when the response is slow, one might click the submit button multiple times. How to prevent this from happening?"
Just Disable the form submit button, like below code.
<form ... onsubmit="buttonName.disabled=true; return true;">
<input type="submit" name="buttonName" value="Submit">
</form>
It will disable the submit button, on first click for submitting. Also if you have some validation rules, then it will works fine. Hope it will help.
Create a unique identifier (for example, you can hash the current time), and make it a hidden input on the form. On the server side, check the unique identifier of each form submission; if you've already received that hash then you've got a repeat submission. The only way for the user to re-submit is to reload the form page.
edit: relying on javascript is not a good idea, so you all can keep upvoting those ideas but some users won't have it enabled. The correct answer is to not trust user input on the server side.
Disable the submit button soon after a click. Make sure you handle validations properly. Also keep an intermediate page for all processing or DB operations and then redirect to next page. THis makes sure that Refreshing the second page does not do another processing.
You could also display a progress bar or a spinner to indicate that the form is processing.
Using JQuery you can do:
$('input:submit').click( function() { this.disabled = true } );
&
$('input:submit').keypress( function(e) {
if (e.which == 13) {
this.disabled = true
}
}
);
I know you tagged your question with 'javascript' but here's a solution that do not depends on javascript at all:
It's a webapp pattern named PRG, and here's a good article that describes it
You can prevent multiple submit simply with :
var Workin = false;
$('form').submit(function()
{
if(Workin) return false;
Workin =true;
// codes here.
// Once you finish turn the Workin variable into false
// to enable the submit event again
Workin = false;
});
On the client side, you should disable the submit button once the form is submitted with javascript code like as the method provided by #vanstee and #chaos.
But there is a problem for network lag or javascript-disabled situation where you shouldn't rely on the JS to prevent this from happening.
So, on the server-side, you should check the repeated submission from the same clients and omit the repeated one which seems a false attempt from the user.
You can try safeform jquery plugin.
$('#example').safeform({
timeout: 5000, // disable form on 5 sec. after submit
submit: function(event) {
// put here validation and ajax stuff...
// no need to wait for timeout, re-enable the form ASAP
$(this).safeform('complete');
return false;
}
})
The simpliest and elegant solution for me:
function checkForm(form) // Submit button clicked
{
form.myButton.disabled = true;
form.myButton.value = "Please wait...";
return true;
}
<form method="POST" action="..." onsubmit="return checkForm(this);">
...
<input type="submit" name="myButton" value="Submit">
</form>
Link for more...
Use this code in your form.it will handle multiple clicks.
<script type="text/javascript">
$(document).ready(function() {
$("form").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
});
</script>
it will work for sure.
This allow submit every 2 seconds. In case of front validation.
$(document).ready(function() {
$('form[debounce]').submit(function(e) {
const submiting = !!$(this).data('submiting');
if(!submiting) {
$(this).data('submiting', true);
setTimeout(() => {
$(this).data('submiting', false);
}, 2000);
return true;
}
e.preventDefault();
return false;
});
})
the best way to prevent multiple from submission is this
just pass the button id in the method.
function DisableButton() {
document.getElementById("btnPostJob").disabled = true;
}
window.onbeforeunload = DisableButton;
To do this using javascript is bit easy. Following is the code which will give desired functionality :
$('#disable').on('click', function(){
$('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>
Most simple solutions is that disable the button on click, enable it after the operation completes. To check similar solution on jsfiddle :
[click here][1]
And you can find some other solution on this answer.
This works very fine for me. It submit the farm and make button disable and after 2 sec active the button.
<button id="submit" type="submit" onclick="submitLimit()">Yes</button>
function submitLimit() {
var btn = document.getElementById('submit')
setTimeout(function() {
btn.setAttribute('disabled', 'disabled');
}, 1);
setTimeout(function() {
btn.removeAttribute('disabled');
}, 2000);}
In ECMA6 Syntex
function submitLimit() {
submitBtn = document.getElementById('submit');
setTimeout(() => { submitBtn.setAttribute('disabled', 'disabled') }, 1);
setTimeout(() => { submitBtn.removeAttribute('disabled') }, 4000);}
Just to add to the possible answers without bypassing browser input validation
$( document ).ready(function() {
$('.btn-submit').on('click', function() {
if(this.form.checkValidity()) {
$(this).attr("disabled", "disabled");
$(this).val("Submitting...");
this.form.submit();
}
});
});
An alternative to what was proposed before is:
jQuery('form').submit(function(){
$(this).find(':submit').attr( 'disabled','disabled' );
//the rest of your code
});
<h3>Form</h3>
<form action='' id='theform' >
<div class='row'>
<div class="form-group col-md-4">
<label for="name">Name:</label>
<input type='text' name='name' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<label for="email">Email:</label>
<input type='text' name='email' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<input class='btn btn-primary pull-right' type="button" value="Submit" id='btnsubmit' />
</div>
</div>
</form>
<script>
$(function()
{
$('#btnsubmit').on('click',function()
{
$(this).val('Please wait ...')
.attr('disabled','disabled');
$('#theform').submit();
});
});
</script>
This is a clean Javascript code that prevents multiple valid submissions:
<script>
var form = document.querySelector('form');
form.onsubmit = function(e){
if(form.reportValidity())
// if form is valid, prevent future submissions by returning false.
form.onsubmit = (e)=> false;
return true;
}
</script>

Categories