AJAX POST Object return partial data - php

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

Related

Double insertion of data using modal

I`m working on PHP + MYSQL + AJAX project. I used Bootstrap Modal when adding data. After first time I click add, it will insert two records however it only occurs in its first time click.
Is there any way to prevent saving two records.
I appreciate your help and suggestion. Thanks
This is my modal
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data" class="form-horizontal">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="col-lg-3 control-label">Name</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sName" maxlength="150" id="sName" placeholder="Enter your Name" />
<span id='remainingC'></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sUsername" maxlength="20" id="sUsername" placeholder="Enter your Username"/>
<span id='remainingCu'></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Birthday</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sBirthday"
onchange ="getAge();" maxlength="20" id="sBirthday" placeholder="YYYY-mm-dd"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Age</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="iAge" maxlength="3" id="iAge" placeholder="Autofill when you fill Birthday"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sEmail" id="sEmail" placeholder="Enter your Email - eg. jb#gmail.com"/>
</div>
</div>
My AJAX requests
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
$('#operation').val("Add");
// $('#user_uploaded_image').html('');
});
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 4],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var sName = $('#sName').val();
var sUsername = $('#sUsername').val();
var sBirthday = $('#sBirthday').val();
var iAge = $('#iAge').val();
var sEmail = $('#sEmail').val();
if(sName != '' && sUsername != '' && sBirthday != '' && iAge != '' && sEmail != '')
{
$.ajax({
url:"insert.php",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Both Fields are Required");
}
});
This is my Function for adding (insert.php)
if($_POST["operation"] == "Add")
{
$statement = $connection->prepare("
INSERT INTO users (sName, sUsername, sBirthday, iAge, sEmail)
VALUES (:sName, :sUsername, :sBirthday, :iAge, :sEmail)
");
$result = $statement->execute(
array(
':sName' => $_POST["sName"],
':sUsername' => $_POST["sUsername"],
':sBirthday' => $_POST["sBirthday"],
':iAge' => $_POST["iAge"],
':sEmail' => $_POST["sEmail"]
)
);
if(!empty($result))
{
echo 'Data Inserted';
}
}
Duplicate data after 1st click of add button in modal:
Duplicate

How to exclude hidden form elements to form serialization

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

405 (Method Not Allowed) in custom URL Route Laravel 5.2

I got stuck with my ajax POST request.
My URL looks like this localhost/product/list (if a row is clicked,it will redirect to page.edit through a request like this localhost/product/list/edit/{id} )
When localhost/product/list/edit/{id} receives the edit request the response shows an error like localhost/product/list/edit/update_list 405 (Method Not Allowed).
I am confused why the URL changes from localhost/product/list/edit/{id} to localhost/product/list/edit/update_list, I mean the variable /{id} is missing.
Console always marks this part in my AJAX edit.js as an error.
$.ajax({
type:"POST",
data: {
'id': id,
'judul': judulArtikel,
'isi': isiArtikel,
// --- till the end ---
}
});
Here is my load.js which loads data from a database.
<td><a id='"+result.data[count-1].id+"'' href='list/edit/"+result.data[count-1].id+"' class='glyphicon glyphicon-pencil'></a></td>
Here is my route.php.
Route::get('list/edit/{id}', 'Controller#list_to_edit');
Route::post('/update_list', 'ProductController#update_list');
Here is my controller.
public function list_to_edit($id){
$artikel = Artikel::where("id","=",$id)->get();
return view('page.edit',compact('artikel'));
}
Here is my edit.js.
$(document).ready(function(){
$('#isi_artikel').summernote({
height: 300,
minHeight: 400,
maxHeight: 400,
focus: true
});
$('#btn_submit').click(function(e){
e.preventDefault();
var isiArtikel = $('#isi_artikel').summernote('code');
var judulArtikel = $('#judul').val();
var deskripsiArtikel = $('#deskripsi').val();
var kategori = $('input[name="etype"]:checked').val();
if($('#inputpicture').val() == ""){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN':$('meta[name="csrf_token"]').attr('content')
}
})
$.ajax({
type:"POST",
data: {
'id' : id,
'judul' : judulArtikel,
'isi' : isiArtikel,
'kategori' : kategori,
'deskripsi' : deskripsiArtikel,
'image' : null
},
dataType: "json",
url: "update_list",
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf_token']").attr('content'));
},
success: function(result){
if(result){
window.location.href = "kelola";
}
},
error : function(jqXhr) {
var errors = jqXhr.responseJSON;
//console.log(jqXhr);
errorsHtml = "<div class='alert alert-warning text-center' role='alert'>";
$.each( errors , function( key, value ) {
errorsHtml += value[0] ;
//console.log(value[0]);
});
errorsHtml += "</div>";
$('.alerts').html("<div>gila lu</div>");
$('.alerts').append(errorsHtml).fadeIn(200).fadeToggle(10000).fadeOut(50);
}
}, "json");
}else{
var ajax = function(imageData){
requestUploadArtikel(judulArtikel, isiArtikel, kategori, deskripsiArtikel, imageData);
}
imageupload($('#inputpicture').get(0), ajax);
}
});
function requestUploadArtikel(judul, isi, kategori, deskripsi, imageData){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN':$('meta[name="csrf_token"]').attr('content')
}
})
$.ajax({
type:"POST",
data: {
'id' : id,
'judul' : judul,
'isi' : isi,
'kategori' : kategori,
'deskripsi' : deskripsi,
'image' : imageData
},
dataType: "json",
url: "update_artikel",
success: function(result){
if(result){
window.location.href = "kelola";
}
},
error : function(jqXhr) {
var errors = jqXhr.responseJSON;
//console.log(jqXhr);
errorsHtml = "<div class='alert alert-warning text-center' role='alert'>";
$.each( errors , function( key, value ) {
errorsHtml += value[0] ;
//console.log(value[0]);
});
errorsHtml += "</div>";
$('.alerts').html("<div>gila lu</div>");
$('.alerts').append(errorsHtml).fadeIn(200).fadeToggle(10000).fadeOut(50);
}
}, "json");
}
function imageupload(element, ajax){
console.log('testimageupload');
var elementId = element.id;
if(element.files && element.files[0]){
var file = element.files[0];
var validFileType = ".jpg, .png, .bmp";
var extension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
$("#"+elementId+"-show").attr('src', "");
console.log(extension);
//validatefile
if(validFileType.toLowerCase().indexOf(extension)<0){
$("#"+elementId+"-alert").show();
$("#"+elementId+"-show")
.attr('style', '')
.css('height','auto')
return;
}
$("#"+elementId+"-alert").hide();
//showfile
var reader = new FileReader();
reader.onload = function(e){
ajax(e.target.result);
}
if (reader.readAsDataURL) {reader.readAsDataURL(element.files[0]);}
else if(reader.readAsDataurl) {reader.readAsDataurl(element.files[0]);}
else if(reader.readAsDataUrl) {reader.readAsDataUrl(element.files[0]);}
}
else{
console.log('else');
$(elementId+"-show").attr('src',"");
}
}
});
here's my edit.blade.php
#extends('layout.layout')
#section('css')
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.css" rel="stylesheet">
#stop
#section('script')
<script type="text/javascript" src="{{ asset('js/artikel/edit.js') }}"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.js"></script>
#stop
#section('content')
<!-- Main Content -->
<div class="container">
<div class="row">
<h1 class="text-center edittengah">Edit Artikel</h1>
<div class="alerts"></div>
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
#foreach ($artikel as $a_artikel)
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Judul Artikel</label>
<input type="text" class="form-control" placeholder="Judul Artikel" id="judul" required data-validation-required-message="Harap tuliskan judul artikel." value="{{$a_artikel->judul}}">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label for="inputpicture">Ganti Foto Artikel</label>
<input type="file" name="picture" class="" id="inputpicture">
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Deskripsi Artikel</label>
<textarea name="deskripsi" id="deskripsi" cols="70" rows="5" placeholder="Deskripsi Artikel">{{ $a_artikel->deskripsi }}</textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Isi</label>
<div id="isi_artikel">{!! $a_artikel->content !!}</div>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label>Jenis Artikel</label>
<?PHP if($a_artikel->kategori == "umum"){?>
<label><input class="CBumum" type="radio" name="etype" value="umum" checked="true"> Umum </label>
<label><input class="CBsh" type="radio" name="etype" value="selfhelp"> Self Help </label>
<label><input class="CBact" type="radio" name="etype" value="activites"> Activities </label>
<?PHP }
elseif($a_artikel->kategori == "selfhelp"){
?>
<label><input class="CBumum" type="radio" name="etype" value="umum" > Umum </label>
<label><input class="CBsh" type="radio" name="etype" value="selfhelp" checked="true"> Self Help </label>
<label><input class="CBact" type="radio" name="etype" value="activites"> Activities </label>
<?php }
else{
?>
<label><input class="CBumum" type="radio" name="etype" value="umum" > Umum </label>
<label><input class="CBsh" type="radio" name="etype" value="selfhelp"> Self Help </label>
<label><input class="CBact" type="radio" name="etype" value="activites" checked="true"> Activities </label>
<?php }?>
</div>
</div>
<hr>
<br>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<input class="btn btn-success" id="btn_submit" type="submit">
#endforeach
</div>
</div>
</div>
</div>
</div>
#stop
Your help is needed. Thanks in advance.
OKay my bad knowledge in routes,,
my ajax url update :
"url" : "/update_list"
it must should be
"url" : window.location + "/update_list"
and my controller from :
Route::post('/update_list', 'Controller#update_post');
to
Route::post('kelola/list/{id}/update_list', 'Controller#update_post');
'kelola/list/{id}/update_list' refer to my baseUrl before ajax process URL

How to get sql data in html form fields using Ajax JQuery , PHP and PL SQL

I am learning Ajax JQuery , PHP and PL SQL.I have designed the html form given below:
Whenever,user enter a Loan ID and press Edit button, then i want to copy the query result outputs for particular Loan ID inside corresponding html from fields if that data exist,other wise print Not Exist in them.I don't know how ajax take data and distinguish them for separate form fields
here is my front end code:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body >
<div class="container" >
<div class="panel-group">
<div class="panel panel-primary" >
<div class="panel-heading" >
<h3 class="panel-title" style="text-align: center;">Record Loan Type Information</h3>
</div>
<div class="panel-body">
<form class="form-horizontal" >
<div class="form-group">
<label class="control-label col-sm-3" for="acode">Loan ID:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="textloanid" name="loanid" placeholder="Enter Loan ID">
<span id="errmsg1" class="errmsg"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" style="text-align:right;" >Loan Name:</label>
<div class="col-sm-5">
<input type="text" id="textloan_name" name="loan_name" class="form-control" placeholder="Enter Loan Name" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="dcode">Description:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="textdescription" name="description" placeholder="Enter Loan Description">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" style="text-align:right;">Amount:</label>
<div class="col-sm-5">
<input type="text" id="textamount" name="amount" class="form-control" placeholder="Enter Amount" >
<span id="errmsg2" class="errmsg"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" style="text-align:right;" >Sanction Date:</label>
<div class="col-sm-5">
<div class="input-group date">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
<input type="text" id='textdatetimepicker1' name="textdatetimepicker1" class="form-control" placeholder="DD/MM/YYYY">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" style="text-align:right;">Interest Rate:</label>
<div class="col-sm-5">
<input type="text" id="textrate" name="rate" class="form-control" placeholder="Enter Rate" >
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" id="btnSubmit" class="btn btn-primary">Save</button>
<button type="submit" name="editbtn" class="btn btn-success editbtn">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
<button type="button" class="btn btn-info">Exit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var values = $("form").serialize();
$("form").on("submit", '.editbtn', function(event) {
event.preventDefault();
var values = $( this ).serialize();
$('#serialize').text(values);
$.ajax({
url: "loan_type_info.php",
type: "post",
async:true,
data: values,
dataType: 'html',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(data) {
$('#result').html((data)? data:"Empty!");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
</script>
</body>
</html>
I think,somehow i need to store query output row in php and send them to ajax.so that ajax can output them in their form fields.
Here is my back end php code:
<?php
$loanid = (isset($_POST['loanid'])) ? $_POST['loanid'] : "not";
$loan_name = (isset($_POST['loan_name'])) ? $_POST['loan_name'] : "not";
$description = (isset($_POST['description'])) ? $_POST['description'] : "not";
$amount = (isset($_POST['amount'])) ? $_POST['amount'] : "not";
$datestring = (isset($_POST['textdatetimepicker1'])) ? $_POST['textdatetimepicker1'] : "not";
$rate = (isset($_POST['rate'])) ? $_POST['rate'] : "not";
echo $loanid;
echo $loan_name;
echo $description;
echo $amount;
echo $rate;
$date_arr = explode('/', $datestring);
$date = date("Y/m/d", strtotime($date_arr[2] . $date_arr[1] . $date_arr[0]));
echo $datestring;
echo var_dump($date);
$conn = oci_connect('usr', 'pass', 'test');
if (!$conn) {
trigger_error("Could not connect to database", E_USER_ERROR);
} else {
echo "Connection established ";
}
$stid = oci_parse($conn, " begin
:result := PKG_PAYROLL.find_loan_type(
'<loan_type>
<loan_id>$loanid</loan_id>
</loan_type>'
);
end;");
oci_bind_by_name($stid, ':result', $ru, 500);
$output = oci_execute($stid);
echo $ru;
?>
In PL SQL, i need to run query and get the data back to php.
Here is my PL/SQL Code:
FUNCTION find_loan_type(loan_type_data NVARCHAR2 ) RETURN clob IS ret clob;
xmlData XMLType;
v_code NUMBER;
v_errm VARCHAR2(100);
loan_id NUMBER(10);
BEGIN
xmlData:=XMLType(loan_type_data);
loan_id := xmlData.extract('/loan_type/loan_id/text()').getstringval();
select * from TBL_LOAN_TYPE where LNTYPE_ID=loan_id;
ret:=to_char(sql%rowcount);
COMMIT;
RETURN '<result><status affectedRow='||ret||'>success</status></result>';
EXCEPTION
WHEN OTHERS THEN
v_code := SQLCODE;
v_errm := SUBSTR(SQLERRM, 1, 100);
DBMS_OUTPUT.PUT_LINE (v_code || ' ' || v_errm);
RETURN '<result><status>Error</status> <error_message>'|| 'Error Message:' || v_errm ||'</error_message> </result>';
END find_loan_type;
please help me on that.i realized that, if i can understand to exchanging data from front end to back end via ajax, php and PL SQL then, i can solve this.if you have such kind experience, then please share your knowledge.please let me know for further information.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