HTML required attribute not working with AJAX submission - javascript

HTML required attribute not working with AJAX submission
I have created a model Form and set its input field to require attribute but its not working with ajax
<div class="modal fade hide" id="ajax-book-model" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="ajaxBookModel">Add New Machine</h5>
<!-- <button type="reset" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> -->
<button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" onClick="window.location.reload();">
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST">
<input type="hidden" name="id" id="id">
<input type="hidden" name="user_id" id="user_id" value="{{ Auth::user()->id }}">
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Name</label>
<input type="text" id="machine_name" name="machine_name" class="form-control form-control-sm" placeholder="Enter Machine Name" required>
<span class="text-danger">{{ $errors->first('machine_name') }}</span>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>IOT Device ID</label>
<input type="text" id="iot_device_id" name="iot_device_id" class="form-control form-control-sm" placeholder="Enter IOT Device ID" required>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Local device ID</label>
<input type="text" id="local_device_id" name="local_device_id" class="form-control form-control-sm" placeholder="Enter Local Device ID" required>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-gradient-danger mb-2" data-dismiss="modal" onClick="window.location.reload();">Close</button>
<button type="submit" id="btn-save" value="addNewBook" class="btn btn-sm btn-gradient-danger mb-2">Save</button>
</div>
</form>
</div>
</div>
</div>
and this is ajax code
i just want to run simpal html required field validation with ajax
$('body').on('click','#btn-save', function (event){
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save"). attr("disabled", true);
// ajax
$.ajax({
type:"POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id:id,
user_id:user_id,
machine_name:machine_name,
iot_device_id:iot_device_id,
local_device_id:local_device_id,
},
dataType: 'json',
success: function(res){
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save"). attr("disabled", false);
}
});
});
i just want to run required field validation with ajax i could not find any solution .

Try changing your btn click event to form submit event.
$('body').on('submit', '#addEditBookForm', function (event) {
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save").attr("disabled", true);
// ajax
$.ajax({
type: "POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id: id,
user_id: user_id,
machine_name: machine_name,
iot_device_id: iot_device_id,
local_device_id: local_device_id,
},
dataType: 'json',
success: function (res) {
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save").attr("disabled", false);
}
});
});

The following should help: change to a form confirmation event instead of a Click button event. And do not forget to write this code so that the page does not reload:
event.preventDefault();

Related

validations not working for checking empty fields

validations not working for checking empty fields
while clicking create button no message is alerting
and console is clear not showing any error
my Jquery code:
var assign_report_form = $('#assign_report_form');
$('#create').on('click', function(){
var source_id = $('#src_id option:selected').text();
var username = $('#username').val();
var email = $('#email').val();
var query_name = $('#query_name').val();
var channel = $('#channel').val();
var condition = $('#condition').val();
if((source_id =="")||(username == "")||(email == "")||(query_name == "")||(channel == "")||(condition == "")){
$('#error_message').show().delay(5000).fadeOut();
}
else{
// var data = {'source_id': source_id,
// 'username':username,
// 'email':email,
// 'query_name':query_name,
// 'channel': 'email',
// 'condition': condition
// }
// console.log('data',data)
$.ajax({
url:'/add_report/',
type:'POST',
data:{'source_id': source_id,
'username':username,
'email':email,
'query_name':query_name,
'channel': 'email',
'condition': condition
},
success: function(res){
if(res =='success')
// $('#Add_modal').modal('toggle');
// $('#success_message').show().delay(5000).fadeOut();
// $("input[type=text],input[type=email],select").val("");
// }
// else{
// $('#error_message').show().delay(5000).fadeOut();
// }
console.log('form saved..')
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown)
}
})
event.preventDefault();
}
});
});
validations not working for checking empty fields
while clicking create button no message is alerting
and console is clear not showing any error
Here is the html code:
<button type="button" data-toggle="modal" data-target="#Add_modal" class="btn btn-secondary" id="add_row" style="margin-right: 10px;">Add</button>
<!-- Add New Report Model -->
<div class="modal fade" id="Add_modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h3 class="modal-title" id="lineModalLabel">Assign New Report</h3>
</div>
<div class="modal-body">
<!-- content goes here -->
<div class="alert alert-warning" id="#error_message" style='display:none;'>
<strong>Error!</strong>Please fill Empty fields
</div>
<form id="assign_report_form">
{% csrf_token %}
<!-- <input type="hidden" id="src_id" value="{{ source_id }}"/> -->
<div class="form-group">
<label for="username">Source ID</label>
<select id="src_id" class="form-control" name="source_id">
{% for source in sources %}
<option value="{{source_id}}" selected>{{ source.id }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="queryname">Query_Name</label>
<input type="text" class="form-control" name="query_name" id="query_name" placeholder="Query_Name">
</div>
<div class="form-group">
<label for="channel">Channel</label>
<input type="text" class="form-control" name="channel" id="channel" placeholder="Channel">
</div>
<div class="form-group">
<label for="condition">Condition</label>
<input type="text" class="form-control" name="condition" id="condition" placeholder="Condition">
</div>
<input type="button" id="create" class="btn btn-primary" value='Create'/>
</form>
</div>
</div>
</div>
In your html code you need to omit the "#" in id="#error_message" and write id="error_message" instead.
You should always use $('<dropdown selector>').val();, like in your case.
var source_id = $('#src_id option').val();
This will work always for select elements.

TypeError: 'append' called on an object that does not implement interface FormData

$(document).on('submit','#form_pem', function(event){
event.preventDefault();
var kodebayar = $('#kodebayar').val();
var nama = $('#nama').val;
var harga = $('#harga').val;
var postData = new FormData(this);
if(kodebayar != '' && nama != '' && harga != ''){
$.ajax({
url:"<?=site_url('bpem/user_action')?>",
method:"POST",
data:postData,
contentType:false,
proccessData:false,
success: function(data)
{
alert(data);
$('#form_pem')[0].reset();
$('#modalpem').modal('hide');
dataTable.ajax.reload();
}
});
}
else{
alert("Silahkan isikan semua data!");
}
});
this is my JS
<div class="modal fade text-xs-left" id="modalpem" tabindex="-1" role="dialog" aria-labelledby="myModalLabel35" aria-hidden="true">
<div class="modal-dialog modal-sm">
<form method= "post" id="form_pem">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title text-xs-center">Tambah Biaya Pembayaran</h3>
</div>
<div class="modal-body">
<fieldset class="form-group floating-label-form-group">
<label for="Kode">Kode <span class="required">*</span></label>
<input type="text" class="form-control" name="kodebayar" id="kodebayar" placeholder="Kode Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="nama">Nama <span class="required">*</span></label>
<input type="text" class="form-control" name="nama" id="nama" placeholder="Nama Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="projectinput7">Biaya Perbulan <span class="required">*</span></label>
<div class="input-group">
<span class="input-group-addon">Rp.</span>
<input type="number" class="form-control" placeholder="Biaya Perbulan" aria-label="Amount (to the nearest dollar)" name="harga" id="harga">
<span class="input-group-addon">.00</span>
</div>
</fieldset>
</div>
<div class="modal-footer">
<input type="reset" class="btn btn-grey" value="Bersihkan">
<input type="submit" class="btn btn-warning" name="action" id="action" value="Tambah">
</div>
</div>
</form>
</div>
</div>
and this is the view.
But i got an error like
TypeError: 'append' called on an object that does not implement interface FormData.
Did i forget something to add? What should i do? thankyou for your help
Need a correction for typo :)
proccessData:false
should be
processData: false
To avoid FormData errors make sure that the ajax options must be like
$.ajax({
url : "url",
type: "POST",
data : postData,
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR){
//
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});

how to post modal information to a api using jquery,javascript,ajax

I have a modal, e.g the modal is in modal.html, the method i wrote in a javascript file modal.js. when I am trying to submit data through modal, it is not working properly. the code is below. please help me someone.
/modal.html
<div class="col-md-12 text-right">
<button type="button" data-toggle="modal" data-target="#myModal">Update User Information</button>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Enter User Information</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" class="form-control" id="user_name" placeholder="User name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email_id" placeholder="Enter email">
</div>
<div class="form-group">
<input type="text" class="form-control" id="address" placeholder="Enter Address">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" id="myFormSubmit">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
/modal.js
$(function() {
$('#myFormSubmit').click(function () {
$.post("/api/adduserInfo/v1",
{
user_name : $("#user_name").val(),
email : $("#email_id").val(),
address : $("#address").val()
});
});
});
You can use something like this (you will have to get the parametres via post on the server side):
<!-- FORM -->
<form id="idform">
<!-- FORM INPUTS -->
<input class="btn btn-large btn-primary" value="Submit" type="submit">
</form>
<script>
// Variable to hold request
var request;
$("#idform").submit(function(event) {
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
$.ajax({
url: '/api/adduserInfo/v1',
type: 'post',
data: serializedData,
beforeSend: function () {
$("#divtoaddresult").html("Processing, please wait...");
},
success: function (response) {
$("#divtoaddresult").html(response);
}
});
});
</script>

Modal Hide Not Working

The modal form submits, returns formSuccess, sends the email, returns the signup alert, but the modal does not hide. Any suggestions?
The modal html:
<div class="modal fade" id="signupModal" tabindex="-1" role="dialog" aria-labelledby="signupModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Provide a few details and we'll be in touch...</h4>
</div>
<div class="modal-body">
<form id="contactForm" role="form">
<input type="hidden" id="theme" name="theme" value="flatly"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Your name" required>
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Your email address" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Have a question or comment?" required></textarea>
</div>
</div>
<div class="modal-footer">
<button id="form-submit" type="submit" class="btn btn-success">Sign Up</button>
</div>
</form> <!-- add tag v_07 -->
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
The signup alerts html:
<div class="container form-message">
<div class="row">
<div id="signupSuccess" class="alert alert-success" style="display:none">
<p id="signupSuccessText">Thanks for signing up for preview access, we'll be in touch! In the meantime join us on Twitter, Facebook, and LinkedIn.</p>
</div>
<div id="signupError" class="alert alert-info" style="display:none">
<p id="signupErrorText">Well this is embarrassing. It looks like we're having trouble. While we fix this, we can be reached at info#timbercheck.net</p>
</div>
</div>
</div>
And here is the code from js file.
$("#contactForm").submit(function(event){
event.preventDefault();
submitForm();
});
function submitForm(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
}
}
});
};
function formSuccess(){
$("#signupSuccess").show();
$("#signupModal").modal('hide'); // add v_07
};
function formError(){
$("#signupError").show();
$("#signupModal").modal('hide'); // add v_07
};
You should add data-dismiss="modal" instead on your button because you are anyway going to show another modal.
EDIT : Change type from submit to button
<button id="form-submit" type="button" class="btn btn-success" data-dismiss="modal">Sign Up</button>
And try this,
$("#form-submit").click(function(event){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
}
}
});
};
function formSuccess(){
$("#signupSuccess").show();
$("#signupModal").modal('hide'); // add v_07
};
function formError(){
$("#signupError").show();
$("#signupModal").modal('hide'); // add v_07
};
Instead of..
$('#myModal').modal('hide')
This worked...
$('#myModal').hide();
$('.modal-backdrop').hide();
Source: https://stackoverflow.com/a/29560331/7069248
Could be related to version of Bootstrap
This solution works for me:
setTimeout(function(){
$('#close-modal').click();
$('#close-modal').click();
},200);

How to send var from ajax to submit of modal in bootstrap?

I have a php file that contains a bootstrap/ajax calendar with click action that open a modal bootstrap. This action send a var to the modal and when you click into submit modal button this save the var into mysql database with a php file called. My problem is that in the modal is showed the var correctly, but this isn't sended to php file to save into database.
This is my code:
$(document).ready(function() {
...
eventClick: function(event, jsEvent, view) {
$('#createEventModalEdit #start').text(event.start);
$('#createEventModalEdit #end').text(event.end);
$('#createEventModalEdit #patientName').text(event.title);
$('#createEventModalEdit #id').text(event.id);
$('#createEventModalEdit').modal('show');
...
$('#submitButtonEdit').on('click', function(e){
// We don't want this to act as a link so cancel the link action
e.preventDefault();
doSubmitEdit();
});
function doSubmitEdit(){
$("#createEventModalEdit").modal('hide');
console.log($('#apptStartTime').val());
console.log($('#apptEndTime').val());
console.log($('#apptAllDay').val());
console.log($('#id').val());
var title = $('#patientName2').val();
var start = $('#apptStartTime').val();
var end = $('#apptEndTime').val();
var allDay = $('#apptAllDay').val();
var idEvent = $('#id').val();
alert(end);
$.ajax({
url: 'process.php',
data: 'type=changetitle&title='+title+'&eventid='+idEvent, **Here var idEvent haven't value. If I change this for exist id like: '25' is changed**
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
alert("form submitted");
$("#calendar").fullCalendar('renderEvent',
{
title: $('#patientName2').val(),
start: new Date($('#apptStartTime').val()),
end: new Date($('#apptEndTime').val()),
allDay: ($('#apptAllDay').val() == "true"),
},
true);
}
And html modal bootstrap code:
<div id="createEventModalEdit" class="modal hide" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 id="myModalLabel1">Crear tarea</h3>
</div>
<div class="modal-body">
<form id="createAppointmentForm" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputPatient">Tarea:</label>
<div class="controls">
<input type="text" name="patientName2" id="patientName2" tyle="margin: 0 auto;" data-provide="typeahead" data-items="4" data-source="["Value 1","Value 2","Value 3"]">
<input type="hidden" id="apptStartTime"/>
<input type="hidden" id="apptEndTime"/>
<input type="hidden" id="apptAllDay" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="start">Inicio:</label>
<div class="controls controls-row" id="start" style="margin-top:5px;">
</div>
<label class="control-label" for="end">Fin:</label>
<div class="controls controls-row" id="end" style="margin-top:5px;">
</div>
<label class="control-label" for="start">Inicio:</label>
<div class="controls controls-row" id="id" style="margin-top:5px;">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button type="submit" class="btn btn-primary" id="submitButtonEdit">Save</button>
</div>
What I doing bad?? How can assign correctly the value into idEvent?
Thanks!

Categories