How do I submit a form after JQuery Ajax validation? - php

I can't get the .submit() jquery function to work I've boiled down everything in my code to:
<form action="/server/addserver.php" method="post" accept-charset="utf-8" id="mainform"><input type="text" name="test" value="" /><input type="submit" name="submit" value="Submit" id="submitbutton" /></form>
<script type="text/javascript">
$("#submitbutton").click(
function(){
$("#mainform").submit();
return false;
});
</script>
Seems to me this should 1 - stop the default behavior of the button then 2 - manually submit the form.
If i swap out .submit(); with .hide(); that works. Is this not the preferred way to manually submit a form after first running some ajax validation ?
Thanks

You can do:
$(function () {
$('#mainform').submit(function () {
if (isFormValid()) { // do your validation
return true;
}
return false;
});
});
This will run when the form is submitted (just use the normal <input type="submit" /> button). Returning false here will prevent the page from posting.
If you wanted to bind the event to your button, try it like this:
$(function () {
$('#submitbutton').click(function () {
if (isFormValid()) { // do your validation
$('#mainform').submit();
}
return false;
});
});

First, there are a couple things I think you should be aware of:
Anytime you want to bind an event to a DOM element right off the bat like that, you should make sure the page has fully loaded. If in doubt, wrap your code inside $(document).ready(function() { /* code to execute after page load */ });.
Also, the .trigger("submit") method doesn't work if the name attribute of the input[type="submit"] element is set to the value "submit". Since .submit() called with no arguments is a shortcut for .trigger('submit'), then anytime you call JQuery's .submit() method on an element, you would want to make sure and assign the input's name attribut something other than "submit".
Now, to answer your questions; first about whether returning false is the preferred way to manually submit a form, the answer is usually no. The reason is that returning false does three things, and you usually don't want to do all of them. It prevents the default browser behavior for the event, it also stops the event from bubbling, and, it immediately returns, exiting the function. Usually, you probably just want to either event.preventDefault() or event.stopPropagation()… or even unbind the event altogether. In this case though, in my opinion, returning false rather than calling the appropriate evening methods seems to muddle the intention of your code.
If you also need to prevent the default browser action on the submit event, you can use JQuery's alternate trigger method:
$('#mainform').triggerHandler('submit');
.
Though, the validator method itself should probably be where you call form.submit() in the case that there are no errors. It should also be where you handle form submission, since it is the gatekeeper, so to speak.
All in all, if you're going to the Validator plugin, you should follow it's own conventions. Ensure the form does a default submit by adding name="submit" to your submit button and then remove all the JQuery code you have and replace it with this example from the Validator documentation:
$("#mainform").validate({
submitHandler: function(form) {
form.submit(); // Don't use a JQuery selector here, just "form"
}
});
That should allow the plugin to operate as expected. The last step would be to add your validation rules, of course. I hope that helps. If you still have trouble with eventing, try using JQuery's Event object methods for debugging on the console.

Related

Recaptcha invisible never sends form name in post [duplicate]

Ok, this is less of a question than it is just for my information (because I can think of about 4 different work arounds that will make it work. But I have a form (nothing too special) but the submit button has a specific value associated with it.
<input type='submit' name='submitDocUpdate' value='Save'/>
And when the form gets submitted I check for that name.
if(isset($_POST['submitDocUpdate'])){ //do stuff
However, there is one time when I'm trying to submit the form via Javascript, rather than the submit button.
document.getElementById("myForm").submit();
Which is working fine, except 1 problem. When I look at the $_POST values that are submitted via the javascript method, it is not including the submitDocUpdate. I get all the other values of the form, but not the submit button value.
Like I said, I can think of a few ways to work around it (using a hidden variable, check isset on another form variable, etc) but I'm just wondering if this is the correct behavior of submit() because it seems less-intuitive to me. Thanks in advance.
Yes, that is the correct behavior of HTMLFormElement.submit()
The reason your submit button value isn't sent is because HTML forms are designed so that they send the value of the submit button that was clicked (or otherwise activated). This allows for multiple submit buttons per form, such as a scenario where you'd want both "Preview" and a "Save" action.
Since you are programmatically submitting the form, there is no explicit user action on an individual submit button so nothing is sent.
Using a version of jQuery 1.0 or greater:
$('input[type="submit"]').click();
I actually was working through the same problem when I stumbled upon this post. click() without any arguments fires a click event on whatever elements you select: http://api.jquery.com/click/
Why not use the following instead?
<input type="hidden" name="submitDocUpdate" value="Save" />
Understanding the behavior is good, but here's an answer with some code that solved my problem in jquery and php, that others could adapt. In reality this is stripped out of a more complex system that shows a bootstrap modal confirm when clicking the delete button.
TL;DR Have an input dressed up like a button. Upon click change it to a hidden input.
html
<input
id="delete"
name="delete"
type="button"
class="btn btn-danger"
data-confirm="Are you sure you want to delete?"
value="Delete"></input>
jquery
$('#delete').click(function(ev) {
button.attr('type', 'hidden');
$('#form1').submit();
return false;
});
php
if(isset($_POST["delete"])){
$result = $foo->Delete();
}
The submit button value is submitted when the user clicks the button. Calling form.submit() is not clicking the button. You may have multiple submit buttons, and the form.submit() function has no way of knowing which one you want to send to the server.
Here is another solution, with swal confirmation. I use data-* attribute to control form should be send after button click:
<button type="submit" id="someActionBtn" name="formAction" data-confirmed="false" value="formActionValue">Some label</button>
$("#someActionBtn").on('click', function(e){
if($("#someActionBtn").data("confirmed") == false){
e.preventDefault();
swal({
title: "Some title",
html: "Wanna do this?",
type: "info",
showCancelButton: true
}).then(function (isConfirm) {
if (isConfirm.value) {
$("#someActionBtn").data("confirmed", true);
$("#someActionBtn").click();
}
});
}
});
i know this question is old but i think i have something to add... i went through the same problem and i think i found a simple, light and fast solution that i want to share with you
<form onsubmit='realSubmit(this);return false;'>
<input name='newName'/>
<button value='newFile'/>
<button value='newDir'/>
</form>
<script>
function getResponse(msg){
alert(msg);
}
function realSubmit(myForm){
var data = new FormData(myForm);
data.append('fsCmd', document.activeElement.value);
var xhr = new XMLHttpRequest();
xhr.onload=function(){getResponse(this.responseText);};
xhr.open('POST', 'create.php');
// maybe send() detects urlencoded strings and setRequestHeader() could be omitted
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(new URLSearchParams(data));
// will send some post like "newName=myFile&fsCmd=newFile"
}
</script>
summarizing...
the functions in onsubmit form event are triggered before the actual form submission, so if your function submits the form early, then next you must return false to avoid the form be submitted again when back
in a form, you can have many <input> or <button> of type="submit" with different name/value pairs (even same name)... which is used to submit the form (i.e. clicked) is which will be included in submission
as forms submitted throught AJAX are actually sent after a function and not after clicking a submit button directly, they are not included in the form because i think if you have many buttons the form doesn't know which to include, and including a not pressed button doesn't make sense... so for ajax you have to include clicked submit button another way
with post method, send() can take a body as urlencoded string, key/value array, FormData or other "BodyInit" instance object, you can copy the actual form data with new FormData(myForm)
FormData objects are manipulable, i used this to include the "submit" button used to send the form (i.e. the last focused element)
send() encodes FormData objects as "multipart/form-data" (chunked), there was nothing i could do to convert to urlencode format... the only way i found without write a function to iterate formdata and fill a string, is to convert again to URLSearchParams with new URLSearchParams(myFormData), they are also "BodyInit" objects but return encoded as "application/x-www-form-urlencoded"
references:
https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
https://developer.mozilla.org/en-US/docs/Web/API/FormData
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit#usage_notes (proves that form.submit() does not emulate a submit button click)
Although the acepted answer is technicaly right. There is a way to carry the value you'd like to assign. In fact when the from is submited to the server the value of the submit button is associated to the name you gave the submit button. That's how Marcin trick is working and there is multiple way you can achive that depending what you use. Ex. in jQuery you could pass
data: {
submitDocUpdate = "MyValue"
}
in MVC I would use:
#using (Html.BeginForm("ExternalLogin", "Account", new { submitDocUpdate = "MyValue" }))
This is actually how I complied with steam requirement of using thier own image as login link using oAuth:
#using (Html.BeginForm("ExternalLogin", "Account", new { provider = "Steam" }, FormMethod.Post, new { id = "steamLogin" }))
{
<a id="loginLink" class="steam-login-button" href="javascript:document.getElementById('steamLogin').submit()"><img alt="Sign in through Steam" src="https://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_01.png"/></a>
}
Here is an idea that works fine in all browsers without any external library.
HTML Code
<form id="form1" method="post" >
...........Form elements...............
<input type='button' value='Save' onclick="manualSubmission('form1', 'name_of_button', 'value_of_button')" />
</form>
Java Script
Put this code just before closing of body tag
<script type="text/javascript">
function manualSubmission(f1, n1, v1){
var form_f = document.getElementById(f1);
var fld_n = document.createElement("input");
fld_n.setAttribute("type", "hidden");
fld_n.setAttribute("name", n1);
fld_n.setAttribute("value", v1);
form_f.appendChild(fld_n);
form_f.submit();
}
</script>
PHP Code
<?php if(isset($_POST['name_of_button'])){
// Do what you want to do.
}
?>
Note: Please do not name the button "submit" as it may cause browser incompatibility.

Stop form from refreshing on submit

I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});

Cannot change form action via jquery

I'm trying to change my form action to another link during submit using jquery. Please view the following code:
javascript
$(document).ready(function(){
$("form[name='search']").submit(function(e){
var submit=$(this);
submit.attr('action','?search='+submit.find("input[name='tsearch']").val());
});
});
HTML/PHP
<form name="search" method="post">
<input class="inputbox" type="text" name="tsearch" value="<?php echo $text_search; ?>" />
Though i can't seem to get it working. Any help here will be appreciated.
Here's a working example: http://jsfiddle.net/RmKDT/4/
You can see by the alerts that the action is changing. You just need to resubmit the form as well.
Edit: Fixed potential infinite loop
$(function(){
var submitted = false;
$('form').submit(function(e){
if (submitted == true) {
return;
}
e.preventDefault();
var action = $(this).attr('action');
alert(action);
$(this).attr('action', 'two.php');
action = $(this).attr('action');
alert(action);
submitted = true;
// resubmit the form
$(this).submit();
});
});
Your code seems to be fine. There are a few things you can try to get this working.
Be sure your script is being pulled into the page, one way to check is by using the 'sources' tab in the Chrome Debugger and searching for the file else in the html head section
Be sure that you've included the datatale script after you've included jQuery, as it is most certainly dependant upon that.
Check whether jQuery is included properly and once only.
Watch out for jQuery conflicts. There is some other library which is overridding $, so your code is not working because $ is not an alias for jQuery anymore. You can use jQuery.noConflict() to avoid conflicts with other libraries on the page which use the same variable $.
alert('?search='+submit.find("input[name='tsearch']").val()) see whether you are getting the value you want.

submitting a form with out using submit?

I want to submit a form without using submit button how can i do that?
Using jQuery you can do this. Check this
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
Use javascript. Something like
document.forms["myform"].submit();
or
document.myform.submit();
You need to set the name (1. example) or id (2. example) attribute for your form to make this work.
Through javascript you can call form.submit()
Use jquery's form methods to serialize the form variables and send via ajax.
http://api.jquery.com/category/forms/
You can add some javascript logic to ANY submit methods by passing a function to the form's submit event handler.
Eg.
$('#my_form').submit(function(){
alert('Handler for .submit() called.');
return false;
});
Returning false blocks the form from being submitted by all other methods (including the "traditional" submit button). You'd put your ajax code before the return statement.
or add bind the submit function to ANY dom element (image,button,etc.)
Eg.
$('#my_cool_image').click(function() {
$('#my_form').submit();
});
See more at http://api.jquery.com/submit/
Good Luck

How to POST without using Submit?

I want to post the Form but don't want to use the Submit method. If I use JQuery, how to handle the Form input controls?
You can use the jQuery AJAX .post function functions. An example (untested, but should be working):
<script>
function postit(obj) {
var data = $(obj).serialize();
$.post($(obj).attr("action"), data, function() {
//Put callback functionality here, to be run when the form is submitted.
});
}
</script>
<form action="posthandler.php" onsubmit="postit(this); return false;">
<input type="text" name="field">
<input type="submit">
</form>
Also, read about serialize
(Of course you need to include the jQuery library in your code before using this code).
Just create a function that is triggered by whatever event you want, for example: (found this code in another question)
function example() {
// get all the inputs into an array.
var $inputs = $('#myForm :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
}
After that you can do whatever you want with the input values. You might want to consider using more advanced processing though, there are plenty of plugins that can provide this kind of functionality.
I am not sure if I understood the question correctly.
If you don't want to use submit(), you can do the same thing via jQuery.post() using Ajax. The main difference is you have to construct the key value data from the input fields yourself rather than the browser doing it automatically and you won't get a page refresh.
Either Post function or Load function will work.
#PRK are you trying to post the Form when the page loads or when a user hit a button?
load(url, parameters, callback)
eg:
$("#loadItHere").load("some.php", {somedata: 1});

Categories