How to exclude hidden form elements to form serialization - php

I'm burned out finding ways to exclude hidden elements from form serialization.
I tried to use this code:
$("#form-user :not(.hide_element) > :input").serialize();
or this one:
$("#form-user").not(".hide_element > input").serialize();
but still got the same form-data response
I've put the form inside my modal.
<div class="modal-body">
<?php echo form_open('#',array("class"=>"form-horizontal","id"=>"form-user")); ?>
<div id="message"></div>
<div class="form-group">
<label class="control-label col-md-3">Username:</label>
<div class="col-md-9">
<input type="text" name="uname" class="form-control">
</div>
</div>
<div class="form-group hide_element" >
<label class="control-label col-md-3" id='lblpass'>Password:</label>
<div class="col-md-9">
<input type="password" name="pass" class="form-control">
</div>
</div>
<div class="form-group hide_element">
<label class="control-label col-md-3" id='lblnewpass'>Confirm Password:</label>
<div class="col-md-9">
<input type="password" name="confirmpass" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Email Address:</label>
<div class="col-md-9">
<input type="email" name="email" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">User Status:</label>
<div class="col-md-9">
<select name="userstatus" class="form-control">
<option hidden>Select user status of the account (Default = Active)</option>
<option value="1">Active</option>
<option value="2">Inactive</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">User Type:</label>
<div class="col-md-9">
<select name="usertype" class="form-control">
<option hidden>Select user type of the account (Default = Customer)</option>
<option value=1>Customer</option>
<option value=2>Admin</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-success" type="button" id="action"><i class="fa fa-save"></i> Add user</button>
<button class="btn btn-danger" type="button" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>
<?php echo form_close(); ?>
my ajax function:
$(document).ready(function(){
$('#form-user').on('click','#action',function(e){
e.preventDefault();
if(action == 'add'){
$.ajax({
url: site_url('User/add_user'),
data: $("#form-user :not(.working) > input").serialize(),
type:'POST',
encode: true,
dataType:'json',
success:function(data){
if(!data.success){
if(data.errors){
$('#message').html(data.errors).addClass('alert alert-danger');
}
}else{
$('#message').html("").removeClass('alert alert-danger');
$('.modal-title').html('Processing request');
$('#alert').modal('show');
$('#mymodal').modal('hide');
$('#body-message').html("<i class='fa fa-spinner fa-pulse fa-3x fa-fw'></i> Updating...");
setTimeout(function(){
$('#body-message').html("<i class='fa fa-check fa-3x'></i>"+ data.message);
},3000)
setTimeout(function(){
$('#alert').modal('hide');
$('#form-user')[0].reset();
reloadData();
},5000);
}
}
});
}else{
$.ajax({
url: site_url('User/update_user'),
data: $("#form-user :not(.working) > :input").serialize() +"&id=" + id,
type:'POST',
encode: true,
dataType:'json',
success:function(data){
if(!data.success){
if(data.errors){
$('#message').html(data.errors).addClass('alert alert-danger');
}
}else{
$('#message').html("").removeClass('alert alert-danger');
$('.modal-title').html('Processing request');
$('#alert').modal('show');
$('#mymodal').modal('hide');
$('#body-message').html("<i class='fa fa-spinner fa-pulse fa-3x fa-fw'></i> Updating...");
setTimeout(function(){
$('#body-message').html("<i class='fa fa-check fa-3x'></i>"+ data.message);
},3000)
setTimeout(function(){
$('#alert').modal('hide');
$('#form-user')[0].reset();
reloadData();
},5000);
}
}
});
}
});
});

Disabled elements do not get posted nor serialized, so you can temporarily add the disabled attribute to them, and restoring them to their previous state after successfull response:
$('#form-user').on('click','#action',function(e){
$("#form-user .hide_element > input").attr('disabled','disabled');
$.ajax({
...
data: $("#form-user").serialize(),
success:function() {
$("#form-user .hide_element > input").removeAttr('disabled');
}
});
});

Try this:
var frm = $('#finalform').find(":input:not(:hidden)").serialize();
Or
var frm = $('#finalform :input:not(:hidden)').serialize();

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 won't my php code redirect to any php page?

Here is my index page where i can successfully login but wont redirect to any page? just new been trying to get it to working.
<?php include('header.php'); ?>
<body>
<div class="container">
<div style="height:50px;">
</div>
<div class="row" id="loginform">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><span class="glyphicon glyphicon-lock"></span> Login
<span class="pull-right"><span class="glyphicon glyphicon-pencil"></span> <a style="text-decoration:none; cursor:pointer; color:white;" id="signup">Sign up</a></span>
</h3>
</div>
<!-- Body For Login -->
<div class="panel-body">
<form role="form" id="logform">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" name="username" id="username" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" id="password" type="password">
</div>
<button type="button" id="loginbutton" class="btn btn-lg btn-primary btn-block"><span class="glyphicon glyphicon-log-in"></span> <span id="logtext">Login</span></button>
</fieldset>
</form>
<!-- Body For Login -->
</div>
</div>
</div>
</div>
<div class="row" id="signupform" style="display:none;">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><span class="glyphicon glyphicon-pencil"></span> Sign Up
<span class="pull-right"><span class="glyphicon glyphicon-log-in"></span> <a style="text-decoration:none; cursor:pointer; color:white;" id="login">Login</a></span>
</h3>
</div>
<div class="panel-body">
<!-- Body for Sign up -->
<form role="form" id="signform">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Full Name" name="name" id="name" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Email" name="email" id="email" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Username" name="susername" id="susername" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="spassword" id="spassword" type="password">
</div>
<button type="button" id="signupbutton" class="btn btn-lg btn-primary btn-block"><span class="glyphicon glyphicon-check"></span> <span id="signtext">Sign Up</span></button>
</fieldset>
</form>
<!-- Body for Sign up -->
</div>
</div>
</div>
</div>
<div id="myalert" style="display:none;">
<div class="col-md-4 col-md-offset-4">
<div class="alert alert-info">
<center><span id="alerttext"></span></center>
</div>
</div>
</div>
</div>
<script src="custom.js"></script>
</body>
</html>
i don't know why but just keep going back to index.page
<?php
include('conn.php');
session_start();
if(isset($_POST['logform'])){
$username=$_POST['username'];
$password=md5($_POST['password']);
$query=$conn->query("select * from users where username='$username' and password='$password'");
if ($query->num_rows>0) {
$row=$query->fetch_array();
if ($row['level']=="admin") {
$_SESSION['users']=$row['id'];
$_SESSION['level']=$row['level'];
header('location: admin/index.php');
}elseif ($row['level']=="agent") {
$_SESSION['users']=$row['id'];
$_SESSION['level']=$row['level'];
header('location: agent/index.php');
}elseif ($row['level']=="user") {
$_SESSION['users']=$row['id'];
$_SESSION['level']=$row['level'];
header('location: agent/index.php');
}else{
?>
<span>Login Failed. User not Found.</span>
<?php
}
}
}
Here is my login action form it working but will not redirect to any page that i set them i don't know why but im trying my best how to work around the problem
Here is my custom.js which tell the php what to do next
$(document).ready(function(){
//bind enter key to click button
$(document).keypress(function(e){
if (e.which == 13){
if($('#loginform').is(":visible")){
$("#loginbutton").click();
}
else if($('#signupform').is(":visible")){
$("#signupbutton").click();
}
}
});
$('#signup').click(function(){
$('#loginform').slideUp();
$('#signupform').slideDown();
$('#myalert').slideUp();
$('#signform')[0].reset();
});
$('#login').click(function(){
$('#loginform').slideDown();
$('#signupform').slideUp();
$('#myalert').slideUp();
$('#logform')[0].reset();
});
$(document).on('click', '#signupbutton', function(){
if($('#susername').val()!='' && $('#spassword').val()!=''){
$('#signtext').text('Signing up...');
$('#myalert').slideUp();
var signform = $('#signform').serialize();
$.ajax({
method: 'POST',
url: 'signup.php',
data: signform,
success:function(data){
setTimeout(function(){
$('#myalert').slideDown();
$('#alerttext').html(data);
$('#signtext').text('Sign up');
$('#signform')[0].reset();
}, 2000);
}
});
}
else{
alert('Please input both fields to Sign Up');
}
});
$(document).on('click', '#loginbutton', function(){
if($('#username').val()!='' && $('#password').val()!=''){
$('#logtext').text('Logging in...');
$('#myalert').slideUp();
var logform = $('#logform').serialize();
setTimeout(function(){
$.ajax({
method: 'POST',
url: 'login.php',
data: logform,
success:function(data){
if(data==''){
$('#myalert').slideDown();
$('#alerttext').text('Login Successful. User Verified!');
$('#logtext').text('Login');
$('#logform')[0].reset();
setTimeout(function(){
location.reload();
}, 2000);
}
else{
$('#myalert').slideDown();
$('#alerttext').html(data);
$('#logtext').text('Login');
$('#logform')[0].reset();
}
}
});
}, 2000);
}
else{
alert('Please input both fields to Login');
}
});
});
Try to use
<input type ="submit" id="loginbutton">
instead of
<button type="button" id="loginbutton">
to post your form.
Change
header('location: admin/index.php');
to
header('Location: agent/index.php');
it is an easy mistake to make
You forgot to define the methodand action in form tag. The method attribute specifies how to send form-data. When posting a form, it always good to have a method is post. As for action, a route or file location where action should perform.
So try this:
<form method="post" action="/{_action_filename_}.php">

bootstrap modal insert form submit won't reset to add another entry

I am using php mysql to insert to the database and that was working, however the bootstrap modal won't let me submitting another item. The button still says inserting and the last inserted data is still showing in the inputs.
I want to insert multiple times as this becomes part of a larger edit form.
This is put outside of the edit form submit button:
<div id="add_data_Modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<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>
<h4 class="modal-title">Add A New Item</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<input type="hidden" name="job_id" id="job_id" value="<?php echo $job_id;?>">
<input type="hidden" class="form-control" id="job_mat_qty" name="job_mat_qty" value="1" />
<div class="form-group">
<label for="job_mat_desc" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea class="form-control editors" id="job_mat_desc" name="job_mat_desc" autocomplete="off" placeholder="Enter item title and / or description" />
</textarea>
</div>
</div>
<div class="form-group">
<label for="job_mat_cost" class="col-sm-2 control-label">Price</label>
<div class="col-sm-10">
<div class="input-group input-group"> <span class="input-group-addon"><?php echo CURRENCY ?></span>
<input type="text" class="form-control calculate invoice_product_price txt" autocomplete="off" id="job_mat_cost" name="job_mat_cost" aria-describedby="sizing-addon1" placeholder="0.00" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10"> </div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="insert" id="selected" value="Insert" class="btn btn-success" />
</div>
</form>
</div>
</div>
</div>
$(document).on('click', '.delete-rows', function(){
var id = $(this).attr("id");
if (confirm("Are you sure you want to delete this Item?")) {
$.ajax({
type: "POST",
url: "job_remove_material_new.php",
data: ({
id: id
}),
cache: false,
success: function(html) {
$(".delete_mem" + id).fadeOut('slow');
}
});
} else {
return false;
}
});
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#job_mat_desc').val() == "")
{
alert("Description is required");
}
else
{
$.ajax({
url:"add_material.php",
method:"POST",
data:$('#insert_form').serialize(),
cache: false,
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#invoice_table').html(data);
}
});
$(function () {
$(document).on("hidden.bs.modal", "#add_data_Modal", function () {
$('#insert_form')[0].reset();
});
});
}
});
Sorry I have no clue how to add this code correctly for this forum so please be kind....
Thanks
You should try like this
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#job_mat_desc').val() == "")
{
alert("Description is required");
}
else
{
$.ajax({
url:"add_material.php",
method:"POST",
data:$('#insert_form').serialize(),
cache: false,
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
//$('#insert_form')[0].reset();
$('#insert_form input[type="text"],textarea').val(''); // here is change
$('#add_data_Modal').modal('hide');
$('#invoice_table').html(data);
}
});
In my case it will work successfully so I hope it will help you

AJAX POST Object return partial data

I'm using wamp64 webserver and I'm try to post some values to a PHP script to create a PDF (with TCPDF library).
I've a lot (more or less 80) of field to pass (POST) with AJAX and the problem seems to be the amount of variable (or memory, I don't know).
If I try to pass less variable everything it is OK, but when I try to POST the complete set of fields PHP returns an error regarding indexing of Object I'm passing.
This is what I'm try to POST:
$('#btnGeneraPDF').click(function() {
var campi = {
//DATI RICHIESTA VERIFICA
dataCompilazione: $('#data-compilazione').val(),
dataAccettazione: $('#data-accettazione').val(),
rifPreventivo: $('#cod-preventivo').val(),
codRichiesta: $('#cod-rdv').val(),
//DATI UTENTE METRICO
UMragSociale: $('#UM-ragSociale').val(),
UMpiva: $('#UM-piva').val(),
UMrea: $('#UM-rea').val(),
//DATI REFERENTE
REFnominativo: $('#ref-nominativo').val(),
REFtelefono: $('#ref-telefono').val(),
REFemail: $('#ref-email').val(),
REFindirizzo: $('#ref-indirizzo').val(),
REFcomune: $('#ref-comune').val(),
REFprovincia: $('#ref-provincia').val(),
REFcap: $('#ref-cap').val(),
REFnote: $('#ref-note').val(),
STRtipo1: $('#STRtipo1 :selected').text(),
STRmarca1: $('#STRmarca1').val(),
STRmodello1: $('#STRmodello1').val(),
STRmatricola1: $('#STRmatricola1').val(),
STRpistole1: $('#STRpistole1').val(),
STRportata1: $('#STRportata1').val(),
STRprePostPay1: $('#STRprePostPay1 :checked').val(),
STRnote1: $('#STRnote1').val(),
STRtipo2: $('#STRtipo2 :selected').text(),
STRmarca2: $('#STRmarca2').val(),
STRmodello2: $('#STRmodello2').val(),
STRmatricola2: $('#STRmatricola2').val(),
STRpistole2: $('#STRpistole2').val(),
STRportata2: $('#STRportata2').val(),
STRprePostPay2: $('#STRprePostPay2 :checked').val(),
STRnote2: $('#STRnote2').val(),
STRtipo3: $('#STRtipo3 :selected').text(),
STRmarca3: $('#STRmarca3').val(),
STRmodello3: $('#STRmodello3').val(),
STRmatricola3: $('#STRmatricola3').val(),
STRpistole3: $('#STRpistole3').val(),
STRportata3: $('#STRportata3').val(),
STRprePostPay3: $('#STRprePostPay3 :checked').val(),
STRnote3: $('#STRnote3').val(),
STRtipo4: $('#STRtipo4 :selected').text(),
STRmarca4: $('#STRmarca4').val(),
STRmodello4: $('#STRmodello4').val(),
STRmatricola4: $('#STRmatricola4').val(),
STRpistole4: $('#STRpistole4').val(),
STRportata4: $('#STRportata4').val(),
STRprePostPay4: $('#STRprePostPay4 :checked').val(),
STRnote4: $('#STRnote4').val(),
STRtipo5: $('#STRtipo5 :selected').text(),
STRmarca5: $('#STRmarca5').val(),
STRmodello5: $('#STRmodello5').val(),
STRmatricola5: $('#STRmatricola5').val(),
STRpistole5: $('#STRpistole5').val(),
STRportata5: $('#STRportata5').val(),
STRprePostPay5: $('#STRprePostPay5 :checked').val(),
STRnote5: $('#STRnote5').val(),
STRtipo6: $('#STRtipo6 :selected').text(),
STRmarca6: $('#STRmarca6').val(),
STRmodello6: $('#STRmodello6').val(),
STRmatricola6: $('#STRmatricola6').val(),
STRpistole6: $('#STRpistole6').val(),
STRportata6: $('#STRportata6').val(),
STRprePostPay6: $('#STRprePostPay6 :checked').val(),
STRnote6: $('#STRnote6').val(),
STRtipo7: $('#STRtipo7 :selected').text(),
STRmarca7: $('#STRmarca7').val(),
STRmodello7: $('#STRmodello7').val(),
STRmatricola7: $('#STRmatricola7').val(),
STRpistole7: $('#STRpistole7').val(),
STRportata7: $('#STRportata7').val(),
STRprePostPay7: $('#STRprePostPay7 :checked').val(),
STRnote7: $('#STRnote7').val(),
STRtipo8: $('#STRtipo8 :selected').text(),
STRmarca8: $('#STRmarca8').val(),
STRmodello8: $('#STRmodello8').val(),
STRmatricola8: $('#STRmatricola8').val(),
STRpistole8: $('#STRpistole8').val(),
STRportata8: $('#STRportata8').val(),
STRprePostPay8: $('#STRprePostPay8 :checked').val(),
STRnote8: $('#STRnote8').val(),
note: $('#rdv-note').val()
};
//GENERAZIONE PDF
$.ajax({
type: 'POST',
url: 'mysite/pdf/save.php',
async: true,
cache: false,
data: {data: campi},
beforeSend: function(){
},
success: function(response) {
console.log (campi);
setTimeout( function() {
console.log("AJAX SUCCESS");
}, 10 );
if (!response.status) {
alert("Error calling save");
return;
}
if (response.status != 'OK') {
alert(response.status);
return;
}
// We had a response and it was "OK". We're good.
window.open("mysite/pdf/pdfTest.php");
},
error: function( XMLHttpRequest, textStatus, errorThrown ) {
console.log("AJAX ERROR: \n" + errorThrown);
console.log("AJAX ERROR: \n" + textStatus);
}
});
})
This is save.php
<?php // this is save.php
session_start();
// DO NOT just copy from _POST to _SESSION,
// as it could allow a malicious user to override security.
// Use a disposable variable key, such as "data" here.
if (array_key_exists('data', $_POST)) {
$_SESSION['data'] = $_POST['data'];
$_SESSION['data.timestamp'] = time();
// Let us let the client know what happened
$msg = 'OK';
} else {
$msg = 'No data was supplied';
}
Header('Content-Type: application/json; charset=utf8');
die(json_encode(array('status' => $msg)));
?>
The HTML code is:
<div class="tab-pane fade in active" id="tab1">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="STRtipo" class="control-label sr-only">Tipo</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<select name="select2" id="STRtipo1" class="form-control">
<option value=" "> </option>
<option value="NAZ">NAZ</option>
<option value="MID">MID</option>
</select>
</div>
</div>
<label for="STRmarca" class="control-label sr-only">Marca</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRmarca1" placeholder="Marca">
</div>
</div>
<label for="STRmodello" class="control-label sr-only">Modello</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRmodello1" placeholder="Modello">
</div>
</div>
<label for="STRmatricola" class="control-label sr-only">Matricola</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRmatricola1" placeholder="Matricola">
</div>
</div>
<label for="STRpistole" class="control-label sr-only">Pistole</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRpistole1" placeholder="Pistole">
</div>
</div>
<label for="STRportata" class="control-label sr-only">Pistole</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRportata1" placeholder="Portata">
</div>
</div>
</div>
</form>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-sm-2 fancy-checkbox">
<input type="checkbox" id="STRprePostPay1" value="1">
<span>Pre / Post Pay</span>
</label>
<label for="STRnote" class="col-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRnote1" placeholder="Note">
</div>
</label>
</div>
</form>
</div>
And it is made for each of 8 instruments, using jQuery:
var tabContent=$('#tab1').clone();
for (i=2;i<=nTab;i++){
$('#tab' + i).append(tabContent.html());
}
for (i=2;i<=nTab;i++){
$('#tab'+i+' select').attr('id','STRtipo' + i);
$('#tab'+i).find('#STRmarca1').attr('id','STRmarca' + i);
$('#tab'+i).find('#STRmodello1').attr('id','STRmodello' + i);
$('#tab'+i).find('#STRmatricola1').attr('id','STRmatricola' + i);
$('#tab'+i).find('#STRpistole1').attr('id','STRpistole' + i);
$('#tab'+i).find('#STRportata1').attr('id','STRportata' + i);
$('#tab'+i).find('#STRprePostPay1').attr('id','STRprePostPay' + i);
$('#tab'+i).find('#STRnote1').attr('id','STRnote' + i);
}
This code doesn't work... but if i comment some field in the object 'campi', everything works fine. In particular the problem returned from PHP is on 'STRprePostPay1' variable... It tell that is not passed, and if I put a print_r function, I see that that variable is not passed.
Can someone help me?
THanks

Jquery ajax posts twice

I got an ajax issue I can't get my head around. I'm using a ajax post method to send an email. But everytime I send one the post happens 2 times. I've tried adding preventDefault and stopPropagation but it doesn't seem to do the trick.
Jquery
$(document).ready(function()
{
$("#submit_btn").click(function(event)
{
event.preventDefault();
event.stopPropagation();
var proceed = true;
var submit = $('#submit_btn');
$("#contact_form input, #contact_form textarea").each(function () {
$(this).closest("div").removeClass('has-error');
if(!$.trim($(this).val())) {
$(this).closest("div").addClass('has-error');
proceed = false;
}
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).closest("div").addClass('has-error');
proceed = false;
}
});
if(proceed){
post_data = {
'user_name' : $('input[name=name]').val(),
'user_email' : $('input[name=email]').val(),
'subject' : $('select[name=subject]').val(),
'msg' : $('textarea[name=message]').val()
};
$.ajax({
type: 'POST',
url: "./mail.php",
data: post_data,
beforeSend: function() {
submit.html('Sending...');
},
success: function(data){
output = '<div class="alert alert-success" role="alert">Hi ' + $('input[name=name]').val() + ' Thank you for your email</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
},
error: function(){
output = '<div class="alert alert-danger" role="alert">Something went wrong. Please try again</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
}
});
return false;
}
else{
output = '<div class="alert alert-danger" role="alert">Please fill in the required fields so I can get back to you !</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
}
});
$("#contact_form input, #contact_form textarea").keyup(function() {
$(this).closest("div").removeClass('has-error');
$("#contact_form").find("#contact_results").slideUp();
});
});
HTML
<div class="clear" id="contact">
<h3>Contact Me</h3>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<form role="form" id="contact_form" action="">
<div class="form-group">
<label for="name">Name</label><input name="name" type="text" placeholder="Name" class="form-control" id="name" />
</div>
<div class="form-group">
<label for="email">Email address</label>
<input name="email" type="email" placeholder="E-Mail" class="form-control" id="email" />
</div>
<div class="form-group">
<label for="subject">Subject</label>
<select name="subject" class="form-control" id="subject">
<option value="General Question">General Question</option>
<option value="Hire me!">Hire me !</option>
<option value="Partner with me!">Partner with me !</option>
</select>
</div>
<div class="form-group">
<label for="message">Message</label><textarea name="message" placeholder="Message" id="message" class="form-control" rows="5"></textarea>
</div>
<button type="submit" class="btn btn-default" id="submit_btn">Send</button>
<div id="contact_results"></div>
</form>
</div>
</div>
</div>
</div>
If someone could point me in the right direction that would be much appreciated.
Try changing $("#submit_btn").click(function(event) to $("#submit_btn").one('click',function(event)
If that doesn't work, check that the JS is not being loaded twice

Categories