Suppose I have a form :
<form id="myForm" method="POST" action="/something/somewhere">
<input type="text" name="textField" />
<input type="submit" name="foo" value="bar" />
</form>
the /something/somewhere action does not return a complete html page, but just a fragment.
I would like to let the submit button do its posting job, but catch the result of this post and inject it somewhere in the DOM.
The jQuery submit happens before the form is actually submitted. An exemple of how it could work is:
$('#myForm').posted(function(result)
{
$('#someDiv').html(result);
});
Any way to do this?
Description
You can use the jQuery .post() and .serialize() method for that.
.post() Load data from the server using a HTTP POST request.
.serialize() Encode a set of form elements as a string for submission.
.preventDefault() If this method is called, the default action of the event will not be triggered. In your case the normal submit.
Sample
Html
<form id="myForm" method="POST" action="/My/MyActionMethod">
<input type="text" name="textField" />
<input type="submit"/>
</form>
<div id="someDiv"></div>
jQuery
$(function() {
$('#myForm').live('submit', function (e) {
var form = $(this);
e.preventDefault();
$.post(form.attr('action'), form.serialize(), function (result) {
$('#someDiv').html(result);
});
});
});
MVC Controller
public class MyController : Controller
{
[HttpPost]
public ActionResult MyActionMethod(FormCollection forms)
{
// do something with forms["textField"];
return Content("<b>Hello World!</b>");
}
}
If you have trouble getting it to work (thanks IE), try
event.preventDefault ? event.preventDefault() : event.returnValue = false;
More Information
jQuery.post()
jQuery.serialize()
event.preventDefault()
While you can hack a simple example yourself using .post and .serialize, if you want to do anything more than trivial, I'd suggest looking into this plugin, which is (from what github and the project page says) actively community-maintained by the jQuery folks.
Related
Context
I have a working standard form, with method POST, with a standard submit button, and I would like to leave this in this way.
<form id="myform" method="post"... >
...
<input type="submit .../>
</form>
However in some circumstances, I would like to programmatically send the form data to server side and re-render the form. Sending the form data with GET would be great this case.
Question
How can I achieve that document.myform.submit(); use the GET method, instead the POST what is declared in the <form ...> element?
You can always send your data to your serverside by AJAX request and do whatever you please by the response value that you receive. There are plenty of examples if you research it.
Also here's another source to help you get through this problem.
Click here
In my opinion, I will do this(Explicitly Submit form from js)...
<form id="my-form" method="post"... >
...
<button id="btn-submit" type="button" .../>
</form>
<script>
const submit = document.getElementById('btn-submit');
submit.addEventListener('click', function(event) {
event.preventDefault();
const form = document.getElementById('my-form');
if(SOME CONDITION) // some usecases in which we need different method.
{
form.method = 'POST';
} else {
form.method = 'GET';
}
form.submit();
});
</script>
I was looking for a simple JQuery plugin to make it easy to submit forms via Ajax and I found Alajax which I found handy as it integrates into a typical HTML form and does all the job. Unfortunately I don't understand how to prevent the form to be sumbitted if it is not validated (the official web site is quite poor of documentation, nor the author has answered my mail).
For example the following form is submitted via Ajax: the plugin intecepts the form, grabs the 'name' attributes and call send.php as a normal form
<form id="myform" action="send.php">
<input type="text" name="firstname"
<input type="submit" value="Submit">
</form>
<script>
$(document).ready(function (){
$("#myform").alajax();
});
</script>
Alajax has some options as explained:
$('#myform').alajax({
type: '' // Type of return value. Default is "text". Other values are: "json", "xml", "jsonp"
beforeSend: function (){} // Code to run before sending the form
success: function(){} // Code to run when the AJAX call success
error: function(){} // Code to run when error occures
});
But the following code still submits the form:
$('#myform').alajax({
beforeSend: function (){
// Validation code is here. Suppose that form is not validated,
return false; // this should'nt stop submitting the form?
}
});
The code inside the beforeSend option is correctly executed (as I tested it with a call to console.log), but the form is still submitted. How I can prevent the form to be submitted upon an error? I also tried preventDefault without success.
You can't prevent the form submition with alajax. however you can use another submit listener to prevent the event from reaching alajax.
<form id="myform" action="send.php">
<input type="text" name="firstname">
<input type="submit" value="Submit">
</form>
<script>
$(document).ready(function (){
$("#myform").submit(function(e){
e.preventDefault();
if(/* form is invalid */){
e.stopImmediatePropagation();
}
});
$("#myform").alajax();
});
</script>
edit
There is another way you can throw new Error('asd'); inside the beforeSend function.
Why is this form sending data twice? Also, the second time, the data is "undefined".
The form:
<form action="/loginPage" method="POST" >
Username: <input type="text" id="username"> <br><br>
Password: <input type="text" id="password"> <br><br>
<input type="submit" id="Login" value="Login" >
</form>
The client-side script:
$(document).ready(function(){
$('form').submit(function(event){
//event.preventDefault(); This prevents from sending data twice, but then the page doesn't redirect to "Hi, <username>"
$.post("/loginPage",{username: $("#username").val(),password: $("#password").val()}, function(data){
;
});
});
});
The server-side script:
app.post('/loginPage', function(req, res) {
var username = req.body.username;
console.log("Now, "+username);
res.send("Hi, "+username);
//res.sendFile(__dirname + '/lobby.html');
});
This is the output I get when I run this code:
Hi, Sho
Hi, undefined
I'm stuck at this one for the past whole day. Please help me.
When you submit the first time, jQuery fires and sends the POST through AJAX. The second submit is the HTML form firing. You want to stop the HTML form from submitting and use your custom handler instead.
The reason you're getting undefined is because you don't have name attributes on the inputs in your form.
You should return false; in your jQuery handler to prevent the form from firing, and do something with the response data as well.
Your code is posting via ajax, but it's not preventing the ordinary browser action of posting the form. You don't get any parameters from the normal form post because your <input> elements don't have "name" attributes.
You can return false; from the "submit" handler to prevent the normal form submission.
Try this instead: return false in your form onsubmit to prevent it from submitting twice
<form action="/loginPage" method="POST" onSubmit="return false" >
Could this be submitted to a servlet without a Action or Method? I.E.(could you use Jquery alone to send this?, or some other method?)
<form id="form2">
<input type="text" value="12" name="ID"/>
<input type="text" value="NameThatComesFirst" name="FirstName"/>
<input type="text" value="NameThatComesLast" name="LastName"/>
<input type=submit id="submit" value="submit"/>
</form>
No, it doesn't need to be there, by default it will submit to the currently loaded script, using a GET.
If you want to submit it with AJAX, you can define it when calling it instead of through the action/method attribute if you want using the jquery form plugin.
$('#form2').ajaxForm( {
url: 'comment.php',
type: 'PUT',
success: function() {
alert('Thanks for your comment!');
}
});
// The suggested way is to put action and method on the form and `$.ajaxForm`
// will find it.
$('#form2').ajaxForm({ success: function() {
alert('Thanks for your comment!');
}});
You can always send the form yourself by querying the DOM and sending an AJAX request
The answer is yes if you want something to actually happen. By default if no value for the action attribute is specified then it will use the existing page. As for using jQuery only to handle for submission the answer is no. You must use some type of server-side code such as PHP, ASP, JSP, etc to handle the form. Optionally, you can also use server-side JavaScript like node.js if you want.
You can, however submit the form via ajax using jQuery. See the API
Default action for form submission is METHOD="GET" and ACTION="SELF". From the docs.
If the ACTION is missing, the URL for the document itself is assumed.
I FORMULATED MY SELF VERY BADLY!
I will start over :) I appreciate your good answers, and if you can, try answering this: ( I will try to be more specific this time)
What I want is, that a <form>element onsubmit, onclick of a button or whatever takes the value of an <input type="text" value="Default value"> and inserts it in a couple of <span>elements, I like to call "placeholders". This sample might explain it a little better:
<head>
<script type="text/javascript">
$(document).ready(function()
{
$("input[type=button]").click(function //click the button
{ do_the_magic_thing() //make the value from id="txt_inp" appear in class="placeholder"
});
});
</script>
</head>
<body>
<form method="POST" action="" id="theForm"> //could also be get, I don't care
<input type="text" id="txt_inp" value="Default Value" onfocus="if (this.value == Default Value) this.value=''"> //this SHOULD make the Default Value dissapear on focus
<input type="button"> //could also be a submit
<span class="placeholder"></span> //$("#txt_inp").value; goes here
<span class="placeholder"></span> //$("#txt_inp").value; goes here
</body>
Now, is it really as simple as this?:
var do_the_magic_thing = function() {
$(".placeholder").html = $("#txt_inp").value;
};
I'm going to bed now - it's late in Denmark :) I will answer your comments tomorrow :)
OLD POST:
I am very new to this jQuery thing, but I do understand the basics and all. Let's simplify and say I have a form which looks like this:
<form method="POST" action="">
<input type="text" value="Default value">
<input type="submit" value="Click me">
<input type="hidden"> //hidden is for being able to submit by hitting enter
</form>
I've tried with $.post, but I just cannot get it right; it's not working for me.
Now, I would like to cancel the submit (can't that be done by just adding a return false; in the function returning the value, if a such is present?), but this is not crucial.
I think I typed in something like
$.post("test.php", function(data) {
alert("This is the data submitted (and cancelled):" + data);
}); //I have also tried without the "test.php", that's not it
Can you tell me, what I'm doing wrong please? :)
NOTE
It is not necessary, that the submit is cancelled, but I would like that
Nor is it necessary, that POST is the method used, but once again, this is what I prefer
Change the id of your form to "myform" or whatever and the name of your text input to "myinput", and try something like this...
$(document).ready(function() {
$('#myform').submit(submitMyForm);
})
function submitMyForm(e) {
var data = new Object();
data.whatever = $('#myinput').val();
var post = new Object();
//here I use a jquery json extension...you can use anything you like
post.data = $.toJSON(data);
$.post("test.php", post, function(returnval) {
alert(returnval);
}, "text");
//this is to stop the normal form submit action
return false;
}
Then in your test.php you can access it by calling $_POST['data'] (we specified this when we created the property of the "post" object called "data" like this: post.data = 'whatever'.
To answer the revised version of your question, yes, it really is that simple, although the correct syntax for your "do the magic thing" function is the following:
var do_the_magic_thing = function() {
$('.placeholder').html($('#txt_inp').val());
};
P.S. Don't worry too much about not expressing yourself, your English is much better than my Danish.
I think what you want to do is something like this:
<fieldset id="myData">
<legend>My Data</legend>
</fieldset>
<form id="myForm" method="POST" action="">
<input type="text" value="Default value">
<input type="submit" value="Click me">
<input type="hidden"> //hidden is for being able to submit by hitting enter
</form>
$(function() {
$('#myForm').submit(function() {
//do whatever you want here.
//this will take place after the form is submitted, but before your ajax request
$('input[type=text]').each(function() {
$('#myData').append('<div class="placeholder">' + $(this).val() + '</div>');
});
//serialize your form data
var toSubmit = $('input[type=text]').serialize();
//do ajax here
$.post('test.php', toSubmit, function(data) {
alert('Your AJAX POST request returned: ' + data);
}, 'text');
//this will prevent the form from submitting normally
return false;
});
});
Here's a demo of this in action: http://jsfiddle.net/SA3XY/
Also see my comment on your question.
Well for the form submit you need to add the following to the form to cancel the default submit event:
<form onsubmit="return functioncall();">
Then when you return false from the function it will cancel the default form action.
EDIT: If you would like to see all the data that is to be submitted you can serialize the form using jquery serialize() method or serializeArray() method.
If you're trying to accomplish validation, there's a much easier way, just use a validation plugin like this one:
http://docs.jquery.com/Plugins/Validation
Makes it much easier and takes the headache out of developing your own code. Jquery makes it easy to develop powerful javascript applications...but sometimes it's just easier to use stuff that's already been written and debugged (for the most part at least).