Submit AJAX form with multiple events - javascript

I have a form, and when the submit button is clicked, it sends an AJAX request. This works on the button click by:
$(#form).submit(function(event) {
event.preventDefault();
$.ajax({
// ...
})
});
The form data is passed to the URL in the ajax command using data.
Is there a way this form can be submitted and the same AJAX function can run on a dropdown change javascript/jQuery event? The dropdown menu is in the same form.
I have it so that when the AJAX returns successfully, it adds the HTML to populate a div with a table so this needs to be written once.

Short answer: "Yes". You can call the "submit" method of the form from anywhere you like. For example:
$("#someDropdown").change(function() { $("#form").submit(); });
Demo:
$(function() {
$("#someDropdown").change(function() {
$("#form").submit();
});
$("#form").submit(function(event) {
event.preventDefault();
console.log($(this).serialize());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="someDropdown">
<option>Option 1</option>
<option>Option 2</option>
</select>
<hr>
<form id="form">
<input type="text" name="text1" />
<button type="submit">Submit</button>
</form>
Documentation: https://api.jquery.com/submit/

Related

Event triggered on any modification on my form

I made a form with an imput text and a select.
To submit the form i want the user to click a verify button in order to check if all fields are correctly filed.
If it is then the button submit who was initialy disabled is now enable.
Here is the problem, i'd like that if the user modify anything in the form again then the button turn back to disable so that he must verify again to submit.
To do so i'd like to find a jQuery event that triggers on any event on my form to turn back the submit button to disable again.
Any idea of how could i do ?
You can use the form (delegateTarget) then from that select the input types (https://stackoverflow.com/a/3165569/125981) that you wish to be in scope to attach event hanlders, and disable those desired by there type. Since it IS possible to have multiple I have included and example with two submit buttons that are and a reset button that is NOT disabled. To reverse that, you would need to have some way to clear them out so I added an example of a custom event.
Added a reset event handler since it may come into play here.
$('#myform').on('change keyup', 'input[type="text"], select', function(event) {
$(event.delegateTarget).find('input[type="submit"]').each(function() {
console.log("disable:", this);
this.disabled = true;
});
})
.on('all-clear', function(event) {
$(event.delegateTarget).find('input[type="submit"]').each(function() {
this.disabled = false;
});
})
.on('click', '#allclear', function(event) {
$(event.delegateTarget).trigger('all-clear');
})
.on('reset', function(event){
// do whatever is desired on the reset of the form
});
.find('input[type="text"]').trigger('change'); //IF you want disabled initially
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form id="myform">
<input type="text" value="text stuff" />
<select>
<option value="option1" selected="selected">First Option</option>
<option value="option2">Another Option</option>
</select>
<input type="submit" value="Submit" />
<input type="submit" value="Possible Submit" />
<input type="reset" value="Reset" />
<button id="allclear" type="button">All clear</button>
</form>
You need to trigger the event with the on Change function of jQuery. You have to assign it to every input field / Select or whatever, or give them all the same class.
Here is a Doc
Example:
<form>
<input class="target" type="text" value="Field 1">
<select class="target">
<option value="option1" selected="selected">Option 1</option>
<option value="option2">Option 2</option>
</select>
</form>
<div id="other">
Trigger the handler
</div>
Script:
$( ".target" ).change(function() {
alert( "Handler for .change() called." );
});
If you provide any sample Code, we'd be able to help you even more.

Using Jquery Validator and Sweetalert for Form Submission Confirmation Box

I am trying to do the following.
I have 3 buttons, "Continue", "Delete", "New". All of these are type "submit" buttons.
When the form is posted, the value of these buttons is used to determine what happens on the backend.
I want a Sweetalert popup to confirm if the user wants to delete, then when the OK button is hit, the form should progress and submit to the backend.
The issue I currently have is that there is no way to get the value of the submit button to the server side when I incorporate Sweetalert to show when I hit the submit button.
Scenario A) For example, if I remove the "e.preventDefault" from the callback, the alert popups for a brief second but the form submits, not giving the user to confirm or cancel the deletion. This is not correct behaviour, but the "submit" button value does indeed get posted to the server. So to prevent the quick popup issue, I add "e.preventDefault" to stop the normal behaviour of "submit" button.
Scenario B) However, when I have the code as below (i.e. "e.preventDefault" added to the code), the form does not submit after validation. Instead I have to run "$('#myForm').submit()". But when I do this, the value of the "submit" button does not get posted to the server.
If someone could kindly guide me on how I can use jQuery Validate and Sweetalert, it would be much appreciated.
An example of the set up looks like this:
HTML:
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
<form id="myForm" action="/postHere" method="post">
<!-- Options-->
<div class="row-select">
<label for="options">My Options</label>
<select name="options" id="options">
<option disabled="true" selected="selected">Select an Option</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
</div>
<!-- continue details form -->
<div>
<input type="submit" id="continue" name="submitButton" value="Continue this Option">
</div>
<!-- delete details -->
<div>
<input class="delete" type="submit" id="delete" name="submitButton" value="Delete this Option">
</div>
<!-- new -->
<div class="row-spaced">
<input type="submit" id="submitButton" name="submitButton" value="Neither" formnovalidate>
</div>
</form>
Javascript:
function myFunction() {
var continueOption = document.getElementById('continue');
var deleteOption = document.getElementById('delete');
var neither = document.getElementById('new');
$('#myForm').validate({
ignore:'',
rules: {
options: "required"
},
});
// AIM IS TO SHOW A CONFIRMATION BOX IF DELETE IS CLICKED
if(deleteOption) {
deleteOption.addEventListener("click", function(e) {
e.preventDefault();
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
console.log("here");
$('#myForm').submit();
}
});
});
}
}
myFunction();
Backend Illustration:
router.post("/postHERE", (req, res) => {
if (req.body.submitButton == "Continue this Option") {
// Do something CONTINUE
}
else if (req.body.submitButton == "Delete this Option") {
// Do something DELETE
}
else {
// Do something NEW
}
}
JSFiddle:
JSFiddle Example
EDIT:
For the backend I am using Expressjs. I have added this in and fixed a type in the form method to be post.

AJAX Form Post PreventDefault Not Working

I have a simple HTML document with a form I would like to post to the server without leaving the page. I've Googled around the internet all day trying to figure out how to get this to work and I've come up with the following code:
<body>
<script>
$(document).ready(function() {
$('#newResource').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'scripts/script.php?new-resource=1',
data: $('#newResource').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
</script>
<form id="newResource" class="form-basic" enctype="multipart/form-data" method="post" action="scripts/script.php?new-resource=1">
<label><b>Resource Name:</b></label>
<input class="input-text" type="text" placeholder="Enter the resource name..." name="name" id="name" autocomplete="off" required="">
<br>
<label><b>Resource URL:</b></label>
<input class="input-text" type="text" placeholder="Enter the resource URL..." name="url" id="url" autocomplete="off" required="">
<br>
<label><b>Resource Department:</b></label>
<p>Select the department this resource should belong to.</p>
<select class="input-select" name="department" id="department">
<option value="5">Human Resources</option>
<option value="1">Information Technology</option>
<option value="3">Marketing</option>
<option value="0">No Department</option>
<option value="6">Purchasing</option>
<option value="4">Sales</option>
</select>
<br>
<label><b>Resource Icon:</b></label>
<p>Select the icon image to be displayed with this resource.</p>
<select class="input-select" name="icon" id="icon">
<option value="bell.png">Alarm Bell</option>
<option value="chat-bubbles.png">Chat Bubbles</option>
<option value="chronometer.png">Chronometer</option>
<option value="database.png">Database Icon</option>
<option value="envelope.png">Envelope</option>
<option value="folder.png">File Folder</option>
<option value="analytics.png">Monitor with Line Graph</option>
<option value="pie-chart.png">Monitor with Pie Chart</option>
<option value="networking.png">Networking Heirarchy</option>
<option value="orientation.png">Orientation Arrow</option>
<option value="server.png">Server Rack</option>
<option value="settings.png">Settings Gears</option>
<option value="speedometer.png">Speedomoeter</option>
<option value="worldwide.png">World Wide Web Globe</option>
</select>
<br>
<div style="float: right;">
<button type="button" onclick="loadPrefs('resources');" class="form-button cancel">Cancel</button>
<button class="form-button submit" type="submit">Submit</button>
</div>
</form>
</body>
The code is all within the body tag.
The problem is that when I click the submit button I am redirected to the PHP action script. Does the script I have need to be in the head tag instead?
If I remove the action from the form then the script redirects to the same page but no data is submitted.
Here is the PHP script if necessary:
if(isset($_GET['new-resource'])){
// escape the SQL input for security
$name = mysqli_real_escape_string($conn, $_POST['name']);
$url = mysqli_real_escape_string($conn, $_POST['url']);
$department = mysqli_real_escape_string($conn, $_POST['department']);
$icon = mysqli_real_escape_string($conn, $_POST['icon']);
// Run the SQL query to add the new resource item
$sql = "INSERT INTO Resources (ID, ResourceName, ResourceURL, IconImg, Department) VALUES (NULL, '$name', '$url', '$icon', '$department');";
$conn->query($sql);
// Close the SQL connection
$conn->close();
}
I can't seem to figure out why this is not working. Any thoughts and feedback are appreciated.
The important info in your case was "The HTML form elements are added with AJAX". At $(document).ready(), the #newResource form element did not yet exist, so the event was never bound. In your working example you used event delegation: $(document).on('click', '.submit', function(e) {...}, this is the correct way setup event listeners for non-existing elements.
Your event handler is bound to the submit event of the form. By the time the form has been submitted, it's too late to stop the default synchronous HTML form submission.
Bind your handler to the to click event on the submit button, use event.preventDefault() and submit the form via Ajax:
$(document).ready(function() {
$('.submit').click(function (e) {
e.preventDefault();
var form = $('#newResource');
var action = form.attr('action');
var data = form.serialize();
$.ajax({
type: 'POST',
url: action,
data: data,
success: function () {
alert('form was submitted');
}
});
});
});
Please note, the way this is written, it will fire for any click of an element with a class of submit. Since you may have more than one form on your web page and more than one button with a class of submit, it's not good to have the form variable use a hard-coded ID selector.
If the HTML of all your website forms are always coded this same way, with the submit button inside of a div which is nested in the form, you could replace:
var form = $('#newResource');
with:
var form = $(this).parent().closest('form');
Now you can wrap that code in a function called "bindForms()" or whatever, and you have a generic recipe for handling all forms, provided that the HTML structure is always the same (or at least, to the extent that the submit button always has a class of submit and is always wrapped in a parent container which is a child of the form.
Ok, I've managed to get this following code to work:
<script type="text/javascript">
$(document).on('click', '.submit', function(e) {
debugger;
e.preventDefault();
var form = $(this).parent().closest('form');
var action = form.attr('action');
var data = form.serialize();
$.ajax({
type: 'POST',
url: action,
data: data,
success: function () {
loadPrefs('resources');
}
});
});
</script>
The HTML form elements are added with AJAX but so was the script element. I moved the script element to the top of the page so that it is static and no longer loaded with the form.

Monitoring form fails with Ajax

I have a large form that I want to monitor for changes. I found example code for that in this post. When I run the code as posted, it works fine. But my form is using Ajax and it doesn't work for some reason. Here's my jsfiddle. I added a second monitor near the bottom but it isn't working either.
When the monitoring code is in the doc ready function, even the first "hello" update doesn't work. But this may be something to do with jsfiddle since I can get past that point locally. But even then, the origForm data is not seen more than once because, I think, the doc ready function is only called the one time when Ajax loads it.
Is there a way to monitor all of the fields when using Ajax?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="saved_form"></div>
<div id="changed"></div>
<div id="showform"></div>
<script>
$(document).ready(function() {
ShowForm();
$("#saved_form").text("hello");
var $form = $("form"),
origForm = $form.serialize();
$("#saved_form").text(origForm);
$("form :input").on("change input", function() {
$("#changed").text("A change was made");
});
});
function ShowForm () {
$.ajax({
url: 'ajax3.php',
success: function(data) {
$("#showform").html(`
<form>
<div>
<textarea name="description" cols="30" rows="3"></textarea>
</div>
<div>Username: <input type="text" name="username" /></div>
<div>
Type:
<select name="type">
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div>
Status: <input type="checkbox" name="status" value="1" /> 1
<input type="checkbox" name="status" value="2" /> 2
</div>
</form>
`);
}
});
};
var $form2 = $("form"),
origForm2 = $form2.serialize();
$("#saved_form").text(origForm2);
$("form :input").on("change input", function() {
$("#changed").text("A change was made");
});
</script>
You are dynamically adding the form to your page. The selector will not pick up the change event. Also the event and selector in the on method are defined properly. more information about the on method can be found here http://api.jquery.com/on/
Try this:
$(document).on("change", "input, textarea", function() {
$("#changed").text("A change was made");
});
You can use .promise() after using .html() to render your form. This callback is launched right after form has been populated. Then you can use $("#showform form :input") to monitor events just on this eactly form. It costs less in performance than doing with $(document).on(...)
In your code:
function ShowForm () {
$.ajax({
url: 'test',
success: function(data) {
$("#showform").html(`
// <--- All your previous html -->
`).promise().done(function(){
// <--- Execute your monitor after rendering new form -->
$("#showform form :input").on("change input", function() { $("#changed").text("A change was made");
});
});
}
});
};
Look at the updated jsfiddle
To know more about .promise() here-jquery-promises

How to stop opening ACTION page after submitting FORM using JavaScript

When I am submitting the FORM using SUBMIT button, it takes me to the ACTION page. But I want to stay in same page after submission and show a message below the form that "Submitted Successfully", and also reset the form data. My code is here...
<h1>CONTACT US</h1>
<div class="form">
<form action="https://docs.google.com/forms/d/e/1FAIpQLSe0dybzANfQIB58cSkso1mvWqKx2CeDtCl7T_x063U031r6DA/formResponse" method="post" id="mG61Hd">
Name
<input type="text" id="name" name="entry.1826425548">
Email
<input type="text" id="email" name="entry.2007423902">
Contact Number
<input type="text" id="phone" name="entry.1184586857">
Issue Type
<select id="issue" name="entry.1960470932">
<option>Feedback</option>
<option>Complain</option>
<option>Enquiry</option>
</select>
Message
<textarea name="entry.608344518"></textarea>
<input type="submit" value="Submit" onclick="submit();">
</form>
<p id="form_status"></p>
</div>
You need to use Ajax for sending Data and no refresh the page.
//Jquery for not submit a form.
$("form").submit( function(e) {
e.preventDefault();
return false;
});
//Ajax Example
$.ajax({
data: {yourDataKey: 'yourDataValue', moreKey: 'moreLabel'},
type: "POST", //OR GET
url: yourUrl.php, //The same form's action URL
beforeSend: function(){
//Callback beforeSend Data
},
success: function(data){
//Callback on success returning Data
}
});
Instead of adding onclick="submit()" to your button try capturing the submit event. In your submit function you also need to return false and prevent default to prevent the form from not submitting and taking you to the action page.
Using jQuery it would look something like this:
$("#id_form").on("submit", function(e){
//send data through ajax
e.preventDefault();
return false;
});

Categories

Resources