Form validation before Submit - php

I have the following form that needs to feed into the database but I would like it to be validated before it can be saved into the database :
<form name="add_walkin_patient_form" class="add_walkin_patient_form" id="add_walkin_patient_form" autocomplete="off" >
<div class="form-line">
<div class="control-group">
<label class="control-label">
Patient Name
</label>
<div class="controls">
<input type="text" name="patientname" id="patientname" required="" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">
Patient Phone Number
</label>
<div class="controls">
<input type="text" name="patient_phone" id="patient_phone" required="" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">
Department
</label>
<div class="controls">
<select name="department" required="" class="department" id="department">
<option value="">Please select : </option>
<option value="Pharmacy">Pharmacy</option>
<option value="Laboratory">Laboratory</option>
<option value="Nurse">Nurse</option>
</select>
</div>
</div>
</div>
<button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
Add Walk In Patient
</button>
</form>
And the submit is done by a jquery script using the following script :
<script type="text/javascript">
$(document).ready(function () {
//delegated submit handlers for the forms inside the table
$('#add_walkin_patient_button').on('click', function (e) {
e.preventDefault();
//read the form data ans submit it to someurl
$.post('<?php echo base_url() ?>index.php/reception/add_walkin', $('#add_walkin_patient_form').serialize(), function () {
//success do something
// $.notify("New Patient Added Succesfully", "success",{ position:"left" });
$(".add_walkin_patient_form").notify(
"New Walkin Patient Added Successfully",
"success",
{position: "center"}
);
setInterval(function () {
var url = "<?php echo base_url() ?>index.php/reception/";
$(location).attr('href', url);
}, 3000);
}).fail(function () {
//error do something
$(".add_walkin_patient_form").notify(
"There was an error please try again later or contact the system support desk for assistance",
"error",
{position: "center"}
);
})
})
});
</script>
How can I put form validation to check if input is empty before submitting it into the script?

I am using javascript to do the validations.
Following is the form code:
<form action="upload.php" method="post" onSubmit="return validateForm()">
<input type="text" id="username">
<input type="text" password="password">
<input type="submit" value='Login' name='login'>
</form>
To perform validation write a javascript function:
<script>
function checkform(){
var uname= document.getElementById("username").value.trim().toUpperCase();
if(uname=== '' || uname=== null) {
alert("Username is blank");
document.getElementById("username").backgroundColor = "#ff6666";
return false;
}else document.getElementById("username").backgroundColor = "white";
var pass= document.getElementById("password").value.trim().toUpperCase();
if(pass=== '' || pass=== null) {
alert("Password is blank");
document.getElementById("password").backgroundColor = "#ff6666";
return false;
}else document.getElementById("password").backgroundColor = "white";
return true;
}
</script>

You are using,
<button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
Add Walk In Patient
</button>
Here, submit button is used for submitting a form and will never trigger click event. Because, submit will be triggered first thus causing the click event skip.
$('#add_walkin_patient_button').on('click', function (e) {
This would have worked if you have used normal button instead of submit button
<input type="button">Submit</button>
Now to the problem. There are two solution for it ,
If you use click event, then you should manually trigger submit on correct validation case,
<input type="button" id="add_walkin_patient_button">Submit</button>
//JS :
$("#add_walkin_patient_button").click(function() {
if(valid){
$("#form-id").submit();
}
Another option is to use submit event;which is triggered just after you click submit button. Here you need to either allow form submit or halt it based on your validation criteria,
$("#form-id").submit(function(){
if(invalid){
//Suppress form submit
return false;
}else{
return true;
}
});
P.S
And i would recommend you to use jQuery Validate as suggested by #sherin-mathew

make a javascript validation method (say, validateForm(), with bool return type). add [onsubmit="return validateForm()"] attribute to your form and you are done.

You need to prevent default action.
$('#add_walkin_patient_form').on('submit', function(e) {
e.preventDefault();
//Validate form and submit
});

<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<style>
#first{
display: none;
}
</style>
<div class="container"><br>
<div class="col-lg-6 m-auto d-block">
<form action="" method="" onsubmit="return validation()" class="bg-light">
<div class="form-group">
<label for="">Title</label>
<span class="text-danger">*</span>
<!-- <input class="form-control" type="text" > -->
<select name="title" id="title" class="form-control" >
<option value=""class="form-control" >Select</option>
<option value="Mr" class="form-control">Mr</option>
<option value="Mrs" class="form-control">Mrs</option>
</select>
<span id="tit" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<label for="firstName">FirstName</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="First name" id="firstName" >
<span id="first" class="text-danger font-weight-bold"> </span>
</div>
<div class="col">
<label for="lastName">LastName</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Last name" id="lastName">
<span id="last" class="text-danger font-weight-bold"> </span>
</div>
</div>
</div>
<div class="form-group">
<label for="email">Your Email</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Email" id="email">
<span id="fillemail" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="contact">Your Contact</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Contact Number" id="contact">
<span id="con" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="password">Your Password</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Password" id="password">
<span id="pass" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="conPassword">Confirm Password</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Password" id="conPassword">
<span id="conPass" class="text-danger font-weight-bold"> </span>
</div>
<div class="checkbox">
<label><input type="checkbox"> I accept Terms and Conditions</label>
</div>
<div class="checkbox">
<label><input type="checkbox"> I agree to recieve Email Terms and Conditions</label>
</div>
<div class="checkbox">
<label><input type="checkbox"> I agree to recieve SMS Terms and Conditions</label>
</div>
<input type="submit" name="submit" value="SignUp" id="signUp" class="btn btn-success" autocomplete="off">
</form><br><br>
</div>
</div>
<script type="text/javascript">
function validation(){
var title = document.getElementById('title').value;
var firstName = document.getElementById('firstName').value;
var email=document.getElementById('email').value;
var contact=document.getElementById('contact').value;
var password=document.getElementById('password').value;
var conPassword=document.getElementById('conPassword').value;
var signBut=document.getElementById('signUp');
console.log(firstName);
if(title == ""){
document.getElementById("tit").innerHTML =" Please select the title feild first field";
return false;
}
// if(firstName == "" & firstName.length<=3){
// document.getElementById("first").innerHTML =" Please Enter First Name";
// return false;
// document.getElementById("signUp").addEventListener("click", function(event){
// event.preventDefault()
// });
// }
signBut.addEventListener('click',function(e){
if(firstName=="" & firstName<3)
{
document.getElementById("first").innerHTML="Please Enter proper Name";
e.preventDefault();
}
},false);
if(lastName == ""){
document.getElementById("last").innerHTML =" Please Enter Last Name";
return false;
}
else if(email ==""){
document.getElementById("fillemail").innerHTML="Please Enter Email";
}
else if(contact ==""){
document.getElementById("con").innerHTML="Please Enter Your Contact";
}
else if(password ==""){
document.getElementById("pass").innerHTML="Please Enter Your Password";
}
else if(conPassword ==""){
document.getElementById("conPass").innerHTML="Please Confirm Password";
}
}
</script>
</body>
</html>

I think you should use type button
and then eventClick function of jquery

Related

Laravel 9: Data does not appear before editing when the ID is changed then the form autofills using JQUERY AJAX

good afternoon everyone. I'm making a form to edit leave allocation data with jquery ajax. the form consists of (id_kategoricuti, id_karyawan,durasi, mode_alokasi, tgl_masuk, tgl_sekarang, aktif_dari, sampai).
Previously in from create, the conditions are:
when id_kategoricuti is selected, the form durasi, mode_alokasi will be filled in automatically using ajax.
For example, in the selected id_kategoricuti id form Cuti Tahunan, the tgl_masuk and tgl_sekarang forms will appear.
then, when selecting id_karyawan, the tanggal_masuk form will automatically be filled according to the entry date data in the employee table. so that only the aktif_dari and sampai forms are filled in.
condition from edit leave allocation:
data appears according to the id that has been selected.
the user makes changes to the desired data.
save.
however, I'm facing a problem on this edit form:
because when I click on one of the data to edit, what appears on the form is only id_kategoricuti and id_karyawan.
the form mode_alokasi, durasi, aktif_dari and sampai are empty.
The form was only filled in when id_karyawan/id_kagotericuti was edited.
the data in the box below the category form is the data that should appear on the form.
This is the appearance of the leave allocation edit form before editing:
this is the appearance of the leave allocation edit form after the leave id_categories are edited:
my Controller:
public function getTglmasuk(Request $request)
{
try {
$getTglmasuk = Karyawan::select('tglmasuk')
->where('id','=',$request->id_karyawan)->first();
// dd($request->id_karyawan,$getTglmasuk);
if(!$getTglmasuk) {
throw new \Exception('Data not found');
}
return response()->json($getTglmasuk,200);
} catch (\Exception $e){
return response()->json([
'message' =>$e->getMessage()
], 500);
}
}
public function getSettingalokasi(Request $request)
{
try {
$getSettingalokasi=Settingalokasi::select('id','id_jeniscuti','durasi','mode_alokasi')
->where('id_jeniscuti','=',$request->id_jeniscuti)->first();
if(!$getSettingalokasi) {
throw new \Exception('Data not found');
}
return response()->json($getSettingalokasi,200);
} catch (\Exception $e){
return response()->json([
'message' =>$e->getMessage()
], 500);
}
}
my Editalokasi.blade.php:
{{-- FORM SETTING ALOKASI--}}
<div class="modal fade" id="editalokasi{{$data->id}}" tabindex="-1" role="dialog" aria-
labelledby="editalokasi" 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">×</button>
<h4 class="modal-title" id="editalokasi">Edit Alokasi Cuti</h4>
</div>
<div class="modal-body">
<form class="input" action="/updatealokasi/{{$data->id}}" method="POST"
enctype="multipart/form-data">
#csrf
#method('POST')
<div class="panel-body">
<div class="col-md-6">
<div class="form-group col-sm">
<label for="id_jeniscuti" class="col-form-label">Kategori
Cuti</label>
<select name="id_jeniscuti" id="idjeniscuti" class="form-control">
<option value="{{$data->id_jeniscuti}}" selected>
{{$data->jeniscutis->jenis_cuti}}
</option>
#foreach ($jeniscuti as $jenis)
<option value="{{$jenis->id }}">{{ $jenis->jenis_cuti }}
</option>
#endforeach
</select>
</div>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idsettingalokasi" value="{{$data-
>id_settingalokasi}} --> id settingalokasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->id_jeniscuti}}
--> id kategori" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->id_karyawan}} -
->id karyawan" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->durasi}} Hari
--> durasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->mode_alokasi}}
-->mode alokasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="
{{\Carbon\carbon::parse($data->aktif_dari)->format('m/d/Y')}} --
>aktif dari" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="
{{\Carbon\carbon::parse($data->sampai)->format('m/d/Y')}} -->sampai tanggal"readonly>
<div class="form-group col-sm" id="idkaryawan">
<label for="id_karyawan" class="col-form-label">Karyawan</label>
<select name="id_karyawan" id="id_karyawan" class="form-control">
<option value="{{$data->id_karyawan}}" selected>{{$data->karyawans->nama}}</option>
#foreach ($karyawan as $data)
<option value="{{ $data->id }}">{{ $data->nama }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="durasi" class="col-form-label">Durasi (Hari)</label>
<input type="text" class="form-control" name="durasi" placeholder="durasi" id="duration" value="{{$data->durasi}}" readonly>
</div>
<div class="form-group">
<label for="mode_alokasi" class="col-form-label">Mode Alokasi</label>
<input type="text" class="form-control" name="mode_alokasi" placeholder="mode alokasi" value="{{$data->mode_alokasi}}" id="modealokasi" readonly>
</div>
</div>
<div class="col-md-6">
<div class="" id="tglmulai">
<div class="form-group">
<label for="tgl_masuk" class="form-label">Tanggal Masuk</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="tglmasuk" name="tgl_masuk" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tglnow">
<div class="form-group">
<label for="tgl_sekarang" class="form-label">Tanggal Sekarang</label>
<div class="input-group">
<input type="text" class="form-control" id="tglsekarang" name="tgl_sekarang" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalmulai">
<div class="form-group">
<label for="tgl_mulai" class="form-label">Aktif Dari</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea3" name="aktif_dari" value="{{\Carbon\carbon::parse($data->aktif_dari)->format('m/d/Y')}}" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalselesai">
<div class="form-group">
<label for="sampai" class="form-label">Sampai</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea4" name="sampai" value="{{\Carbon\carbon::parse($data->sampai)->format('m/d/Y')}}" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" name="submit" value="save">Save Changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/app.js"></script>
<script src="assets/pages/form-advanced.js"></script>
my Javascript:
<!-- script to fetch data settingalokasi from table settingalokasi -->
<script>
$('#idjeniscuti').on('change',function(e){
var id_jeniscuti = e.target.value;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
});
$.ajax({
type:"POST",
url: '{{route('get.Setting.alokasi')}}',
data: {'id_jeniscuti':id_jeniscuti},
success:function(data){
// console.log(data);
$('#idsettingalokasi').val(data.id);
$('#duration').val(data.durasi);
$('#modealokasi').val(data.mode_alokasi);
}
});
});
</script>
<!-- script to fetch data tanggal_masuk from table karyawan-->
<script>
$('#id_karyawan').on('change',function(e){
var id_karyawan = e.target.value;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
});
$.ajax({
type:"POST",
url: '{{route('get.Tanggalmasuk')}}',
data: {'id_karyawan':id_karyawan},
success:function(data){
// console.log(data);
$('#tgl_masuk').val(data.tglmasuk);
// console.log(data?.tglmasuk)
}
});
});
</script>
<script type="text/javascript">
$(function()
{
$('#tglmulai').prop("hidden", true);
$('#tglnow').prop("hidden", true);
$('#jenicuti').on('change', function(a)
{
if(a.target.value == 1)
{
$('#tglmulai').prop("hidden", false);
$('#tglnow').prop("hidden", false);
} else
{
$('#tglmulai').prop("hidden", true);
$('#tglnow').prop("hidden", true);
}
});
});
</script>
this is my first time using JQUERY AJAX for AUTOFILL. can anyone help me to solve this problem?

Why is my AJAX call in jQuery not working?

What am I trying to achieve:
After form is being filled-out and submit button being clicked, I want to be able to submit form and do an AJAX call - payment.php file (I did integration of PayPal, I am sending following values via mail firstname, surname, email, phone, number, date of birth, CV, photo, etc...) and I am also trying to store it into the database.
Where am I failing at?
This is multiple-step form, the problem is occuring when I get to the last step of filling-out form and by clicking "Submit" button nothing happens - my AJAX call is not working...
My jQuery code:
$(document).ready(function(){
var current_fs, next_fs, previous_fs; //fieldsets
var opacity;
var current = 1;
var steps = $("fieldset").length;
setProgressBar(current);
$(".next").click(function(){
current_fs = $(this).parent();
next_fs = $(this).parent().next();
//Add Class Active
$("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");
//show the next fieldset
next_fs.show();
//hide the current fieldset with style
current_fs.animate({opacity: 0}, {
step: function(now) {
// for making fielset appear animation
opacity = 1 - now;
current_fs.css({
'display': 'none',
'position': 'relative'
});
next_fs.css({'opacity': opacity});
},
duration: 500
});
setProgressBar(++current);
});
$(".previous").click(function(){
current_fs = $(this).parent();
previous_fs = $(this).parent().prev();
//Remove class active
$("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");
//show the previous fieldset
previous_fs.show();
//hide the current fieldset with style
current_fs.animate({opacity: 0}, {
step: function(now) {
// for making fielset appear animation
opacity = 1 - now;
current_fs.css({
'display': 'none',
'position': 'relative'
});
previous_fs.css({'opacity': opacity});
},
duration: 500
});
setProgressBar(--current);
});
function setProgressBar(curStep){
var percent = parseFloat(100 / steps) * curStep;
percent = percent.toFixed();
$(".progress-bar")
.css("width",percent+"%")
}
$(".submit").click(function(){
var request;
//moj kod
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $("#msform");
// 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();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "payment.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Request uspješno poslat!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.log(JSON.stringify(errorThrown));
console.error(
"Desio se sljedeci error: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
//moj kod ->end
return false;
})
});
This is jQuery code (obviously) - and here I am handling the form and its data (at least it's what I intended to do with it)
This is form inside of HTML:
<form class="paypal" action="payment.php" method="post" name="Form" id="msform">
<?php
$paket = $_GET['paket'];
if($paket == "standard")
{
?>
<input type="hidden" name="standard" value="standard">
<input type="hidden" name="item_number" value="1">
<?php
}
else if($paket == "bewerbungscheck")
{
?> <input type="hidden" name="bewerbungscheck" value="bewerbungscheck">
<input type="hidden" name="item_number" value="2">
<?php
}
else if($paket == "premium")
{
?> <input type="hidden" name="premium" value="premium">
<input type="hidden" name="item_number" value="3">
<?php
}
else if($paket == "lowbudget")
{
?>
<input type="hidden" name="lowbudget" value="lowbudget">
<input type="hidden" name="item_number" value="4">
<?php
}
else{
echo "There's no package with this name, please go back and choose again, wisely!";
?>
<button class="btn">
Go Back
</button>
<?php
exit();
}
?>
<!-- progressbar -->
<ul id="progressbar">
<li class="active" id="account"><strong>Personal Info</strong></li>
<li id="personal"><strong>Appointment</strong></li>
<li id="payment"><strong>Documents</strong></li>
<li id="confirm"><strong>Finish</strong></li>
</ul>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar"
aria-valuemin="0" aria-valuemax="100"></div>
</div>
<br>
<!-- fieldsets -->
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Personal Information:</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 1 - 4</h2>
</div>
</div>
<!-- FOR PAYPAL -->
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="lc" value="DE" />
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" />
<input type="hidden" id="first_name" name="first_name" value="Customer's First Name" />
<input type="hidden" id="last_name" name="last_name" value="Customer's Last Name" />
<input type="hidden" id="payer_email" name="payer_email" value="customer#example.com" />
<!-- END OF SECTION FOR PAYPAL -->
<label class="fieldlabels">Email: *</label>
<input id="email" type="email" name="email" placeholder="example#meinegutebewerbung.de" />
<label class="fieldlabels">Name: *</label>
<input id="fn" type="text" name="uname" placeholder="Name" />
<label class="fieldlabels">Surname: *</label>
<input id="sur" type="text" name="usur" placeholder="Surname" />
<label class="fieldlabels">Expertised in: *</label>
<input type="text" name="expert" placeholder="ex.:Bachelor in Computer science" />
<label class="fieldlabels">Phone number: *</label>
<input type="tel" name="phone" placeholder="+000000000000000" />
<label class="fieldlabels">Birth Date: *</label>
<input type="date" name="date" placeholder="Date" />
</div>
<input type="button" name="next" onclick="populate()" class="next action-button"
value="Next" />
</fieldset>
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Appointment details:</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 2 - 4</h2>
</div>
</div>
<label class="fieldlabels">Select appointment date: *</label>
<input id="date_picker" type="date" name="date-res" />
<label class="fieldlabels">Which time span is the most fitting for you: *</label> <br>
<select name="suitabletime " id="suitable">
<option value="09-14">09:00 - 14:00</option>
<option value="14-20">14:00 - 20:00</option>
</select>
</div>
<input type="button" name="next" class="next action-button" value="Next" />
<input type="button" name="previous" class="previous action-button-previous"
value="Previous" />
</fieldset>
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Upload documents:</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 3 - 4</h2>
</div>
</div>
<label class="fieldlabels">Upload Your Photo:</label>
<input type="file" name="pic" accept="image/*">
<label class="fieldlabels">Upload CV (must be PDF):</label>
<input type="file" name="pic" accept=".pdf">
</div>
<input type="button" name="next" class="next action-button" value="Submit" />
<input type="button" name="previous" class="previous action-button-previous"
value="Previous" />
</fieldset>
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Finish:</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 4 - 4</h2>
</div>
</div>
<br><br>
<h2 class="purple-text text-center"><strong>SUCCESS !</strong></h2>
<br>
<div class="row justify-content-center">
<div class="col-3">
<img src="https://i.imgur.com/GwStPmg.png" class="fit-image">
</div>
</div>
<br><br>
<div class="row justify-content-center">
<div class="col-7 text-center">
<h5 class="purple-text text-center">You Have Successfully Signed Up</h5>
</div>
</div>
</div>
</fieldset>
</form>
How did I came to conclusion that this is not working?
I have actually inserted console.log() so I can get some output after the code is executed, but I am not getting anything. The second thing is that I also setted up PHP to do echo and again I am not getting anything.
As #kikon already stated inside of the comments, the problem was that I did not put the class="submit" as a attribute to the <button>, therefore element with the class of submit didn't exist, so the jQuery couldn't trigger the code inside of the function for AJAX.

unable to insert record through jquery ajax

Right now I am facing a problem : I am trying to insert records in the database with the help of jQuery & Ajax. Unfortunately, I tried to alert inserted values but It doesn't show. I also checked through serialize function and I am unable to do that.
Here is my code of ajax
<script type="text/javascript">
$(document).ready(function(){
$("#add_new").click(function(){
$("#add").slideToggle();
});
$("#submit").click(function(){
var stud_no=$("#roll").val();
if(stud_no==''){
$("#msg").html("Input Roll Number");
} else {
var datastr = $("#sampleform").serialize();
alert(datastr);
$.ajax({
type:'POST',
url:'add_it.php',
data:datastr,
success:function(response){
$("#my_form")[0].reset();
$("#msg").html("Student Successfully Added");
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
});
});
</script>
Here is body code :
<body>
<a id="add_new">+add new item</a><br /><br />
<div id="msg"></div><br />
<div id="add">
<form id="sampleform">
<fieldset>
<div class="form-group row">
<label for="roll" class="col-sm-2 col-form-label">Roll Number</label>
<div class="col-sm-6">
<input type="text" name="roll" class="form-control" id="roll">
</div>
</div>
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-6">
<input type="text" name="name" class="form-control" id="name">
</div>
</div>
<div class="form-group row">
<label for="clas" class="col-sm-2 col-form-label">Class</label>
<div class="col-sm-6">
<input type="text" name="standard" class="form-control" id="standard">
</div>
</div>
<div class="form-group row">
<label for="mail" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-6">
<input type="email" name="mail" class="form-control" id="mail">
</div>
</div>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</fieldset>
</fieldset>
</form>
</div>
Here is my add_it.php
<?php
include('connectdb.php');
$stud_no = trim($_POST['stud_no']);
$name = trim($_POST['name']);
$standard = trim($_POST['standard']);
$mail = trim($_POST['mail']);
$query = "insert into student (stud_no,name,standard,email) values ('$stud_no','$name','$standard','$mail')";
mysqli_query($con,$query) or die (mysqli_error());
?>
Your HTML form fields doesnt have any of these variables sent. You need to add name="email" etc to your form fields.
So for example the email field has to look like this:
<input type="email" name="email" class="form-control" id="mail">
id, class etc is not sent in POST - and therefor can not be recieved in the other end.
Jquery's serialize() function also only handles "name" fields.
https://api.jquery.com/serialize/
Snippet :
For a form element's value to be included in the serialized string, the element must have a name attribute

How to Activate Submit button once all fields are filled

I have the following code displaying input fields in a form. I want to have the submit button active only once all fields are filled. I cant seem to figure out where I've gone wrong. I have omitted some text inputs here for space.
Form:
<?php
if(#$_GET['q']==4 && !(#$_GET['step']) ) {
echo '
<div class="row">
<span class="title1" style="margin-left:40%;font-size:30px;"><b>Enter Quiz Details</b></span><br /><br />
<div class="col-md-3"></div><div class="col-md-6"> <form class="form-horizontal title1" name="form" action="update.php?q=addquiz" method="POST">
<fieldset>
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
<label for="name">Enter Title</label>
<input id="name" name="name" class="form-control input-md" type="text">
</div>
</div>
<div class="form-group">
<label class="col-md-12 control-label" for=""></label>
<div class="col-md-12">
<input type="submit" style="margin-left:45%" class="btn btn-primary" value="Submit" class="btn btn-primary" id="submit" disabled="disabled"/>
</div>
</div>
</fieldset>
</form>
</div>';
}
?>
<script>
(function() {
$('form input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#submit').attr('disabled', 'disabled'); //Leave as disabled if any of the fields are empty
} else {
$('#submit').removeAttr('disabled');//Remove the disabled attribute once all fields are filled
}
});
});
</script>
The code is exactly as it appears here. If I've missed something, kindly point me in a direction. Thank you.
You are using the attribute as disabled="disabled" buts its an attribute having no value you should use it like this <input type="submit" style="margin-left:45%" class="btn btn-primary" value="Submit" class="btn btn-primary" id="submit" disabled/>
Here I have created a working JSFiddle for you check it and do correction https://jsfiddle.net/g1cra5f8/

How to submit form on one page to a different page using ajax call in jquery

I have a page called page2.php. It has a form that allows you to search via jquery ajax call. The code is below. My question is, I have a different form on page1.php. How can I submit the form on page1.php to go to page2.php and have it execute the page2.php code below using the data from the form on page1.php? I know this is most likely simple, having a brain fart right now.
$(function() {
$.validate({
form: '#form_search',
validateOnBlur: false,
errorMessagePosition: 'top',
onSuccess: function(form) {
var formval = $(form).serialize();
var formurl = '/page2.php?a=search';
$('#form_results').html('<div class="form_wait_search">Searching, please wait...<br><img src="/images/search-loader.gif"></div>');
$.ajax({
type: 'POST',
url: formurl,
data: formval,
success: function(data){
var json = $.parseJSON(data);
$('#form_errors').html(json.message);
$('#form_results').html(json.results);
}
});
return false;
}
});
});
UPDATE
Here is the forms Im referring to.
On page1.php this is like a module on the right side bar. Just a form that I want to post to page2.php
<div class="scontent_box1">
<strong class="box_title"><i class="fa fa-search fa-flip-horizontal"></i> Find Locations</strong>
<form method="post" action="/page2.php">
<div class="form-group">
<label>Street Address</label>
<input type="text" class="form-control" name="ad" placeholder="Enter Street Address...">
</div>
<div class="form-group">
<label>City, State or Zip Code</label>
<input type="text" class="form-control" name="ct" placeholder="Enter City, State or Zip Code...">
</div>
<button type="submit" class="btn btn-default blue_btn">Search</button>
</form>
</div>
Now here is the form on page2.php that executes the ajax code above. I want page1.php to submit to page2.php and envoke the same jquery code above.
<div class="row no_gutters">
<div class="search_page">
<div id="form_errors"></div>
<form method="post" id="form_search">
<div class="form-group">
<label for="ad">Street Address<span class="reqfld">*</span></label>
<input type="text" class="form-control" data-validation="required" id="ad" name="ad" placeholder="Enter Street Address..." value="">
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="ct">City, State or Zip Code<span class="reqfld">*</span></label>
<input type="text" class="form-control input-sm" data-validation="required" id="ct" name="ct" placeholder="Enter City Name..." value="">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-xs-12">
<button type="submit" class="btn btn-default blue_btn btn-block">Search Locations</button>
</div>
<div class="col-md-8"></div>
</div>
</form>
</div>
<div id="form_results"></div>
</div>

Categories