bootstrap modal upload file - php

I'm having a problem to upload a file using bootstrap modal upload file
This is my modal code
<div id="myModalAtiv" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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="alert alert-info" id="myModalLabel"><span class="glyphicon glyphicon-pencil"></span> Edição de Atividades</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="formacoes" enctype="multipart/form-data">
<div class="form-group">
<input type="hidden" name="idformacao" id="idformacao">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Escola:</label>
<input class="form-control" name="escola" id="escola" disabled="true">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Nome:</label>
<input class="form-control" name="nome" id="nome">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Data:</label>
<div class="input-group date" id="datetimePicker">
<input type="text" class="form-control" name="inicio" id="inicio" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</div>
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Horas:</label>
<input class="form-control" name="horas" id="horas">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Local:</label>
<input class="form-control" name="local" id="local">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Destinatários:</label>
<input class="form-control" name="destinatarios" id="destinatarios">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Data Limite:</label>
<div class="input-group date" id="dataLimitePicker">
<input type="text" class="form-control" name="dataLimite" id="dataLimite" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input span3"><i class="icon-file fileupload-exists"></i>
<span class="fileupload-preview"></span></div>
<span class="btn btn-file"><input type="file" name="fileToUpload" id="fileToUpload" /></span>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-info">Atualizar</button>
<button type="button" class="btn btn-default"data-dismiss="modal">Fechar</button>
</div>
</form>
</div>
</div><!-- End of Modal body -->
</div><!-- End of Modal content -->
and this is my ajax function to send the form
<script>
$(document).ready(function () {
$('#datetimePicker').datetimepicker({format: 'YYYY-MM-DD'});
$('#dataLimitePicker').datetimepicker({format: 'YYYY-MM-DD'});
$('#formacoes').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
nome: {
validators: {
notEmpty: {
message: 'Tem de definir alguma formação'
}
}
}
},inicio: {
validators: {
notEmpty: {
message: 'Data inicial obrigatória'
},
date: {
format: 'YYYY-MM-DD',
message: 'Data inicial inválida'
}
}
},
dataLimite: {
validators: {
notEmpty: {
message: 'Data limite obrigatória'
},
date: {
format: 'YYYY-MM-DD',
message: 'Data limite inválida'
}
}
}
}).on('success.form.fv', function (e) {
e.preventDefault();
var $form = $(e.target),
fv = $form.data('formValidation');
$.ajax({
url: 'updates.php',
type: 'POST',
data: $form.serialize(),
success: function (response) {
console.log(response.status);
if (response.status === 'success') {
$("#myModalAtiv").modal('hide');
$('#respostas .modal-title').html('Sucesso');
$('#respostas .modal-body').html('Informação: ' + response.message);
$('#respostas').modal('show');
$('#respostas').on('hidden.bs.modal', function () {
window.location.reload(true);
});
}
}
});
});
});
All seems to be ok, but when i trying to send the from to my function it says
Notice: Undefined index: fileToUpload
This is my php function
$idformacao= filter_input(INPUT_POST, 'idformacao');
if ($idformacao != null) {
echo "aqui";
$userid = filter_input(INPUT_POST, 'userid');
$nome = filter_input(INPUT_POST, 'nome');
$inicio = filter_input(INPUT_POST, 'inicio');
$horas = filter_input(INPUT_POST, 'horas');
$local = filter_input(INPUT_POST, 'local');
$destinatarios = filter_input(INPUT_POST, 'destinatarios');
$dataLimite = filter_input(INPUT_POST, 'dataLimite');
$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/uploads';
$uploadfile = $uploaddir . '/' . basename($_FILES['fileToUpload']['name']);
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
$target_path = "/uploads/" . basename($_FILES['fileToUpload']['name']);
$ret = $ebspma->updateFormacoes($idformacao, $nome, $inicio, $horas, $local, $destinatarios, $dataLimite,$target_path);
}
echo json_encode($ret);
}
And this is the line where i have the error
$uploadfile = $uploaddir . '/' . basename($_FILES['fileToUpload']['name']);

e.preventDefault();
var fileToUpload= $('#fileToUpload')[0].files[0];
var idformacao = $("#idformacao").val();
var formData = new FormData(this);
formData.append('fileToUpload', fileToUpload);
formData.append('idformacao', idformacao);
//use this same format to append other of your fields
$.ajax({
type:'POST',
url: 'updates.php',
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(response){
//You can continue with your response status code here
}
Just hope that this works for you.

Add data-bs-focus="false" in modal first line at the end:
id="myModalAtiv" class="modal fade bs-example-modal-lg" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-bs-focus="false"

Related

Update Data with Bootstrap Modal using CodeIgniter and Ajax

I'm trying to figure it out why I can't get the alert warning or success from the form validation in a modal. all I want at first is to update the data in the database and it work. now I can't see the alert whether it is wrong or correct, the modal close after I submit and how can I transfer the echo json_encode to alert in modal
view: layout view
$('#login_form').on('submit', function( event ){
event.preventDefault();
var Admin_id = $('#Admin_id').val();
var username = $('#username').val();
var email = $('#email').val();
var contact = $('#contact').val();
var hoax = $('#hoax').val();
var confirm = $('#confirm').val();
var date = $('#date').val();
$.ajax({
url: "<?php echo base_url('profile/profile_update'); ?>",
method: "POST",
data: {Admin_id:Admin_id, username:username, email:email,
contact:contact, confirm:confirm, date:date, hoax:hoax},
dataType: "json",
success: function(data){
if (data.result){
$('#result').html('<p class="alert-success"> The inputs are insufficient </p>');
}else{
$('#result').html('<p class="alert-warning"> The profile successfully updated</p>');
}
//return false;
//event.preventDefault();
}
});
return false;
//event.preventDefault();
});
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="profile" id="1" href="#Profile_modal" data-toggle="modal">Profile</a>
<div class="modal" id="Profile_modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg modal-dialog-scrollable" >
<div class="modal-content">
<div class="modal-header bg-secondary">
<h5 class="modal-title text-white">Profile</h5>
<button type="button " class="close" data-dismiss="modal" aria-label="Close">
<span class="text-white" aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" >
<div class="text-center" id="result"> </div>
<div id="data_profile"> </div>
</div>
</div>
</div>
</div>
Controller: profile/profile_update
public function profile_update(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[3]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[13]');
$this->form_validation->set_rules('contact', 'Contact', 'trim|required|min_length[11]');
$this->form_validation->set_rules('hoax', 'Password',
'trim|required|min_length[6]|matches[confirm]');
$this->form_validation->set_rules('confirm', 'ConfirmPassword', 'trim|required|min_length[6]');
if ($this->form_validation->run() == FALSE) {
$data = array('profile_errors' => validation_errors());
echo json_encode(array("result"=>false));
}else{
$this->load->model('admin_model');
$data=$this->profile_model->update_data();
//$data = 'Your Profile Data has been Updated Successfully';
echo json_encode(array("result"=>true));
}
}
profile/get_fetchdata()
public function get_fetchdata(){
$Admin_id = $this->input->post('Admin_id');
if(isset($Admin_id) and !empty($Admin_id)){
$records = $this->profile_model->fetch_data($Admin_id);
$output = '';
foreach ($records->result_array() as $row) {
$attributes = array('id'=>'login_form', 'class'=>'form');
$output = '<div class="text-center" id="result"> </div>';
echo form_open('profile/profile_update', $attributes);
$output = '
<div class="form-group text-left">
<label> Username </label>
<input type="text" id="username" class="form-control" value='. $row["username"] .' placeholder="Enter Username" name="username" maxlength="10" required>
</div>
<div class="form-group text-left">
<label> Email </label>
<input type="Email" id="email" class="form-control" value='. $row["email"] .' placeholder="Enter Email" name="email" maxlength="20" required>
</div>
<div class="form-group text-left">
<label> Phone Number</label>
<input type="number" id="contact" class="form-control" value='.$row["contact"].' placeholder="Enter Phone Number" name="contact" maxlength="11" required>
</div>
<div class="form-group text-left">
<label> Password </label>
<input type="password" id="hoax" class="form-control" value='. $row["hoax"].' placeholder="Enter Password" name="hoax" maxlength="15" required>
</div>
<div class="form-group text-left">
<label> Confirm Password </label>
<input type="password" id="confirm" class="form-control" value='.$row["hoax"].' placeholder="Confirm Password" name="confirm" maxlength="15" required>
</div>
<input type="hidden" id="Admin_id" class="form-control" value='. $row["Admin_id"] .' name="Admin_id">
<input type="hidden" id="date" class="form-control" value='. $row["date_modified"] .' name="date">
<button class="btn btn-primary float-right new_profile" id="1" name="submit" type="submit" >Save</button>
<button class="btn btn-danger mx-2 float-right" data-dismiss="modal" type="button"> Cancel </button>';
echo form_close();
}
echo $output;
}else {
echo "Nothing to show";
}
}
if you use json as dataType, the browser will wait always for a JSON response, so the best thing to do here is the following:
if($this->form_validation->run() == FALSE){
echo json_encode(array("result" => false, "message" => "Failed"));
}else{
echo json_encode(array("result" => true, "message" => "Success!"));
}
and you can check the results on ajax side by using:
$('#login_form').on('submit', function( event ){
event.preventDefault();
var Admin_id = $('#Admin_id').val();
var username = $('#username').val();
var email = $('#email').val();
var contact = $('#contact').val();
var hoax = $('#hoax').val();
var confirm = $('#confirm').val();
var date = $('#date').val();
$.ajax({
url: "<?php echo base_url('profile/profile_update'); ?>",
method: "POST",
data: {Admin_id:Admin_id, username:username, email:email,
contact:contact, confirm:confirm, date:date, hoax:hoax},
dataType: "json",
success: function(data){
if(data.result){
$('#adminId').val("");
$('#username').val("");
$('#email').val("");
$('#contact').val("");
$('#hoax').val("");
$('#confirm').val("");
$('#date').val("");
$('#result').html('<p class="alert-success"> ' + data.message + ' </p>');
}else{
$('#result').html('<p class="alert-warning"> ' + data.message + ' </p>');
}
//return false;
//event.preventDefault();
}
});
return false;
//event.preventDefault();
});

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 show flash message instead of alert box in popup from?

My code displays an alert box in my popup form but I want to display the flash message in my popup form:
My Ajax:
$('#password_change_form').submit(function(e) {
e.preventDefault();
var saveThis = this;
$.ajax({
type: "POST",
url: "/changepassword",
data: $(saveThis).serialize(),
success: function(data) {
$('#password_change_form')[0].reset();
alert(data);
},
});
}),
My Controller:
$current_password = $user->password;
if(md5($request_data['password']) == $current_password) {
$user_id = $user->id;
$obj_user = User::find($user_id);
$obj_user->password = md5($request_data['new_password']);
$obj_user->save();
$success_output = '<div class="alert alert-success">Password changed</div>';
} else {
$errors_output = '<div class="alert alert-danger">Wrong old password</div>';
$error = array(
'error' => $errors_output
);
echo json_encode($error);
}
$success = array(
'success' => $success_output
);
echo json_encode($success);
Here I want to show the success message in my popup form:
<div class="modal fade common_modal" id="change_password" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-lg" role="document">
<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>
<h3>Změna hesla</h3>
</div>
<div class="modal-body">
<form role="form" id="password_change_form"
class="common_form_style popup_form">
<div class="row">
<div class="col-md-8 col-md-offset-2">
{{ csrf_field() }}
<span id="form_output"></span>
<div class="form-group">
<label for="password" style="width:100%">Původní heslo </label>
<input id="password" type="password" class="form-control" name="password">
<span toggle="#password-field" class="fa fa-fw fa-eye field-icon toggle-password"></span>
</div>
<div class="form-group">
<label for="new_password" style="width:100%">NovÄ› heslo</label>
<input id="new_password" type="password" class="form-control" name="new_password">
<span toggle="#password-field" class="fa fa-fw fa-eye field-icon toggle-password"></span>
<span class="help-block" style="color:#737373;font-size:14px;float:right;margin-right: 30px;font-weight: 100 !important;">MinimálnÄ› 8 znaků, jedno velké a malé písmeno a Äíslo</span>
</div>
<div class="form-group">
<label for="heslo znovu">Potvrzení heslo</label>
<input id="password_confirmation" type="password" class="form-control" name="password_confirmation">
<span toggle="#password-field" class="fa fa-fw fa-eye field-icon toggle-password"></span>
</div>
<div class="submit-btn text-center">
<input type="submit"class="btn btn-default chci" value="Uložit" id="submit_form">
</div>
<div style="margin-top:10px;" id="success-messages"></div>
</div>
<div class="col-md-12 pull-right"></div>
</div>
</form>
I Want to display a success message but currently there is alert in my popup form. The alert screen shot:
Please change to this js code.
$(document).ready(function() {
$('#form').submit(function(e) {
e.preventDefault();
var saveThis = $(this);
$.ajax({
type: "POST",
url: "./index.php",
data: $(saveThis).serialize(),
success: function(data) {
var obj = $.parseJSON(data);
// I don't know where you want to show messages.
// In this case, outputting to id="form_output" element.
$('#form_output').html(obj.success);
}
});
});
});

Ajax file upload without formdata

when i try to upload a file, all data send to database but the input file is empty and won't upload the file how can i send file with my
actual ajax submit form ? without dataForm i'm new to ajax and mysql
here's my code:
function getUsers(){
$.ajax({
type: 'POST',
url: 'tpl/add.php',
data: 'action_type=view&'+$("#userForm").serialize(),
success:function(html){
$('#userData').html(html);
}
});
}
function userAction(type,idb){
id = (typeof idb == "undefined")?'':idb;
var statusArr = {add:"ajouter",edit:"mises à jour",delete:"supprimer"};
var userData = '';
if (type == 'add') {
userData = $("#addForm").find('.form').serialize()+'&action_type='+type+'&idb='+idb;
}else if (type == 'edit'){
userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
}else if (type == 'view'){
userData = $("#viewForm").find('.form').serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&idb='+idb;
}
$.ajax({
url: 'tpl/add.php',
cache: false,
data: userData,
type: 'POST',
contentType: false,
processData: false,
success:function(msg){
if(msg == 'ok'){
alert('Le model a été '+statusArr[type]+' avec succès.');
getUsers();
$('.form')[0].reset();
$('#myModal2').modal('hide');
$('#myModal').modal('hide');
}else{
alert('Un probleme à été detecter, veuillez reessayer.');
}
}
});
}
function editUser(idb){
$.ajax({
type: 'POST',
dataType:'JSON',
url: 'tpl/add.php',
data: 'action_type=data&idb='+idb,
success:function(data){
$('#idbEdit').val(data.idb);
$('#modelEdit').val(data.model);
$('#urldemoEdit').val(data.urldemo);
$('#modelfichEdit').val(data.modelfich);
$('#etatEdit').val(data.etat);
$('#editForm').slideDown();
}
});
}
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ajouter un modele</h4>
</div>
<div class="modal-body" id="addForm">
<form class="form form-horizontal" method="post" id="userForm" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-3">Modele HTML</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="model" id="model"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Aperçu</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="urldemo" id="urldemo"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Fichier HTML </label>
<div class="col-sm-9">
<input type="file" name="file" id="file" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Etat</label>
<div class="col-sm-9">
<select name="etat" id="etat" class="form-control">
<option value="0">activé</option>
<option value="1">désactivé</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
Ajouter
<button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
</div>
</form>
</div>
</div>
</div>

form validation code igniter doesn't work

i am a beginner in using form validation in codeigniter, now i am trying to use form validation codeigniter library, why this is not executed? i already loaded the $this->load->library('form_validation'); at the top of my controller. I mean i want the output where it puts error below my input type. Why my error in array('required' => 'Error Message on rule2 for this field_name')); doesnt appear in my view. Only in Response at console
Here is my fullcode:
VIEW:
<div class="modal fade large" id="admin_create_acct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header btn-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Create Account</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" id="frm_create_user">
<div class="form-group">
<label for="userFName" class="control-label col-sm-4">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="userFName" id="userFName" placeholder="First name">
<div class="msg"></div><!-- form-group -->
</div><!-- col-sm-6 -->
</div><!-- form-group -->
<div class="form-group">
<label for="userMName" class="control-label col-sm-4">Middle Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="userMName" id="userMName" placeholder="Middle name">
<div class="msg"></div><!-- form-group -->
</div><!-- col-sm-6 -->
</div><!-- form-group -->
</form><!-- form-horizontal -->
<button type="button" id="btn_reg" onclick="create_User()" class="btn btn-primary">Create Account</button>
i am just trying one input type and some error for validating, now here is my Controller code:
public function reg_user(){
$this->form_validation->set_rules('userFName', 'userFName', 'trim|required',
array('required' => 'Error Message on First name ')
);
$this->form_validation->set_rules('userMName', 'userMName', 'trim|required',
array('required' => 'Error Message on Middle Name')
);
if ($this->form_validation->run() == FALSE) {
$result['type'] = 'error';
$result['message'] = validation_errors();
}else {
$result['type'] = 'success';
$result['message'] = 'Whooos..! Your Succes Message';
}
echo json_encode($result);
}
my ajax from view:
function create_User() {
$.ajax({
url: siteurl+"admin_controls/reg_user",
type: "POST",
data: $("#frm_create_user").serialize(),
dataType: "JSON",
success: function(data) {
alert(" User Successfully Added added! ");
$("#frm_create_user")[0].reset();
}
});
}
Please follow this Method.
Or
If you just copy and paste this code it will definately work, all you need to just change the controller name in the form action
public function reg_user(){
$this->form_validation->set_rules('userFName', 'userFName', 'trim|required',
array('required' => 'Error Message on First name ')
);
$this->form_validation->set_rules('userMName', 'userMName', 'trim|required',
array('required' => 'Error Message on Middle Name')
);
if ($this->form_validation->run() == TRUE) {
$result['status'] = true;
$result['message'] = "Data inserted successfully.";
}else {
$result['status'] = false;
$result['message'] = $this->form_validation->error_array();
}
echo json_encode($result);
}
Now the Ajax Part
In Ajax i am using the FormData function instead of using serialize function. In case if you are going to upload files it will be helpful.
<script type="text/javascript">
$(document).ready(function() {
$("#form_data").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_data"));
$.ajax({
url : $("#form_data").attr('action'),
dataType : 'json',
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
$('.error').html('');
if(resp.status == false) {
$.each(resp.message,function(i,m){
$('.'+i).text(m);
});
}
}
});
});
return false;
});
View Part
<a data-toggle="modal" href='#admin_create_acct' class="list_sort">Select<a>
<div class="modal fade large" id="admin_create_acct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header btn-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Create Account</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" action="<?php echo base_url('Practice/test_user')?>" method="post" id="form_data">
<div class="form-group">
username : <input type="text" class="form-control" name="name">
<span class="error userFName"></span>
</div>
<div class="form-group">
password : <input type="text" class="form-control" name="userMName">
<span class="error userMName"></span>
</div>
<input type="submit" name="submit" value="submit">
</form>
</div>
</div>
</div>
</div>

Categories