Ajax call on form submission - MVC 5 - javascript

The Goal:
Use an ajax call to either bring back information from database if the user supplied correct information, or if the user is a new user then it will return redirectToAction and send the user to another form. I want to do all of this using either parsley or bootstrap validator (I want to use these tools so that I can put the validator in the input and once I click on submit it will validate the form, but will not submit it. I also want it to have the same look, so the fields highlight similar to http://1000hz.github.io/bootstrap-validator/ The ajax call will handle the decision)
The problem:
Here is a similar form:
<form action="" id="application">
First Name: <input type="text" name="first" required/>
Last Name: <input type="text" name="last" required/>
<button type="submit">Submit</button>
</form>
When one clicks on this form, if the user has not supplied the first and last name it will not submit the form.
What I want it to do is if the user has supplied this information it will not go to the action but will instead execute the ajax call and never submit the form from the button press similar to $(button).click(function (){//do stuff});(the ajax call will handle the submission, my guess here is that we can substitute this ajax call for any JavaScript function).
Finally:
I have read about the e.preventdefault but it did not seem to work for me. How can I get the form to validate the inputs but never actually submit (unless the ajax allows it to). Can you give me an example of how I would do this? Or is this something that cannot be done? Should I do something similar to this Validate Form preventing form submission

Add an onsubmit event on the form, for example,
<form onsubmit = "DoSubmit(this);return false;">
DoSubmit: function()
{
//validate the form and decide submit or not
if($(form).valid())
{//if form valid, this is done by form validation itself
$(form)[0].submit();
}
else
{
//do nothing or do whatever
}
}

Related

Preventing form submission in jquery when for is submitted through javascript .submit

I am trying to prevent a form submission from happening using the event.preventDefault() in JS. While this works fine on a standard form submission, it seems to not be stopping the submission when the form is submitted externally by JS.
Here is an example HTML form that I am using:
<form id="demo12" method="post">
<input type="hidden" id="testID" name="testID" value="42">
</form>
Click this sentence to submit the form
And here is the included javascript/jquery file that is trying to catch this form being submitted:
$("[id^='demo']").submit(function (event) {
event.preventDefault();
// Then there is some ajax code here
}
Due to the nature of the form being added in through Jinja, there are multiple similar forms. I want to catch any form that starts with 'demo' in the id field and run some AJAX to fetch some new information from the server.
This has worked for me in the past, but the only difference is instead of there being a submit button, the form is being submitted separately through an html hyperlink tag. Is JQuery not able to catch the event of the form submission when it is submitted like this?
Currently when I do this, it just posts the form to the same html page and it the jquery function never occurred. I do see in debugging, through in the browser, that the jquery is listening properly and recognizes the form as something it is listening for to be submitted.
$('[data-submit]').on('click', e => {
$(e.target.dataset.submit).trigger('submit');
});
$('#demo12').on('submit', e => {
console.log('you submitted me!');
e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="demo12" method="post">
<input type="hidden" id="testID" name="testID" value="42">
</form>
Click this sentence to submit the form
Rather than calling the native submit event, trigger the submit event on the form. This way, you can process it and conditionally cancel it.

javascript call before submit using thymeleaf does not work as expected

I am new to javascript so it might be a simple question for many.
I have used form sumbit in thymeleaf and am trying to add a JS validation before the form is submitted to the spring mvc controller. I can perform these two actions separately (individual tasks). However I could not really make them work one after the other (js function and form submit). Submit action is triggered by a button inside the form.
<form th:action="#{/user/trigger}" th:object="${triggers}" method="post">
<input type="hidden" name="tradeDate" th:value="${trigger.id.tradeDate}">
<button type="submit" id="ignore" name="action" value="ignoreOrder" class="btn btn-primary btn-sm">Ignore</button>
</form>
The js function is like below:
$(".ignore").click(function() {
//do some processing;
return false;
});
So can someone can help me to rewrite this code which will first call the JS function and submit the form to the java spring mvc controller? Thanks in advance.
The issue with your approach is that after your java-script is validating the code, your html 'submit' button is submitting the form as they're executing one after another. You haven't done anything to prevent the form submission after the validation is getting failed.
To overcome this issue, what you can do is to submit the form through your JavaScript code manually only when your validation is successful.
So your code will look something like this -
1.) Changes in Html code, instead of creating the button type as 'submit', make it as a normal button and run your javascript validation function on its click -
<form th:action="#{/user/trigger}" th:object="${triggers}" id="myForm" method="post">
<input type="hidden" name="tradeDate" th:value="${trigger.id.tradeDate}">
<button type="button" id="ignore" name="action" onclick="myValidationFunction()" value="ignoreOrder" class="btn btn-primary btn-sm">Ignore</button>
</form>
2.) Changes in Javascript code, now after clicking on the above button your javascript validation function will execute and after the validation is successful submit the form manually using the form id, something like this -
function myValidationFunction(){
if( some_condition ){
//validation failed
return;
}
//validation success , when above mentioned if condition is false.
$("#myForm").submit(); // Submit the form
}
For more information about using submit in jquery, refer the official documentation -
https://api.jquery.com/submit/
for jquery, it return a list, so:
$('#search_form')[0].submit();

How to stop Redirecting a page when a form is submitted?

I'm using a form and when the form is submitted I used action attribute and called a server url where the form data gets saved
Here's how it looks :
<form name="example" action="webresources/data/update" method="post">
</form>
The above form when submitted updates the form data in to the server but at the same time it also takes me to the new page webresources/data/update which has nothing but server response
I don't want this response to be shown on the web page. The url should be called when the form is submitted and it should be on the same page without redirecting to a new page.
Is there any way to do this, I'm allowed to send the data only via form parameters.
Thank you in advance :)
Remove the action attribute in the form and put the button outside the form.
When onclick, make an ajax call.
<form>
stuff
</form>
<input type="button" onclick="ajax()">
<script>
function ajax(){}
</script>
<form name="example" action="webresources/data/update" method="post" onclick="return false">
</form>
Returning false will stop the page from reloading or refreshing.
I suggest that before you ask a question you do a quick google search because this was the first result that came up for me prevent form submit from redirecting/refreshing using javascript.

How can I submit a form automatically (onevent) with javascript?

I'd like to be able to submit a form automatically on an event ( a generic form, for user tracking).
For example, create a POST to
http://www.example.com/index.php?option=track&variable=variable
application/x-www-form-urlencoded with stuff like
username=usernamestring
otherdata=otherdata_string
otherdata2=otherdata string 2
The actual string will be preformatted, though, because all it is is like a 'ping'.
It needs to be submitted onevent, with external js ( http://example.com/scripts/js.js )
What the hay should I do? This is getting annoying.
Update: I guess I didn't really make myself clear; I have a premade form that isn't supposed to display on the page; it needs to submit on an event. The form fields do not exist on the page; all I do is link to the script on the page and it executes onLoad.
POST uri: http://www.example.com/index.php?option=track&variable=variable
The arguments above (option=track and variable=variable) are not the form details (postdata).
The content type is application/x-www-form-urlencoded , and has the following keys/values.
username=usernamestring
otherdata=otherdata_string
otherdata2=otherdata string 2 (when encoded, the spaces get turned to %20's.)
I need a script that submits this when run.
You have to get the form object and call the submit(); function provided by HTMLFormObject.
document.getElementById('myForm').submit();
1) with the following, (while page is loaded), the form will be immediately autosubmited
<form action="post.php" name="FNAME" method="post">
<input type="text" name="example22" value="YOURVALUE" />
<input type="submit" />
</form>
<SCRIPT TYPE="text/JavaScript">document.forms["FNAME"].submit();</SCRIPT>
another formSubmit alternative - submits any script:
document.forms[0].submit();
2) or use button click after 2second:
<SCRIPT TYPE="text/JavaScript">setInterval(function () {document.getElementById("myButtonId").click();}, 2000);</SCRIPT>

Submit HTML5 Form using Javascript and validate its inputs

I'm writing form and adding html5 validation attributes to its input like "required", "autofocus". I use Javascript to submit the form using document.myForm.submit() but it doesn't validate the form against the html5 validation attributes as they aren't there.
Any Suggestions?
It appears that triggering a click on the submit button does have the correct effect: http://jsfiddle.net/e6Hf7/.
document.myForm.submitButton.click();
and in case you don't have a submit button, add an invisible one like:
<input type="submit" style="display:none" name="submitButton">
The pimvdb's answer is based on a workaround to include a hidden submit button.
HTML5 provides javascript functions to achieve the same thing without a submit button. As Tigraine pointed out, Mozilla documents two validity checking methods for 'form' elements:
checkValidity() return true/false and doesn't show anything to the end user
reportValidity() return true/false and ALSO shows the validation messages to the end user (like the normal submit button click does)
<!DOCTYPE html>
<html>
<body>
<form name="testform" action="action_page.php">
E-mail: <input type="email" name="email" required><br/>
Report validity<br/>
Check validity<br/>
Submit
</form>
</body>
</html>
Why not simply call the validation manually before you do document.myForm.submit()
What validation framework do you use and what AJAX library?
In case you use jQuery here is the code to prevent the submit:
$('#myForm').submit(function(evt) {
if (! $('#myForm').validate()) {
evt.preventDefault();
}
});
And trigger the submit through:
$('#myForm').submit();
This would call the validation whenever submit is triggered.. And if the validation fails it prevents the submit from executing.
But I'd look at your validationframework as it usually should do this already
In case you don't use any JavaScript framework you may want to have a look at: element.checkValidity(); and how to invoke the HTML5 validation from JavaScript before even calling submit.

Categories

Resources