Here i want save to database, the value 'isi' from textarea, when i running the function, always get null value from textarea, what i do for fix that ?
thanks.
Here script in view :
<div class="tab-pane active" id="tab_1">
<div class="box-body">
<textarea class="form-control" rows="3" placeholder="Apa yang Anda pikirkan ?">{!! Input::old('quoteinput') !!}</textarea>
</div>
<div class="box-footer">
<a href="{!! URL::to('/timeline/quote') !!}">
<button type="submit" class="btn btn-info pull-right">Posting</button>
</a>
</div>
</div>
Here script from controller :
public function postQuote()
{
$Qdata = new QuotesModel;
$Qdata -> kode_user = Auth::user()->kode_user;
$Qdata -> kode_quote = 'Q'.strtotime(Carbon\Carbon::now()).rand(100,999);
$Qdata -> isi = Input::get('quoteinput');
$kategori = 'quote';
if($Qdata->save())
{
$this->postToTimeline($Qdata->kode_quote , $kategori);
}
Session::flash('message', 'Berhasil memposting !');
return redirect()->back();
}
Here script in route:
Route::get('/timeline/quote', 'ClientTimeLineContr#postQuote' );
You can use jquery to get textarea value without form. And to save it to database use AJAX.
HTML
<textarea name="quoteinput" class="form-control mytextarea" rows="3" placeholder="Apa yang Anda pikirkan ?">{!! Input::old('quoteinput') !!}</textarea>
<button type="submit" class="btn btn-info pull-right">Posting</button>
Jquery and ajax:
$(document).on('click','button',function(e)
{
e.preventDefault();
var text = $('textarea.mytextarea').val(); //this is the value of textarea
$.ajax({
type:"POST",
url: "{{url('/timeline/quote')}}",
data: {
"_token": "{{ csrf_token() }}",
"text": text
},
success: function (data) {
var res = $.parseJSON(data);
if(res == true)
{
alert('saved');
}
}
});
});
Controller
public function postQuote(Request $request)
{
if($request->ajax())
{
$text=$request->text;
//save this textarea value to database
echo json_encode(TRUE);die;
}
You can't get value without creating form in html, wether you do it with form::open or by <form> tag. You also have to give the name to the textarea.
<div class="tab-pane active" id="tab_1">
<dorm method="GET" action="{!! URL::to('/timeline/quote') !!}">
<div class="box-body">
<textarea name="quoteinput" class="form-control" rows="3" placeholder="Apa yang Anda pikirkan ?">{!! Input::old('quoteinput') !!}</textarea>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right">Posting</button>
</div>
</form>
</div>
Related
Here I am trying to make a form which enables admin to add a new company , i need to implement the form validation and after that insert data to table (company_details),here is what i have done, using codeigniter and ajax, I am not sure if there is other simple ways to do this process without using ajax , so if there is i would appreciate you help me. here is my code but now when i press create button notting actually happens, and i get
"error :Failed to load resource: the server responded with a status of 500 (Internal Server Error). company:1"
Company.php Controller
<?php
class Company extends CI_Controller
{
function __construct()
{
parent::__construct();
if(!$this->session->userdata('admin'))
redirect('admin');
$this->load->model('company_model');
}
function index()
{
$data['company'] = $this->company_model->getCompanyDetails();
$this->load->view('admin/company', $data);
}
function validation()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('Cname' , 'Company Name' , 'required');
$this->form_validation->set_rules('shname' , 'Short Name' , 'required');
$this->form_validation->set_rules('regNo' , 'Registration No' , 'required|valid_regNo');
if($this->form_validation->run())
{
$this->company_model->create();
$array = array(
'succsee' => '<div class="alert alert success">Your Company Added Sucessfully</div>'
);
redirect('admin/company/');
}
else
{
$array = array(
'error' => true,
'Cname_error' => form_error('Cname'),
'shname_error' => form_error('shname'),
'regNo_error' => form_error('regNo'),
);
}
echo json_encode($array);
}
}
company.php view
<div class="companyAdd" style="display: none;">
<h2 class="heading">Add Company</h2>
<span action="<?php echo site_url('admin/staff/validate');?>" id="success_message"></span>
<form method="post" id="AddCompanyForm">
<div class="row">
<div class="form-group col-md-4">
<label for="email">Company Name</label>
<input type="text" class="form-control" id="Cname" placeholder="Name" name="Cname">
<span id="Cname_error" class="text-danger"></span>
</div>
<div class="form-group col-md-4">
<label for="pwd">Short Name</label>
<input type="text" class="form-control" id="shname" placeholder="Short Name" name="shname">
<span id="shname_error" class="text-danger"></span>
</div>
<div class="form-group col-md-4">
<label for="pwd">Registration No</label>
<input type="text" class="form-control" id="regNo" placeholder="01234567" name="regNo">
<span id="regNo_error" class="text-danger"></span>
</div>
<div class="col-md-12">
<div class="btn-section float-right">
<button class="btn btn-outline-primary" type="submit"><i class="fa fa-plus-circle" aria-hidden="true" id="Ccreat"></i> Create</button>
<button class="btn btn-danger float-right" id="cancelCompany" type="button" onClick="window.location.href=admin/company"><i class="fa fa-plus-circle" aria-hidden="true"></i> Cancel</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
This is my script tag in company.php view
<script>
$(document).ready(function(){
$('#AddCompanyForm').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"<?php echo site_base();?>admin/company/validation",
method:"POST",
data:$(this).serialize(),
dataType:"json",
beforeSend:function(){
$('#Ccreat').attr('disabled', 'disabled');
},
success:function(data)
{
if(data.error)
{
if(data.Cname_error != '')
{
$('#Cname_error').html(data.Cname_error);
}
else
{
$('#Cname_error').html('');
}
if(data.shname_error != '')
{
$('#shname_error').html(data.shname_error);
}
else
{
$('#shname_error').html('');
}
if(data.regNo_error != '')
{
$('#regNo_error').html(data.regNo_error);
}
else
{
$('#regNo_error').html('');
}
}
if (data.success)
{
$('#success_message').html(data.success);
$('#Cname_error').html('');
$('#shname_error').html('');
$('#regNo_error').html('');
$('#AddCompanyForm')[0].reset();
}
$('#Ccreat').attr('disabled',false);
}
})
});
});
</script>
And here is Company_model.php
<?php
class Company_model extends CI_Model
{
//table name: company_details
function getCompanyDetails()
{
return $this->db->get('company_details')->result();
}
function create()
{
$arr['company_name'] = $this->input->post('Cname');
$arr['short_name'] = $this->input->post('shname');
$arr['registration_no'] = $this->input->post('regNo');
$this->db->insert('company_details',$arr);
}
}
This is my first time working with codeigniter and ajax , i would appreciate if someone can help me to solve it.
I have a CRUD with ajax working , but i want to implement a file upload to it.
Everything works fine except the image upload , the image is the only thing that is not saving on database and folder , all the other data are saving.
This is my CRUD Controller(just the add part) where I've implemented the upload code (dados)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class dados extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('dados_model');
$this->load->database();
}
public function index()
{
$data['dados']=$this->dados_model->get_all_dados();
$this->load->view('dados_view',$data);
}
public function dados_add()
{
$config = array(
'upload_path' => "./assets/uploads",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000",
);
$this->load->library('upload',$config);
$this->upload->do_upload('userfile');
$data2=array('upload_data' => $this->upload->data());
$data = array(
'Name' => $this->input->post('Name'),
'City' => $this->input->post('City'),
'address' => $this->input->post('address'),
'lastname' => $this->input->post('lastname'),
'Image' =>$data2['upload_data']['file_name']
);
$this->dados_model->dados_add($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_edit($id)
{
$data = $this->dados_model->get_by_id($id);
echo json_encode($data);
}
And this is my Model, I use it to store the data on the database(dados_model)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class dados_model extends CI_Model
{
var $table = 'dados';
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function get_all_dados()
{
$this->db->from('dados');
$query=$this->db->get();
return $query->result();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('ID',$id);
$query = $this->db->get();
return $query->row();
}
public function dados_add($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
This is my Ajax code to save
<script type="text/javascript">
$(document).ready( function () {
$('#table_id').DataTable();
} );
var save_method; //for save method string
var table;
function add_person()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
//$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal
title
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('dados/dados_add')?>";
}
else
{
url = "<?php echo site_url('dados/dados_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data:$('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
and this is my Modal Form to save
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">dados Form</h3>
</div>
<div class="modal-body form">
<form action="#" method="post" enctype="multipart/form-data" id="form"
class="form-horizontal">
<input type="hidden" value="" name="ID"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Name</label>
<div class="col-md-9">
<input name="Name" placeholder="" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input name="City" placeholder="City" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address</label>
<div class="col-md-9">
<input name="Address" placeholder=""
class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input name="lastname" placeholder="" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<input type="file" name="userfile" placeholder="" class="form-control">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger" data-
dismiss="modal">Cancel</button>
<input type ="submit" name="submit" value="Salvar" id="btnSave "
onclick="save()" class="btn btn-primary" />
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->
</body>
</html>
First, try adding a '/' to the end of 'upload_path' => "./assets/uploads" in your code. This way you have a complete path for the image to go to.
Also, just so your aware, uploading an image like this will save the image on your server in the path provided. This means you need to store the file name in the database.So Make sure that 'Image' =>$data2['upload_data']['file_name'] actually has the correct file name so that when you query that file name from the db you can then find it at ./assets/uploads/filename on your server.
Additionally,
What do you get if you var_dump($data2['upload_data']['file_name'])?
What do you get if you var_dump($this->upload->display_errors()) after calling do_upload?
after searching some ajax codes, this is what worked for me
I changed my ajax function save to this
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('dados/dados_add')?>";
}
else
{
url = "<?php echo site_url('dados/dados_update')?>";
}
$('#form').submit(function(e)
{
$.ajax({
url : url,
type: "POST",
data: new FormData(this),
dataType: "JSON",
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
});
}
I downloaded a web application and i found out that it is created using Smarty Template Engine. I want to add an avatar field when creating new company so i added enctype="multipart/form-data" and <input type="file" name="avatar"> to the existing <form> and i also added avatar to my companies table in my database. Here is the HTML code:
<form class="form-horizontal" id="ib_modal_form" enctype="multipart/form-data">
<div class="form-group"><label class="col-lg-4 control-label" for="company_name">{$_L['Company Name']}<small class="red">*</small></label>
<div class="col-lg-8"><input type="text" id="company_name" name="company_name" class="form-control" value="{$val['company_name']}"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="avatar">{$_L['Avatar']}</label>
<div class="col-lg-8"><input type="file" name="avatar"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="email">{$_L['Email']}</label>
<div class="col-lg-8"><input type="text" id="email" name="email" class="form-control" value="{$val['email']}"> </div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-danger">{$_L['Cancel']}</button>
<button class="btn btn-primary modal_submit" type="submit" id="modal_submit"><i class="fa fa-check"></i> {$_L['Save']}</button>
</div>
I found out that the form goes to this javascript code when clicking the Save Button:
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
$.post( _url + "contacts/add_company_post/", $("#ib_modal_form").serialize())
.done(function( data ) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
});
});
Here is the code in the Controller:
case 'add_company_post':
$data = ib_posted_data();
$company = Model::factory('Models_Company')->create();
$company->company_name = $data['company_name'];
$company->url = $data['url'];
$company->email = $data['email'];
$company->phone = $data['phone'];
$company->logo_url = $data['logo_url'];
$company->avatar = $_FILES['avatar']['name'];
$company->save();
break;
The problem is that it does not recognize $_FILES['avatar']['name']; in the Controller Whenever i add a new company, i get a NULL value in my database. I cant seem to solve this problem. Any help would be appreciated. Thanks.
Change
From
$("#ib_modal_form").serialize()
To
new FormData($("#ib_modal_form")[0])
You should use FormData for uploading files using ajax. $(form).serialize() will give you just key and value.
Can you change your ajax call below way
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
var formData = new FormData($("#ib_modal_form")[0]);
$.ajax({
url: _url + "contacts/add_company_post/",
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
},
});
});
I want to validate my form's input with database, so when user type on form's input and contain email already in use or exists it will display an alert and cant submit. I use CodeIgniter framework and jQuery.
I've tried using the code below to check if name exists and this could work. But when I apply it to the other case for email, it doesn't work and display message "The URI you submitted has disallowed characters."
How is the correct way to fix this?
View (kasir_halaman.php) :
<div id="addModal" class="modal fade" role="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Tambah Kasir</h3>
</div>
<div class="modal-body">
<form action="<?php echo site_url('admin/kasir/addpetugas'); ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama</label>
<input type="text" id="nama" name="nama" class="form-control" maxlength="100" required>
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" id="email" name="email" class="form-control" maxlength="150" required>
</div>
<div class="form-group">
<label>Kategori</label>
<select class="form-control" name="kategoripetugas" required>
<option value=""> -- Pilih Kategori -- </option>
<option value="1">Admin</option>
<option value="2">Kasir</option>
</select>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" maxlength="30">
</div>
<div class="form-group">
<label>Ulangi Password</label>
<input type="password" name="confirmpassword" class="form-control" maxlength="30">
</div>
<button type="submit" class="btn btn-primary" style="width:100%;">Tambah</button>
</form>
</div>
</div>
</div>
</div>
Controller (kasir.php) :
public function cekData($table, $field, $data)
{
$match = $this->Crud->read($table, array($field=>$data), null, null);
if($match->num_rows() > 0){
$report = 2;
}else{
$report = 1;
}
echo $report;
}
public function register_email_exists()
{
if (array_key_exists('email',$_POST)) {
if ($this->Crud->email_exists($this->input->post('email')) == TRUE ) {
echo false;
} else {
echo true;
}
}
}
Model (Crud.php) :
function email_exists($email)
{
$this->db->where('email', $email);
$query = $this->db->get('petugas');
if( $query->num_rows() > 0 ){ return TRUE; } else { return FALSE; }
}
jQuery AJAX (petugas.js) :
$(document).ready(function(){
var check1=0; var id;
$("#nama").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'kasir/cekData/petugas/nama/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*nama petugas sudah terpakai");
check1=0;
}
}
});
});
var check2=0;
$("#email").bind("keyup change", function(){
//var email = $(this).val();
$.ajax({
url:'kasir/register_email_exists',
data:{send:true},
success:function(data){
if(data==1){
$("#report2").text("");
check2=1;
}else{
$("#report2").text("*email sudah terpakai");
check2=0;
}
}
});
});
var check4=0;
$("#confirmpassword").bind("keyup change", function(){
var password = $("#password").val();
var confirmpassword = $(this).val();
if (password == confirmpassword){
$("#report4").text("");
check4=1;
}else{
$("#report4").text("*Password tidak sama");
check4=0;
}
});
$("#submit").click(function(event){
if(check1==0){
event.preventDefault();
}
if(check4==0){
event.preventDefault();
}
});
});
Use ajax post method instead and take data at php side from POST request
you can check more about jquery ajax here: http://api.jquery.com/jquery.post/
and about php post here: http://php.net/manual/en/reserved.variables.post.php
//JS
$("#email").bind("keyup change", function(){
var email = $(this).val();
$.ajax({
url:'kasir/register_email_exists',
type: "POST",// <---- ADD this to mention that your ajax is post
data:{ send:true, email:email },// <-- ADD email here as pram to be submitted
success:function(data){
if(data==1){
$("#report2").text("");
check2=1;
}else{
$("#report2").text("*email sudah terpakai");
check2=0;
}
}
});
});
// PHP
// At php side take your data from $_POST
$send = $_POST['send'];
$email = $_POST['email'];
...
I've been working with Ajax to send and upload files, everything worked perfect, I could upload both photos and files with no problem, but now it just don't work for .pdf files.
This is why I got, from my jQuery file:
function uploadImage(){
$('#file').change(function(){
var file = this.files[0]
if(file){
$('.alert.alert-danger').hide();
$('#filename').text(file.name);
$('#filename').show();
$('.cargando').show();
$('.uploaded').hide();
$('#file').hide();
name = file.name;
size = file.size;
type = file.type;
uploadAjax();
}
});
$('#uploadremove').click(function(e){
e.preventDefault();
$('.alert.alert-danger').hide();
$('#file').show();
$('.cargando').hide();
$('#filename').hide();
$('#uploadok').hide();
$('#uploadremove').hide();
$('#file_id').val("0");
$('.fileinput-button').show();
$('.savebtn').toggleClass('disabled');
$('.uploaded').hide();
});
}
function uploadAjax(){
var inputFileImage = document.getElementById("file");
var filelocation = $('#file').val();
var file = inputFileImage.files[0];
var info = new FormData();
var tipo_archivo = $("#file").attr('accept');
var tipo_archivo = type;
info.append('tipo', tipo_archivo); console.log(file);
var url = HTTP+"admin/uploadfile";
$.ajax({
url:url,
type:'POST',
contentType:false,
data: info,//{archivo : file, tipo : tipo_archivo},
processData:false,
cache:false,
success:function(response){
if(response != '' && !($.isNumeric(response)) ){
$('.alert.alert-danger #uploaderror').html(response);
$('.alert.alert-danger').fadeIn(2000);
$('.cargando').hide();
$('#filename').hide();
$('#file').show();
}
else{
$('.cargando').hide();
$('#uploadok').show();
$('#uploadremove').show();
$('#file_id').val(response);
$('.fileinput-button').hide();
$('.savebtn').toggleClass('disabled');
if(tipo_archivo == "image/*"){
console.log(file);
}
}
}
});
}
And this is the HTML form:
<form class="form-horizontal validate" role="form" method="post" action="<?=fk_link().'admin/savecv'?>">
<input name="location" type="hidden" class="location" value="admin/addcv/<?=#$profesor['id']?>" >
<input name="profesor_id" type="hidden" value="<?=#$profesor['id']?>" >
<div class="form_message">
<div class="alert alert-warning">
</div>
</div>
<?
$texto = "Seleccionar Archivo PDF";
if(#$profesor['profesor_cv']){ $texto = "Cambiar Cv";?>
<div class="uploaded">
<a class="btn btn-success fileDownloadPromise" target="_blank" href="<?=fk_link().'uploads/'.#$cv['cv']?>">
<i class="glyphicon glyphicon-cloud-download"></i>
<span>Descargar</span>
</a>
</div>
<?
} else $texto = "Seleccionar Archivo PDF";?>
<span class="btn btn-danger fileinput-button">
<i class="glyphicon glyphicon-cloud-upload"></i>
<span><?=$texto?></span>
<!-- The file input field used as target for the file upload widget -->
<input id="file" type="file" name="fileToUpload" id="filesToUpload">
</span>
<span class="cargando"><img src="<?=fk_theme_url().'/images/loading.gif'?>"></span>
<span id="filename"></span>
<input id="file_id" name="file_id" type="hidden" value="0" >
<span id="uploadok" class="glyphicon glyphicon-ok"></span>
Cambiar
<div class="clearfix" style="height:10px"></div>
<div class="alert alert-danger col-md-3" style="display:none;">
<span class="glyphicon glyphicon-warning-sign"></span>
<span id="uploaderror">error example</span>
</div>
<input class="btn btn-primary savebtn disabled" value="Guardar" type="submit">
</form>
As I said, everything worked fine but now it only works with images.
info.append('tipo', tipo_archivo);
Up there should be:
info.append('tipo', file);