POST form with jQuery and handle the result - javascript

Is it possible to POST a form through jQuery and also handle the result? (without using json, ajax etc).
Something like this:
<form id="loginform">
//some input fields and a submit button.
</form>
and then from jQuery:
$("#loginform").submit(function (e) {
$.post("somePHPscript")
.done(function (response) {
//Handle response
});
});
.. or would that equal removing the form, and just binding an event to the submit-button, and take the inputs manually?

I'm not exactly sure why you would want a form that handles the submission result by overriding the default form action and not using ajax etc.
You will want to read this: http://api.jquery.com/submit/ which will outline how to capture the form submission event, you can prevent the move to another page by using the event.preventDefault() as outlined in the above link.

The code you have will handle the response. You just have to do something with it. If you're returning a string of text, you can do something like this:
.done(function(response){
alert(response);
});
If you are returning some HTML, maybe something like this:
.done(function(response){
$(response).insertAfter('div');
});
EDIT
Of course, if you submit the form, then there is no point in trying to retrieve a response from the server. But right now your code is submitting the form and trying to do an AJAX request. Might as well stop the form from submitting and doing the AJAX request so you can do something with the response.

<form id="the-form" role="form">
<input type="button" id="button-form">
</form>
$("#button-form").on('click', function (e) {
e.preventDefault();
$.post($("#the-form").attr('action'), function(response) {console.log(response)});
});

Related

click and mousedown events don't work on Ajax form

Simple Ajax popup with a form collecting 3 fields of data, and a submit button. I can't programatically trigger the submit button though.
jQuery('#FormSubmit').click()
doesn't work. Neither does
jQuery('#FormSubmit').mousedown()
nor
document.getElementById("FormSubmit").click();
A real mouse click on the button works, but programmatically triggering it doesn't. It either posts the form in a non-AJAX way (page reload with post data appended to the url) or does nothing.
Anyone know the reasons why?
Is there something specific to Ajax to prevent this?
Edit:
Just tested triggering the submit event on the form instead, and that also posts the form in a non-AJAX way.
You need to use submit, or if you want you can write something like this:
`$('#formSubmit').on('click', function (event) {
event.preventDefault();
var input1 = $('#someInput1').val().trim();
var input2 = $('#someInput2').val().trim();
$.ajax({
url: 'someUrl',
type: 'POST',
success: function (result) {
//do something with the result
}
})
})`
try to use trigger, like this
jQuery('#FormSubmit').trigger("click");

How to trigger submitting form automatically and use preventDefault

I have two ways of using form on a page.
First one is standard way when user types something in input field and clicks the submit button.
Second one is that the form is automatically filled and submitted depending on if a query string is passed to a page. (www.website.com/contact?fillform=true)
Everything works fine except I need yet to trigger the submit button for when query string is passed but currently it just refreshes the page.
I have done part in PHP, I have checked variables and they are ok.
Here is Codepen, e.preventDefault() is commented out since it doesn't work on window load
$(window).load(function() {
// Function for submitting form
function submitForm(e) {
console.log('I am in');
e.preventDefault();
jQuery.ajax({
... // Submit form
})
}
// Normal way of submitting form, works ok
$contactForm.on('submit', function(e) {
submitForm(e);
});
// This should trigger form automatically
if(fillFormAutomatically) {
// Everything so far works ok
// I just need to trigger form without page refresh but none of these works
$submitBtn.trigger('click');
$submitBtn.triggerHandler('click');
$contactForm.submit(e);
$contactForm.submit(function(e) {
console.log(e); // nothing in console shows here
submitForm(e);
});
submitForm(); // This triggers function but I can't pass event?
}
});
I think there is a couple of problems.
.load() was depreciated in jQuery 1.8, so don't use that. See: https://api.jquery.com/load-event/
Secondly, when you call submitForm() on window.ready(), there is no event. So you're trying to call .preventDefault() on undefined. Just move it to the .submit() function.
Does that answer your question?
$(window).ready(function() {
var $form = $("#form");
var $submitBtn = $("#submitBtn");
// Send form on window load
submitForm();
// Normal way
$form.submit(function(e) {
e.preventDefault();
submitForm(e);
});
// Send form
function submitForm() {
$('#vardump').append('Sending form...');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="form">
<input type="text" value="Somedata">
<button id="submitBtn">Submit</button>
</form>
<div id="vardump"></div>

How to submit (or not submit) a form based on the result of an Ajax request?

I have a form on my site where users submit stuff and get results
<form accept-charset="UTF-8" action="/submit-stuff" data-remote="true" method="post">
<!-- various form fields -->
<input type="submit" value="Run Code" id="submit-button">
</form>
Before submitting their info to the backend, I try to get the results in Javascript. If I can get the results, I return false in Javascript to prevent the form submission.
$('#submit-button').click(function() {
if(canGetResults()){
//deal with submission and then
return false;
}
//the button will work as usual if canGetResults is false or there's an error
});
This works fine, but now I want to try to get the results through another ajax request and only submit to my regular backend if that fails. I call the following code after the button is clicked:
$.post("http://example.com/submit-stuff", json, function(data) {
//do stuff with data
});
However, it's asynchronous (so I can't return results from it) so the code reaches return false even when the other ajax attempt fails. How should I fix this so it only submits to my own backend when the ajax attempt failed?
I could change the $.post to $.ajax and make it synchronous, but that's not usually recommended. Alternatively, I can submit the form within the $.post callback, but how should I submit the whole form from there? And would it still submit if there's an error or http://example.com/submit-stuff doesn't work?
Your submit handler should always prevent the form from submitting.
Then, if the Ajax code comes back with an OK, you should call the form's submit() method. This will bypass the submit handler and submit the form.
NB: Call submit on the DOM object, not the jQuery object. jQuery has a habit of triggering event handlers from its wrappers.
You can bind the ajax request all in your submit function, and call a .post() event if necessary:
$("form").submit(function(e){
e.preventDefault(); // <-prevents normal submit behaviour
//only post if your ajax request goes your way
$.ajax(url,function(data){
//argument to post or not
if(data=="success"){ postForm(); }
});
});
function postForm(){
$.post(
"/submit-stuff"
,$( "form" ).serialize()
,function(data){
//your code after the post
});
}
If you do not want to create a separate function for your postForm, then you can just put it inside the wrapper where it's currently being called.

handling successful form submission with jquery

In my application I'm using a plugin that generates the following markup:
<form id="addCommentForm"
action="/foo/add"
method="post"
onsubmit="
jQuery.ajax({type:'POST', data:jQuery(this).serialize(),
url:'/foo/add',
success:function(data,textStatus) {
jQuery('#comments').html(data);
},
});
return false">
<!-- form elements here -->
</form>
When the form is submitted successfully I want to do something else after the success handler defined by the plugin, say alert('hello');.
The reason I'm struggling with this is because I can't just add my code to the end of the success handler above, because this code is not under my control.
I looked for a form event that executes after onsubmit that I could attach my code to, but didn't find anything.
If you can't really change it, you could use .ajaxSuccess() to handle all the external ajax calls and filter the one you need:
$('form').ajaxSuccess(function(evt, request, settings) {
if (settings.url == 'xxx')
alert('test');
});
Not pretty but it might work for you.

Hiding And Submitting A Form Using jquery

How to Hide a form and submit that form using jquery?
Is this possible?
Yes, it is possible:
On your HTML page:
<form id="my-form">
</form>
Submit
Your script:
$(document).ready(function() {
$("a#submit").click(function() {
$("#my-form").hide();
$("#my-form").submit();
});
});
If your form contains a Submit button and you want the form to be hidden when the Submit button is pressed, instead you can listen to the submit event and handle it like this:
$("#my-form").submit(function() {
$(this).hide();
return true;
});
What are you trying to do? Some scam?
You can place the form in a hidden div and using $(document).ready event, you can autosubmit the form.
Do you mean a field within a form that already has data inserted, eg. hard-coded in by you, the developer?
If this is the case, just set an id to the input field, with the value hard-coded in. Then set it's display to 'none'. Use your Jquery to interpret the data as normal.
You could also just make a variable in your jquery script, and avoid all this.
Since you've added the jquery-ajax tag, I guess you want to submit the form through AJAX. In that case you are probably looking for something like this:
$("#your-form-id").submit(function(){
$.ajax({
type: "POST",
url: "some.php",
data: $(this).serialize(),
success: function(){
$("#your-form-id").hide();
}
});
return false;
});

Categories

Resources