How to submit multiple forms with Jquery AJAX - javascript

Here is my HTML and jquery Ajax Code, i want when first row successfully proceed, One new row created by jquery. However first row properly work and proceed, but when second row created by ajax. it does not work, when i submit, it redirect on same page. Please check my code and let me know why my second row not work properly. how i can handle this situation ?
HTML CODE:
<div id="songsList">
<div class="songRow">
<div class="SongStatus"></div>
<form action="" method="POST" class="songsForm">
<div class="col-sm-3">
<input type="text" name="song_title" class="form-control" placeholder="Song Title">
</div>
<div class="col-sm-2">
<input type="text" name="singer_name" class="form-control" placeholder="Singer Name">
</div>
<div class="col-sm-2">
<input type="text" name="album_name" class="form-control" placeholder="Album Name">
</div>
<div class="col-sm-1">
<input type="text" name="album_year" class="form-control" placeholder="Year">
</div>
<div class="col-sm-3">
<input type="text" name="song_url" class="form-control" placeholder="Song Url http://">
</div>
<input type="hidden" name="songsSubmit" value="yes">
<div class="copySongUrl"><button type="submit" class="btn btn-primary"><i class="glyphicon glyphicon-upload"></i> Upload</button></div>
</form>
</div>
<hr />
</div>
Jquery/Ajax Code:
$(function() {
$('.songsForm').submit(function (event) {
event.preventDefault();
event.returnValue = false;
$.ajax({
type: 'POST',
url: 'post.php',
data: $(this).serialize(),
beforeSend: function() {
$(".copySongUrl :button").remove();
$(".copySongUrl").append('<img src="images/ajax-loader.gif" class="ajaxImage">');
},
success: function(res) {
if (res == 'success') {
$(".ajaxImage").remove();
$('input[name=song_title]').attr("disabled", true);
$('input[name=singer_name]').attr("disabled", true);
$('input[name=album_name]').attr("disabled", true);
$('input[name=album_year]').attr("disabled", true);
$('input[name=song_url]').attr("disabled", true);
$('.copySongUrl').append("<button type='button' id='plain-copy' class='btn btn-info'><i class='glyphicon glyphicon-paperclip'></i> Copy Url</button><script>document.getElementById('plain-copy').addEventListener('click', function() { clipboard.copy('<?php if(isset($_SESSION['uploadedUrl'])) echo $_SESSION['uploadedUrl']; ?>').then(function(){ document.getElementById('plain-copy-result').textContent = 'success'; }, function(err){ document.getElementById('plain-copy-result').textContent = err; });});<\/script>");
// Here Adding New Row, Similar Like Top HTML
$('#songsList').append('<div class="songRow"> <div class="SongStatus"></div> <form action="" method="POST" class="songsForm"><div class="col-sm-3"><input type="text" name="song_title" class="form-control" placeholder="Song Title"></div><div class="col-sm-2"><input type="text" name="singer_name" class="form-control" placeholder="Singer Name"></div><div class="col-sm-2"><input type="text" name="album_name" class="form-control" placeholder="Album Name"></div><div class="col-sm-1"><input type="text" name="album_year" class="form-control" placeholder="Year"></div><div class="col-sm-3"><input type="text" name="song_url" class="form-control" placeholder="Song Url http://"></div><input type="hidden" name="songsSubmit" value="yes"><div class="copySongUrl"><button type="submit" class="btn btn-primary"><i class="glyphicon glyphicon-upload"></i> Upload</button></div> </form></div><hr />');
} else {
$(".ajaxImage").remove();
$(".copySongUrl").append('<button type="submit" class="songUploadButton" class="btn btn-primary"><i class="glyphicon glyphicon-upload"></i> Upload</button>');
$(".SongStatus").append("<div class='alert alert-info'><li class='glyphicon glyphicon-warning-sign'></li> <b>"+ res +"</b></div>");
}
},
error: function () {
$('.SongStatus').html('Failed').slideDown();
}
});
});
});

You should change this:
$('.songsForm').submit(function (event) {
to this:
$('.songsList .songRow').submit('.songsForm',function (event) {
This is called delegated event.
Since your original code is pin pointing an element (could be a set of elements), it attaches the event to the element/s once only, and when further clones are created they dont have the event attached.
Delegated events are basically applied to the parent (element container) and then whenever an identified element is rendered within the parent, the element is immediately attached.
You can read here: Event Delegation

Related

Handling Button Enabling Via jQuery When 3 Form Areas Need to Have Values

After some reconfiguring I have some jQuery that handles enabling a "save" button when a field has a value:
$(document).ready(function () {
$('.save-button').attr('disabled', true);
$('#selection').keyup(function () {
if ($('#selection').val().length != 0) {
$('.save-button').attr('disabled', false);
} else {
$('.save-button').attr('disabled', true);
}
});
});
... but I realize now I should only enable this button when three separate form elements have values -- two of which are input fields, and one being a text-area.
The thing is, these could be filled in in any order, so how do I get my check to run so as to make sure it enables the "save" button when all three have values? In other words, what event can I use to check this?
The three IDs in question are: selection, schedule, and json-data
Here is my relevant HTML:
<div class="form-group">
<label>Job Name</label>
<input type="text" class="job-name form-control" id="selection">
</div>
<div class="form-group">
<div><label for="meeting-time">Schedule</label></div>
<input type="datetime-local" class="job-schedule form-control" min="getDateDefault()" max="getEndDate()"
id="schedule">
</div>
<div class="form-group">
<label>Repeat Every</label>
<input type="text" class="job-repeat-every form-control">
</div>
<div class="form-group">
<label>Job Data (json)</label>
<textarea class="job-data form-control" id="json-data">{}</textarea>
</div>
<div class="form-group">
<span class="btn btn-default btn-success save-button" data-action="save">Save</span>
<span class="btn btn-default btn-warning" data-action="cancel">Cancel</span>
</div>
You should use the focusout event on each element you need to check its value.
I have created a snippet, you can see the updated version of your code.
$(document).ready(function () {
$('.save-button').attr('disabled', true);
$('#selection, #schedule, #json-data').focusout(function () {
if ($('#selection').val() == "" ||
$('#json-data').val() == "" ||
$('#schedule').val() == ""
) {
$('.save-button').attr('disabled', true);
} else {
$('.save-button').attr('disabled', false);
}
});
});
.btn[disabled="disabled"] {
color: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label>Job Name</label>
<input type="text" class="job-name form-control" id="selection">
</div>
<div class="form-group">
<div><label for="meeting-time">Schedule</label></div>
<input type="datetime-local" class="job-schedule form-control" min="getDateDefault()" max="getEndDate()"
id="schedule">
</div>
<div class="form-group">
<label>Repeat Every</label>
<input type="text" class="job-repeat-every form-control">
</div>
<div class="form-group">
<label>Job Data (json)</label>
<textarea class="job-data form-control" id="json-data">{}</textarea>
</div>
<div class="form-group">
<span class="btn btn-default btn-success save-button" data-action="save">Save</span>
<span class="btn btn-default btn-warning" data-action="cancel">Cancel</span>
</div>

How to end edit mode connection from database without refreshing a page?

need your help on this.
I have 2 click event, one on table which is for add mode and one button which is on another table for update mode. These two mode has one input property, it changes value when I clicked for add and update. My problem is from update mode then to add click event, when I (button) submit the add value, the mode is still on update. It changes the existing value not adding another value to database.
How would I end the update mode to give way the add mode?
<form method="post" id="api_crud_form">
<h4 class="modal-title" id="h4">Add / Update Item</h4>
<hr>
<div class="row">
<div class="col-md-1">
<button type="submit" name="button_action" id="button_action-insert" class="btn btn-danger btn-sm form-control" value="Insert">Save</button>
<button type="submit" name="button_action" id="button_action-update" class="btn btn-danger btn-sm form-control" value="Update">Update</button>
<input type="hidden" name="product_id" id="product_id" />
<input type="hidden" name="order_id" id="order_id" />
<input type="text" name="tran_id" id="tran_id" value="<?php echo $tran_id; ?>" />
<input type="hidden" name="tran_amount" id="tran_amount" />
<input type="hidden" name="action" id="action" value="insert" />
</div>
<div class="col-md-2">
<input type="text" name="tran_quantity" id="tran_quantity" placeholder="Enter Quantity here" autocomplete="off" class="input form-control" />
</div>
<div class="col-md-7">
<input type="text" name="product_description" id="product_description" class="input form-control" readonly/>
</div>
<div class="col-md-2">
<input type="text" name="product_price" style="text-align: right;" id="product_price" class="input form-control" readonly/>
</div>
</div>
<hr>
</form>
Here is JS code
$('#api_crud_form').on('submit', function(event){
event.preventDefault();
if($('#tran_quantity').val() == '') {
alert("Enter Quantity");
} else if ($('#tran_quantity').val() == '0') {
alert("Enter a valid number!");
} else if ($('#product_description').val() == '') {
alert("You have not selected an item yet.");
} else if ($('#product_price').val() == '') {
alert("You have not selected an item yet.");
} else {
var form_data = $(this).serialize();
$.ajax({
url:"action.php",
method:"POST",
data:form_data,
success:function(data) {
fetch_data();
$('#api_crud_form')[0].reset();
$('#apicrudModal').modal('hide');
if(data == 'insert') {
alert("Item inserted successfully!");
}
if(data == 'update') {
alert("Item updated successfully");
}
}
});
}
});

jQuery and Ajax not working $.on

I want when I click on Clear button, all fields in the form to be cleared.
The ajax request is only replacing the form from the tag <form> to </form>.
When it is clicked on Clear button, the console output is working.
I have the following form:
<div class="col-lg-5 formWrapper">
<form data-th-fragment="layoutForm" id="layoutForm" class="form-horizontal" data-th-object="${layout}" data-th-action="#{/layouts/add}" method="POST" role="form">
<div class="row">
<input id="objectId" data-th-field="*{id}" type="hidden">
<input data-th-if="*{filePath} !=null" data-th-field="*{filePath}" type="text" hidden="hidden">
<label for="layoutName" >Layout name</label>
<input data-th-field="*{name}" id="layoutName" class="form-control" type="text">
</div>
<div class="row">
<div class="col-lg-4">
<label for="status">Status</label>
<select id="status" data-th-field="*{status}"class="form-control">
<option value="1">Active</option>
<option value="0">Blocked</option>
</select>
</div>
<div class="col-lg-6">
<label for="exhibitorName">Exhibitor</label>
<select data-th-field="*{exhibitor}" name="exhibitorName" id="exhibitorName" class="form-control">
<option data-th-each="exhibitor : ${exhibitorsList}" data-th-value="${exhibitor.id}" data-th-text="${exhibitor.exhibitorName}"></option>
</select>
</div>
</div>
<div class="row">
<div class=" col-lg-3">
<input id="clearForm" type="reset" value="Clear" class="form-control btn-lg btn btn-default">
</div>
<div class=" col-lg-3 col-lg-offset-4">
<input id="submitButton" type="submit" value="Add" class="form-control btn-lg btn btn-success">
</div>
</div>
</form>
</div>
The form looks something like this:
The jQuery is as follow:
$(document).ready(function() {
$('.formWrapper').on('click','#clearForm', function (event) {
$(this).closest('form').find("input[type=text]").val("");
console.log("ASD");
});
});
The snipped is how I replace the form:
$("body").on('click','#editLayout', function(event){
var ajax = $.ajax({
url : "/layouts/edit/" + $(this).data("id"),
dataType : "html",
success: function (data) {
$("#layoutForm").replaceWith(data);
$('#submitButton').val('Edit').addClass('btn-warning').removeClass('btn-success');
}
});
});
Try this,
$('#form_id').trigger("reset");
or
$('#form_id')[0].reset();
A reset button doesn't need any script at all (or name or id):
<input type="reset">
and you're done. But if you really must use a script, note that every form control has a form property that references the form it's in, so you could do:
<input type="button" onclick="this.form.reset();">
But a reset button is a far better choice.
Try to use $('#clearForm').reset(); or $('#clearForm')[0].reset();

AJAX form submission - Each click submits the form i++ number of times

I have an issue where my form submission in with AJAX works fine the first time, but if I click the submit button again, or press enter, the form submits twice. A third click causes the form to be submitted 3 times and so on. I've tried inserting return false and preventDefault() within the scripts.js file to no avail.
An implementation of my form can be found here and the resulting list of output can be found here
Additionally, I notice that the scripts.js never proceeds to the line with document.getElementById('test').innerHTML="this works3";
Any help would be greatly appreciated. Thank you!
index.html
<form id="form1" action="addpost.php" method="post">
<div class="form-group" >
<label for="title">Title:</label>
<input name="title" type="title" class="form-control " id="title" placeholder="Enter title (Compulsory)" required>
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name">
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<div class="form-group">
<label for="article">Article:</label>
<textarea name="article" class="form-control" rows="5" id="article"></textarea>
</div>
<div class="form-group">
<label for="img1">Image 1:</label>
<input type="file" class="form-control" id="img1" accept="image/*">
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<label id="test">hi</label>
<button class="btn btn-primary" onclick="poop()">Button</button>
<input type="submit" class="btn btn-primary" onclick="poop()" value = "submit"/>
</form>
scripts.js
function poop()
{
document.getElementById('test').innerHTML="this works";
var form = $('#form1');
document.getElementById('test').innerHTML="this works2";
form.submit(function (event)
{
$.ajax
({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data)
{
alert('ok');
}
});
});
document.getElementById('test').innerHTML="this works3";
}
Thanks to Liam and Vinod for pointing me in the right direction. I included the script to override the submit function in the index.html file. Solved the problem quite nicely.
index.html
<form id="form1" action="addpost.php" method="post">
<div class="form-group" >
<label for="title">Title:</label>
<input name="title" type="title" class="form-control " id="title" placeholder="Enter title (Compulsory)" required>
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name">
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<div class="form-group">
<label for="article">Article:</label>
<textarea name="article" class="form-control" rows="5" id="article"></textarea>
</div>
<div class="form-group">
<label for="img1">Image 1:</label>
<input type="file" class="form-control" id="img1" accept="image/*">
<span class="help-block">This is some help text that breaks onto a new line and may extend more than one line.</span>
</div>
<label id="test">hi</label>
<input type="submit" class="btn btn-primary" value = "submit"/>
</form>
// script included within body of html
<script type="text/javascript">
var form = $('#form1');
document.getElementById('test').innerHTML="this works2";
form.submit(function (event)
{
event.preventDefault();
$.ajax
({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data)
{
alert('ok');
}
});
});
</script>

Populate form with data from another form

I have a page with a small tour, within the tour points are inputs. Also on this page is another form, these forms have similar inputs including first, last name, etc...
If the user inputs their first name into form 1, how can I populate the first name field of form 2?
This is form 1:
<form role="form" id="inviteform3" class="form-inline" action="name.php" method="POST">
<div class="form-group">
<input type="text" class="form-control input-sm" name="name" placeholder="First Name"
id="hello" autocomplete="off" style="margin-top:10px">
</div>
<center>
<span id="start">Let's get started, <span id="result"></span></span>
<button class="btn btn-brand btn-sm next-screen animated bounceInUp"
id="go" style="margin-top:5px; display:none" href="#services" data-animation-delay=".5s">
Let's Go!</button></center>
<button class="btn btn-block btn-brand btn-xs invitebtn3" id="casi" type="submit"
style="margin-top:5px"><i class="fa fa-thumbs-o-up"></i> Submit</button>
</form>
This is form 2:
<form role="form" id="inviteform" class="form-inline"
action="http://omnihustle.net/demo/invitations/invite_request" type="POST"><div
class="form-group">
<input type="text" class="form-control input-sm" id="InputFirstName" placeholder="First
Name">
</div>
<div class="form-group">
<input type="text" class="form-control input-sm" id="InputLastName" placeholder="Last
Name">
</div>
<div class="form-group">
<input type="email" class="form-control input-sm" id="InputEmail" placeholder="Email">
</div>
<button class="btn btn-brand btn-sm invitebtn" type="submit" data-toggle="modal" data-
target=".bs-example-modal-sm"><i class="fa fa-check fa-fw"></i> Invite Me</button></form>
Here is my php file which the form is sent to:
<html>
<body>
<?php session_start(); ?>
<?php
if (isset($_POST['name']) && !empty($_POST['name'])) {
$_SESSION['name'] = $_POST['name'];
}
?>
<?php echo $_POST["name"]; ?>
</body>
</html>
Jquery has not worked since I am unable to enter html into the "value" field of the form, so what is the alternative?
Here is what ive tried;
<script>
$(document).on("ready", function(){
//Form action
$("#inviteform3").on("submit", function(event){
// Stop submit event
event.preventDefault();
$.ajax({
type:'POST',
url: 'name.php',
data:$('#inviteform3').serialize(),
success: function(response)
{
$('#inviteform3').find('#result').html(response);
$('.coupontooltip5').find('#result2').html(response);
$('#announcement').find('#result3').html(response);
$('#announcement2').find('#result4').html(response);
$('#progressbutton').find('#result5').html(response);
$('#inviteform').find('#result6').html(response);
}});
});
});
</script>
I have tried inputting "span id="result6" into the "value" tag of the input and the form does not allow the function, just shows the html as the default value of the input..
You can add a 'keyup' handler which copy the content to the second field. Add the following lines into the 'ready' handler.
$('#hello').on('keyup', function() {
$('#InputFirstName').val($(this).val());
});
If you add a 'change' handler instead of this 'keyup' handler, the handler is called only after the the field loses the focus.
By the way, name.php does not work. session_start() must be called before any output is made. Hence:
<?php session_start(); ?>
<html>
<body>

Categories