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
Related
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
I want save SVG data in a database. I will try with a simple submit and also with AJAX. I also set content-type="image/svg-xml"
I will check data with print_r($_POST); SVG Content displayed here when I will try to store on db svg value as null.
<?php echo form_open('admin/shape/add',array('class' => 'form-horizontal', 'name' => 'catfrm', 'id' => 'catfrm')); ?>
<div class="box-body">
<div class="col-md-8">
<div class="form-group">
<label class="col-sm-2 control-label">Title <span class="error">*</span></label>
<div class="col-sm-10">
<input type="text" name="title" value="" id="title" class="form-control" />
</div>
</div>
<!-- form-group -->
</div>
<div class="col-md-8">
<div class="form-group">
<label class="col-sm-2 control-label">Content <span class="error">*</span></label>
<div class="col-sm-4" id="shape_priview" height="30px">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0,0,100,100"><polygon points="50 0, 0 100, 100 100"></polygon></svg>
</div>
<div class="col-sm-6">
<textarea name="content" id="shape_content" class="form-control"><svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0,0,100,100"><polygon points="50 0, 0 100, 100 100"></polygon></svg></textarea>
</div>
</div>
<!-- form-group -->
</div>
</div>
<div class="box-footer" align="center">
<button type="submit" class="btn btn-success">Add</button>
<button type="reset" class="btn btn-dark" onclick="window.location.href = '<?php echo site_url('admin/shape'); ?>'">Cancel</button>
</div>
<?php echo form_close();?>
$(document).ready(function() {
$("#shape_content").on("change keyup paste", function() {
$("#shape_priview").text('');
var shape_content = $("#shape_content").val();
$("#shape_priview").html(shape_content);
});
$("#catfrm").validate({
rules: {
title: {
required: true,
}
},
messages: {
title: {
required: "Title is required",
}
},
submitHandler: function(form) {
$("#catfrm").submit(function(event) {
event.preventDefault();
var content = $("#shape_content").val();
var title = $("#title").val();
alert(content);
$.ajax({
type: "post",
url: "<?php echo site_url('admin/shape/add'); ?>",
data: {
"title": title,
"content": content
},
contentType: "application/json",
success: function(responseData, textStatus, jqXHR) {
alert(responseData);
alert("data saved")
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
});
}
});
});
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
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();
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