Undefined value set by previous Jquery event - javascript

I am trying to post a form with dynamic set value on click event by getting undefined respose Here is my code.
$( ".paymentselect" ).click(function() {
var bookingid=$(this).data('id');
$('#paymentstats').css('display','block');
$('#paymentform').attr('action', document.location.origin +"/accounts/" + bookingid);
});
$('#paymentform').submit(function(event){
event.preventDefault();
var data=$('#paymentform').serialize();
$.ajax({
url: $(this).attr('action'),
method: 'POST',
data: data,
beforeSend: function() {
// setting a timeout
$('#wait').html('<i class="material-icons">cached</i>');
},
success: function(data){
if(data.status){
$('#paymentstats').css('display','none');
alert("UPDATED");
//location.reload();
}else
{
alert("something went wrong");
}
}
});
});
On POST bookingid is Undefind. Little Help will be appriciated
EDITED :
<table>
<tr>
<td>
<button class="paymentselect" data-id="NH7003687415654"> Update</button>
</td>
</tr>
<table>
<div id="paymentstats" class="custom-modal">
<!-- Modal content-->
<div class="modal-content">
<div class="card" style="margin-bottom:0px">
<form id="paymentform" method="POST"> //form that will be posted
<div class="body">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<div class="form-line">
<input type="text" class="form-control" id="utr" name="utr" placeholder="" required>
<input type="hidden" class="form-control" id="bookingpaymentid" name="id" placeholder="">
</div>
<label class="small-label" for="utr">Payment UTR(if any)</label>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<div class="form-line">
<input type="text" class="form-control" id="ref" name="ref" placeholder="" required>
</div>
<label class="small-label" for="ref">Payment Ref</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="spin" id="wait"></div>
<button type="submit" class="btn btn-raised bg-pink waves-effect">Submit</button>
<button type="button" class="btn btn-raised bg-red waves-effect" id="close-btn">Close</button>
</div>
</form>
</div>
</div>
As requested Above is my html Code As requested.
I ALREADY TRIED SETTING bookingpaymentid Val on click event But It Also shows Undefined when Form is POST On the Server.
I just figured out that value become undefined when i post form . Any Suggestion

Because you declare bookingid inside $( ".paymentselect" ).click(function() {.
You can try this:
var bookingid = null;
$( ".paymentselect" ).click(function() {
bookingid=$(this).data('id');
$('#paymentstats').css('display','block');
$('#paymentform').attr('action', document.location.origin +"/accounts/" + bookingid);
});

In plunker bookingid is not undefined. Go to plunker address and check browser console to see variable's values.
You might be having trouble to load order of your scripts file. As you can see in plunker make sure to load your js codes end of the body tag.

Related

Why is a html-form submission inside a modal not being picked up by submit function and ajax?

Question: why is a form submission not being picked up by $("#form_name").submit(function (event) {...}); and therefore ajax call not being executed?
Possible Cause: While it's not clear to me why this isn't working, I suspect it's related to an improper combination of MDBootstrap modal classes, jQuery Ajax, and html form.
Details:
To be able to edit rows in my data table, I use the following modal with an embedded form tag, see below. If the submit button is clicked, the datatable gets updated in the browser. But but my ajax call, which I need to send the edited fields back to my controller, is not being served (i.e. the console.log() function is not being executed).
Modal:
<div class="modal fade modalEditClass" id="modalEdit" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="/zkl/edit_pers_post" method="post" id="editForm">
<div class="modal-body mx-3 modal-inputs">
<div class="md-form mb-5">
<label>Nachname</label>
<input type="text" name="nachname" class="form-control" />
</div>
<div class="md-form mb-5">
<label>Vorname</label>
<input type="text" name="vorname" class="form-control" />
</div>
<div class="md-form mb-5">
<label>Kürzel</label>
<input type="text" name="kuerzel" class="form-control" />
</div>
<div class="md-form mb-5">
<label>Telefon</label>
<input type="text" name="tel" class="form-control" />
</div>
<div class="md-form mb-5">
<label>E-Mail</label>
<input type="email" name="email" class="form-control" />
</div>
<div class="md-form mb-5">
<label>ID</label>
<input type="number" name="id" readonly class="form-control" />
</div>
<div class="modal-footer d-flex justify-content-center editInsideWrapper">
<button id="button-save-edit" type="submit" name="submit"
class="btn btn-outline-secondary btn-block editInside" data-dismiss="modal">Edit
form
<i class="fas fa-paper-plane-o ml-1"></i>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
Submit function and AJAX call:
<script>
$("#editForm").submit(function (event) {
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serializeArray(); //Encode form elements for submission
/* test log */
console.log(form_data)
$.ajax({
url: post_url,
contentType: "application/json",
type: request_method,
data: JSON.stringify(form_data)
})
});
</script>
my datatable is constructed as follows:
html
<div class=table-responsive-md>
<table id="ex1" class="table table-striped table-hover table-sm" cellspacing="0" width="100%">
</table>
</div>
jquery
<script>
// construct DataTable using data variable and column titles
$('#ex1').DataTable({
data: data,
columns: [
...
],
// add some column definitions
"columnDefs": [
...
]
});
// construct mdbEditor
$('#ex1').mdbEditor({
modalEditor: true,
});
$('.dataTables_length').addClass('bs-select');
thank you for reading and if possible answering this question.

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();

Prevent reload after form submit with Thymeleaf fragments, Ajax and Spring boot

I've searched for a long time here but nothing helped.
I have a Spring Boot application together with Thymeleaf Bootstrap and jQuery
Application Layout
In the application Layout The right menu is in The mqttCenter.html:
<div class="panel panel-default panel-back">
<div class="panel-body button-wrapper">
<a type="button" onlick="showIotManagerFrag();"
href="javascript:void(0);" class="btn btn-primary btn-block">IoT - Manager</a>
</div>
</div>
<div id=deviceManager></div>
where the button opens a thymeleaf Fragment with ajax request and puts it into the upper shown deviceManager div element. This is the layout next to the navigationbar. Because i realized with an ajax call theres no pagerefresh or direction to another page.
And here is the fragments.html:
<div id="device-management" th:fragment="deviceManager" class="panel panel-default panel-back">
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<h1 class="text-center">IoT - Manager:</h1>
</div>
</div>
<div class="row">
<div class="col-md-5">
<h3 class="text-center bottom-buffer">Fügen Sie ein neues IoT - Device hinzu:</h3>
<form id="addDevice" name="addDevice" th:action="#{/users/addDevice}" th:object="${device}" method="post">
<div class="form-group">
<label class="control-label" for="name">Device - Name:</label>
<input type="text" class="form-control" id="firstName" th:field="*{name}" placeholder="Name eingeben">
</div>
<div class="form-group">
<label class="control-label" for="name">Device - Typ:</label>
<select class="form-control" id="sel1" th:field="*{type}">
<option th:each="deviceType : ${deviceTypes}" th:value="${deviceType.type_id}" th:text="${deviceType.type}"></option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="topic">MQTT - Topic:</label>
<input type="text" class="form-control" id="topic" th:field="*{topic}" placeholder="Topic eingeben">
</div>
<div class="form-group">
<label class="control-label"for="description">Beschreibung:</label>
<textarea class="form-control" rows="5" id="description" th:field="*{description}" placeholder="Eine kurze Beschreibung"></textarea>
</div>
<div class="form-group">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-default button-width"><span class="glyphicon glyphicon-send"></span> Hinzufügen</button>
</div>
</div>
</form>
</div>
<div class="col-md-2"></div>
<div class="col-md-5">
<h3 class="text-center bottom-buffer">Löschen Sie ein vorhandenes IoT - Device:</h3>
<form id="removeDevice" name="removeDevice" th:action="#{/users/removeDevice}" th:object="${device}" method="post">
<div class="form-group">
<label class="control-label" for="name">IoT - Device auswählen:</label>
<select class="form-control" id="sel1" th:field="*{name}">
<option th:each="deviceName : ${deviceList}" th:value="${deviceName.device_id}" th:text="${deviceName.name}"></option>
</select>
</div>
<div class="form-group">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-default button-width"><span class="glyphicon glyphicon-send"></span>Löschen</button>
</div>
</div>
</form>
<div id="device-submit"></div>
</div>
</div>
</div>
</div>
This fragment is called from mqttCenter.html and is in a different file fragments.html. The modelobjects are passed by the Ajax Controller Call.
So I want no refresh or redirect to other pages after the submit of the forms inside. I've looked on many ajax requests here like put forms into json and work with #ResponseBody and suitable Mediatypes in my Controller but nothing worked.
Teh Resopnsebody always redirected me to the Requestmapping url instead back to the ajax success Method.
Here a Code snippet from Controller und Ajax for form Submit.
#RequestMapping(value = "/users/addDevice", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE)
#ResponseBody
public String deviceSaving(#Valid #ModelAttribute("addDevice") AddDevice device, BindingResult bindingResult)
{
do Stuff.
return "success- String"
and here Ajax Call in fragments.html:
$(document).ready(function()
{
$('#addDevice').submit(function(event)
{
var json = $('#addDevice').serialize();
$.ajax({
url: "addDevice",
data: JSON.stringify(json),
type: "POST",
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
var respContent = typeof(data);
console.log(respContent);
respContent += "<span>"
respContent += smartphone + "</span>"
$("#device-submit").html(respContent);
}
});
event.preventDefault();
});
});
What i'm doing wrong? Thanks for help...
Make sure you don't see any error in the JavaScript console.
I think you should move the preventDefault line into very first place of the submit function.
$(document).ready(function() {
$('#addDevice').submit(function(event) {
event.preventDefault();
var json = $('#addDevice').serialize();
$.ajax({
url: "addDevice",
data: JSON.stringify(json),
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data) {
var respContent = typeof(data);
console.log(respContent);
respContent += "<span>"
respContent += smartphone + "</span>"
$("#device-submit").html(respContent);
}
});
});
});
Hope that helps!

Submit button is not working with HTML and JavaScript

Whenever I attempt to click the submit button, nothing happens.
I have attempted to change the button, however I doubt this is the issue.
JavaScript Code:
$('#contactForm').submit(function () {
$.ajax({
type: "POST",
url: "php/contact.php",
data: $('#contactForm').serialize(),
success: function (msg) {
if (msg == 'SEND') {
$('.success').fadeIn();
$('.error').fadeOut();
$('#contactForm')[0].reset();
} else {
$('.success').fadeOut();
$('.error').fadeIn().find('h3').text(msg);
}
}
});
return false;
});
HTML Code:
<div>
<h2 class="small-heading">CONTACT US</h2>
<div class="contact-form col-sm-11 clearfix">
<form action="contact-complete.php" id="contactForm" method="post" name="contactForm">
<fieldset>
<div class="col-sm-12">
<input id="name" name="name" placeholder="Your Name*" type="text" value="">
</div>
<div class="col-sm-12">
<input id="email" name="email" placeholder="Your Email*" type="text" value="">
</div>
<div class="col-xs-12">
<textarea cols="5" id="message" name="message" placeholder="Your Message....*"></textarea>
</div>
<div class="col-xs-12">
<button type="submit" form="contactForm" class="submit active">SEND</button>
</div>
<div class="error col-xs-12">
<h3></h3>
</div>
<!-- Error Message [ END ] -->
<div class="success col-xs-12" id="update">
<h3>Success! Your message was sent.</h3>
</div>
<!-- Submit Button [ END ] -->
</fieldset>
</form>
<!-- Contact Form [ END ] -->
</div>
</div>
If you could please help me out this would be much appreciated.
Thank you for all of your help.
This seems to be an issue within the AJAX call. I removed "return false;" from the code and it seemed to work. However, it was sending the information twice. So I just removed the AJAX code all together and it worked just fine redirecting to the PHP mail() script.
Thanks for all of your help.
Your button doesnt have an action and you don´t listen for it either
<button type="submit" form="contactForm" class="submit active" OnClick="submit()">SEND</button>
Or add an ID and listen for that in the JS

submit function submits twice after first submisson jquery, PHP

function slideupSubmit (name) {
$(name).submit(function ( event ) {
event.preventDefault();
var target = $(this).attr("action");
var response = $(this).attr("response");
var formName = $(this).attr("id");
$.post(target,
$(this).serialize() + '&' + $.param({ 'formName':formName, response : response}),
function (data) {
$(response).html(data);
$(name).hide();
$(name)[0].reset();
}
);
});
};
function resetForm (name){
$(name).show();
};
Im really new at this and only been coding for a few months so if my code is really bad I apologize, and if the solution is very easy, please forgive me.
I wrote this code so I could reuse it to submit diffrent forms on my page and have a response sent to a div above it. Im able to post everything I want but after the first time it posts, if I post again, it will post twice. Then three times. I know I did something wrong but I cant find the error.
I include this on my response to allow the form to be brought back after hiding.
<a onClick="resetForm('.$_POST['formName'].')" href="#" response=""> New Form?</a>
Here is the form.
<!-- Form 1 --->
<div class="row ">
<div class="col-xs-12">
<div class="well well-dark ">
<h4>Update Contacts</h4>
<span class="contactUpdate-response text-success"></span>
<form id="contactUpdate" class="form form-inline hidden contact-form" response=".contactUpdate-response" method="post" action="ajax/contactUpdate.php">
<div class="form-group">
<input hidden name="contact_entry" value="1"/>
</div>
<div class="form-group">
<label>Contact Title:</label>
<input class="form-control" name="contact_title" required />
</div>
<div class="form-group">
<label>Link to Employee</label>
<select name="empId" class="form-control select-emp-name"></select>
</div>
<div class="form-group">
<label>Category:</label>
<select name="category"class="form-control select-contact-categories ">
</div>
<div class="form-group">
<label>Link to Location</label>
<select name="locat_id" class="form-control select-location"></select>
</div>
<div class="form-group">
<label>Number:</label>
<select name="extId" class="form-control select-dig-ext"></select>
</div>
<div class="form-group">
<input hidden name="updateBy" value="24"/>
</div>
<div class="form-group">
<input onclick="slideupSubmit(contactUpdate)" type="submit" class="form-control btn btn-primary" value="Update List" />
</div>
</form>
</div>
</div>
</div>
<!--- -->
<input type="submit" class="form-control btn btn-primary" value="Update List" />
take your event listener out of function
and remove onclick=...
$(name).submit(function ( event ) {
event.preventDefault();
var target = $(this).attr("action");
var response = $(this).attr("response");
var formName = $(this).attr("id");
$.post( target, $(this).serialize()
+'&'+$.param({ 'formName': formName,
response : response}),
function(data){$(response).html(data);
$(name).hide();
$(name)[0].reset();
});

Categories