I have created a form in CodeIgniter for uploading an image.
The View file:
<form method="POST" action="<?php echo base_url().'promotions/add_item' ?>" enctype='multipart/form-data' class="form-horizontal" id="addItem">
<div class="form-group">
<label class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Title">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Image</label>
<div class="col-sm-9">
<input type="file" name="pro_image">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" name="description" placeholder="Description"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
</div>
</div>
</form>
The Ajax code:
<script>
$(function(){
$( "#addItem" ).submit(function( event ) {
var url = $(this).attr('action');
$.ajax({
url: url,
data: $("#addItem").serialize(),
type: $(this).attr('method')
}).done(function(data) {
$('#ret').html(data);
// window.location.reload();
$('#addItem')[0].reset();
});
event.preventDefault();
});
});
</script>
The Controller file:
<?php
$this->form_validation->set_rules('title','Title','required');
$this->form_validation->set_rules('description','Description','required');
var_dump($_FILES['pro_image']);
if ($this->form_validation->run() == FALSE) {
echo '<div class="alert alert-dismissable alert-danger"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><small>'. validation_errors().'</small></div>';
} else {
if ($_FILES['pro_image']['size'] > 0) {
$this->upload->initialize(array(
"upload_path" => './uploads/',
"overwrite" => FALSE,
"encrypt_name" => TRUE,
"remove_spaces" => TRUE,
"allowed_types" => "gif|jpg|png|jpeg",
));
if (!$this->upload->do_upload('pro_image')) {
echo 'Error :'. $this->upload->display_errors();
}
$data = $this->upload->data();
$img = $data['file_name'];
}
$title = $this->input->post('title');
$description = $this->input->post('description');
$this->promotions_model->add_item($title, $description,'uploads/'.$img);
}
Whenever I attempt to upload an image it always comes as null, but if I comment out the event.preventDefault(); line then upload an image, then it works fine. However, then the other functionality like validation and return messages fail to work properly.
Can any one please tell me what is issue with event.preventDefault()?
<script>
$(function(){
$( "#addItem" ).submit(function( event ) {
event.preventDefault();
var url = $(this).attr('action');
var data= new FormData($("#addItem")[0]);
$.ajax({
url: url,
contentType:false,
cache:false,
processData:false,
data: data,
type: 'POST' // POST/GET
success:function(data) {
$('#ret').html(data);
$('#addItem')[0].reset();
}
});
});
});
Add event.preventDefault(); in the begining sumbit listner
Related
when i want to input textarea with CKeditor , the string is Null , but when i delete class="CKeditor" in textarea the string successfully filled.
i have check in controller and database but it does not matter
My Controller
function AddNews(){
$data = array(
'title_news' => $this->input->post('title_news'),
'text' => $this->input->post('text_news'),
'date' => $this->input->post('date'),
);
$insert = $this->m_news->save($data);
echo json_encode(array("status" => TRUE));
}
My View
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id_news"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title News </label>
<div class="col-md-9">
<input name="title_news" placeholder="Title Name" class="form-control" type="text"><span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Title News </label>
<div class="col-md-9">
<textarea class="ckeditor" name="text_news" rows="3" placeholder="Enter text . . . "></textarea><span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date</label>
<div class="col-md-9">
<div class="input-group">
<input class="form-control date-picker" name="date" type="text" data-date-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" /><span class="input-group-addon"><i class="fa fa-calendar bigger-110"></i></span>
</div>
</div>
</div>
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
</div>
</form>
My Ajax Input
function save()
{
var formData = new FormData($('#form')[0]);
$.ajax({
url : "<?php echo base_url('admin-spot/news/AddNews')?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
redirect: true,
success: function(data){
if(data.status){
$('#modal_form').modal('hide');
}
else
{}
error: function (jqXHR, textStatus, errorThrown){
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
My Model
function Save($data)
{
$sql = $this->db->insert($this->table, $data);
return $sql;
}
hello guys,
when I want to input textarea with CKeditor , the string is Null , but when I delete class="CKeditor" in textarea the string successfully filled.
I have check in controller and database but it does not matter
Add this to your script
function save()
{
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
var formData = new FormData($('#form')[0]);
$.ajax({
....
});
}
Error loading file to server and check everything and apparently it's okay please help
enter image description here
View
<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">Modal title</h4>
</div>
<div class="modal-body">
<form id="myForm" action="" method="post" class="form-horizontal" enctype="multipart/form-data">
<input type="hidden" name="txtProdId" value="0">
<div class="form-group">
<label for="category" class="label-control col-md-4">Nombre categoría</label>
<div class="col-md-8">
<select class="form-control col-md-4" for="name" name="txtId" id="categoria">
</select>
</div>
</div>
<div class="form-group">
<label for="subcategory" class="label-control col-md-4">Nombre subcategoría</label>
<div class="col-md-8">
<select class="form-control col-md-4" for="name" name="txtSubId" id="subcategoria">
</select>
</div>
</div>
<div class="form-group">
<label for="codig" class="label-control col-md-4">Codigo</label>
<div class="col-md-8">
<input type="text" name="txtCodigo" class="form-control">
</div>
</div>
<div class="form-group">
<label for="name" class="label-control col-md-4">Nombre Producto</label>
<div class="col-md-8">
<input type="text" name="txtProducto" class="form-control">
</div>
</div>
<div class="form-group">
<label for="description" class="label-control col-md-4">Descripción</label>
<div class="col-md-8">
<textarea class="form-control" name="txtDescripcion"></textarea>
</div>
</div>
<div class="form-group">
<label for="picture" class="label-control col-md-4">Imagen</label>
<div class="col-md-8">
<input type="file" name="txtFoto" id="txtFoto">
</div>
</div>
<div class="form-group">
<label for="cant" class="label-control col-md-4">Cantidad</label>
<label for="catalog" class="label-control col-md-4">Precio catálogo</label>
<label for="ofert" class="label-control col-md-4">Precio oferta</label>
</div>
<div class="input-group">
<div>
<input type="text" name="txtCantidad" class="form-control">
</div>
<span class="input-group-addon">-</span>
<div>
<input type="text" name="txtCatalogo" class="form-control">
</div>
<span class="input-group-addon">-</span>
<div>
<input type="text" name="txtOferta" class="form-control">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="button" id="btnSave" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
Jquery ajax View
$(function(){
showAllProduct();
//Add New
$('#btnAdd').click(function(){
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Registrar Producto');
$('#myForm').attr('action', '<?php echo base_url() ?>producto/addProduct');
});
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var codig = $('input[name=txtCodigo]');
var productName = $('input[name=txtProducto]');
var description = $('textarea[name=txtDescripcion]');
var cant = $('input[name=txtCantidad]');
var catalog = $('input[name=txtCatalogo]');
var ofert = $('input[name=txtOferta]');
var myFile = $("#txtFoto").val();
alert(myFile);
var result = '';
if(codig.val()==''){
codig.parent().parent().addClass('has-error');
}else{
codig.parent().parent().removeClass('has-error');
result +='1';
}
if(productName.val()==''){
productName.parent().parent().addClass('has-error');
}else{
productName.parent().parent().removeClass('has-error');
result +='2';
}
if(description.val()==''){
description.parent().parent().addClass('has-error');
}else{
description.parent().parent().removeClass('has-error');
result +='3';
}
if(cant.val()==''){
cant.parent().parent().addClass('has-error');
}else{
cant.parent().parent().removeClass('has-error');
result +='4';
}
if(catalog.val()==''){
catalog.parent().parent().addClass('has-error');
}else{
catalog.parent().parent().removeClass('has-error');
result +='5';
}
if(ofert.val()==''){
ofert.parent().parent().addClass('has-error');
}else{
ofert.parent().parent().removeClass('has-error');
result +='6';
}
//if()
if(result=='123456'){
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'añadido';
}else if(response.type=='update'){
var type ='actualizado';
}
$('.alert-success').html('Producto '+type+' con éxtito').fadeIn().delay(4000).fadeOut('slow');
showAllProduct();
}else{
alert('Error');
}
},
error: function(){
alert('No se puede añadir el dato');
}
});
}
});
});
Controller: The file 'txtFoto' does not arrive is as if it had been sent from the form
public function addProduct(){
$pathArchivo = $this->filePath();
$result = $this->m->addProduct($pathArchivo);
$msg['success'] = false;
$msg['type'] = 'add';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
public function filePath(){
$archivo=$_FILES['txtFoto'];
$config['upload_path'] = realpath(APPPATH.'../image/product/');
//$config['file_name'] = "nombre_archivo";
$config['allowed_types'] = "gif|jpg|jpeg|png";
$config['max_size'] = "50000";
$config['max_width'] = "2000";
$config['max_height'] = "2000";
$this->load->library('upload', $config);
$res = '';
if ( ! $this->upload->do_upload($archivo)) {
$error = array('error' => $this->upload->display_errors());
$res = 'hola no funciona';
print_r($error);
}else {
$file_data = $this->upload->data();
$file_path = './image/product/'.$file_data['file_name'];
$res = $file_path;
//print_r($data);
}
return $res;
}
Model
public function addProduct($path){
$field = array(
'sub_id'=>$this->input->post('txtSubId'),
'pr_codigo'=>$this->input->post('txtCodigo'),
'pr_nombre'=>$this->input->post('txtProducto'),
'pr_descripcion'=>$this->input->post('txtDescripcion'),
'pr_cantidad_stock'=>$this->input->post('txtCantidad'),
'pr_precio_catalogo'=>$this->input->post('txtCatalogo'),
'pr_precio_oferta'=>$this->input->post('txtOferta'),
'pr_foto'=>$path
);
$this->db->insert('producto', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
Your method is correct if you are trying to send a TEXT file.
Before you continue doing it with AJAX ,
Lets try and send the file normally
and you would want to receive it like this
$this->upload->do_upload('txtFoto');
I am just curious , If you are using ci's upload handler , why do you take it from PHP's $_FILE?
$_FILES['txtFoto']
Can you share any var_dump from $_FILES?
EDIT
You can do it via AJAX using FormData
var formData = new FormData($('#myForm'))
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
success: function(response){
//handle success
},
error: function(){
//handle error
alert('No se puede añadir el dato');
}
});
On the Controller ,
Initialize your upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
And make sure that the directory you want to upload your image is writable
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
After posting data I can't see the success message in safari browser because page is refreshing after submitting the data. Other browsers shows the success message they are not refreshing. Please find the below code and help me to find out the issue?
HTML
<form action="" method="post" id="form-add-vehicleDetails">
<ol style="visibility:hidden;"></ol>
<div id="successvehicleadded"></div>
<div class="addvehicledetailsform">
<div id="validatevehicledetails"></div>
<div class="form-group form-group-default required">
<label for="Producer">Producer</label>
<input type="text" name="producer" id="producer" class="form-control" maxlength="100" autocomplete = "off" >
</div>
<div class="form-group form-group-default required">
<label for="Model">Model</label>
<input type="text" name="model" id="model" class="form-control" maxlength="100" autocomplete = "off" >
</div>
<div class="form-group form-group-default required">
<label for="Motor">Motor</label>
<input type="text" name="motor" id="motor" class="form-control" maxlength="100" autocomplete = "off" >
</div>
<div class="form-group form-group-default required">
<label for="LicensePlate">License Plate</label>
<input type="text" name="licenseplate" id="licenseplate" class="form-control" maxlength="20" autocomplete = "off" >
</div>
<div class="form-group form-group-default required">
<label for="Freetext">Freetext</label>
<textarea class="form-control" rows="9" id="freetext" name="freetext"></textarea>
</div>
<div class="modal-footer">
<input type="hidden" name="_token" value="{!! csrf_token() !!}">
<button class="btn btn-primary btn-cons m-b-10" type="button" id="addvehicle">Add Vehicle Details</button>
</input>
</div>
</div>
</form>
js
$(document).ready(function(){
$('[data-toggle="modal"]').click(function() {
var id = $(this).attr('data-id');
$("#addvehicle").click(function(e){
e.preventDefault();
var producer = $('#producer').val();
var model = $('#model').val();
var motor = $('#motor').val();
var licenseplate = $('#licenseplate').val();
var freetext = $('textarea#freetext').val();
var token = $('input[name=_token]').val();
var addvehicle = $('#addvehicle').val();
var dataString = 'producer='+producer+'&model='+model+'&motor='+motor+'&licenseplate='+licenseplate+'&freetext='+freetext+'&token='+token+'&addvehicle='+addvehicle+'&id='+id;
$.ajax({
type: "post",
url: "{!! URL::to('socialaddvehicle') !!}",
data: dataString,
success: function(data) {
//alert(data);
//$('.addvehicledetailsform').fadeOut('slow'); //hiding form
var successContent = '<div class="alert alert alert-success" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span></button><strong>Well done!</strong> Vehicle added successfully.</div>';
$('#successvehicleadded').html(successContent);
},
error: function(data) {
if( data.status === 422 ) {
//process validation errors here.
var errors = data.responseJSON;
errorsHtml = '<div class="alert alert-danger"><ul>';
$.each( errors , function( key, value ) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul></div>';
$( '#validatevehicledetails' ).html( errorsHtml );
}
}
});
return false;
});
});
});
Remove the action attribute and add onsubmit="return false;" to your form.
This should fix Opera trying to send the form.
This should do the trick.
$('#form-add-vehicleDetails').on('submit', function(e){
return false;
});
This do two things in to the submit event, fired after send the form.
Cancel the default event. e.prventDefault();
And stops the propagation prevent the event from bubbling up. e.stopPropagation()
As karim79 explains in his answer.
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