I have a form which data is inserting into data base through ajax. Along with when input fields has error then showing error under neath to the every fields.
我有一个表格,数据通过ajax插入数据库。当输入字段有错误时,然后在每个字段的neath下显示错误。
But when i select the image and trying to upload the name of image into database, then nothing goes on, neither image uploading to the upload path nor inserting the name of the image into database.
但是当我选择图像并尝试将图像名称上传到数据库中时,没有任何内容,图像上传到上传路径,也没有将图像名称插入数据库。
In Case of image upload error i can not even display image upload error.
在图像上传错误的情况下,我甚至无法显示图像上传错误。
Controller:- In my Controller as you can see that i have an array named result which has two keys status and message and default status is false.
控制器: - 在我的控制器中你可以看到我有一个名为result的数组,它有两个键状态和消息,默认状态为false。
In the else part a loop is running which has only form error not any type of image error may be this is reason for not showing any error for image.
在else部分中,循环正在运行,其中只有形式错误,而不是任何类型的图像错误,这可能是因为没有显示图像的任何错误。
No Problem if error is not showing But at least file name should be inserting.
没有问题,如果没有显示错误但至少应该插入文件名。
function infoValidation() {
$result = array('status' => false, 'message' => array());
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run('company_registration')) {
$config['upload_path'] = 'assets/uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload',$config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data['upload_data'] = $this->upload->data('file_name');
$image_name = $data['upload_data'];
//$result['message'] = $this->upload->display_errors();
//$result['status'] = false;
}
else
{
$image_name = '';
}
$data = array(
'email' => $this->input->post('email'),
'first_name' => $this->input->post('firstname'),
'last_name' => $this->input->post('lastname'),
'pincode' => $this->input->post('pincode'),
'state' => $this->input->post('state'),
'landmark' => $this->input->post('landmark'),
'address' => $this->input->post('address'),
'state' => $this->input->post('state'),
'image' => $image_name,
'joined_date' => date('Y-m-d H:i:s')
);
$result['status'] = true;
$this->Perfect_mdl->c_insert($data);
}else {
foreach ($_POST as $key => $value) {
$result['message'][$key] = form_error($key);
}
}
echo json_encode($result);
}
Ajax:
$("#form").submit(function(e){
e.preventDefault();
var me = $(this);
$.ajax({
url : me.attr('action'),
dataType : 'json',
type : 'POST',
data : me.serialize(),
success: function(resp) {
console.log(resp);
if (resp.status == true) {
$('#myModal').modal('show');
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
}else {
$('#msg').html('<div class="alert alert-danger"><h5>Please Check Your Details</h5></div>');
$.each(resp.message, function(key, value) {
var element = $("#"+key);
element.closest('.form-group')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
if(element.parent('.input-group').length) {
element.parent().after(value);
} else {
element.after(value);
}
// element.after(value);
});
}
}
});
});
How can i Upload an image into database, If this is not the right way then please Suggest the right way for doing this
如何将图像上传到数据库中,如果这不是正确的方法那么请建议正确的方法
4 个解决方案
#1
7
serialize() method not able to post file data.
serialize()方法无法发布文件数据。
For sending file using ajax use FormData instead of serializing
对于使用ajax发送文件,请使用FormData而不是序列化
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
HTML5引入了FormData,允许开发人员动态构建表单对象,然后通过AJAX发送此表单对象。
View
<form action="Your controller method name" method="post" id="form_img" enctype="multipart/form-data" accept-charset="utf-8">
<div>
username : <input type="text" name="name">
<span class="error name"></span>
</div>
<div>
password : <input type="text" name="password">
<span class="error password"></span>
</div>
<div>
file : <input type="file" name="image">
<span class="error image"></span>
</div>
<input type="submit" name="submit" value="submit">
</form>
Jquery call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").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);
});
}
}
});
});
});
</script>
controller
function test_image() {
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'name', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run() == TRUE) {
if($_FILES['image']['error'] != 0) {
$result['status'] = false;
$result['message'] = array("image"=>"Select image to upload");
} else {
$config['upload_path'] = 'images';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload',$config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data['upload_data'] = $this->upload->data('file_name');
$image_name = $data['upload_data'];
}
else
{
$image_name = '';
}
$data = array(
'name' => $this->input->post('name'),
'password' => $this->input->post('password'),
'image' => $image_name,
'joined_date' => date('Y-m-d H:i:s')
);
$result['status'] = true;
$this->Perfect_mdl->c_insert($data);
$result['message'] = "Data inserted successfully.";
}
}else {
$result['status'] = false;
// $result['message'] = validation_errors();
$result['message'] = $this->form_validation->error_array();
}
echo json_encode($result);
}
Try this flow for upload image using ajax
尝试使用ajax上传图像
#2
3
try this codein view
试试这个代码视图
$('#formElement').submit(function () {
var formData = new
FormData(document.getElementById("formElement"));
formData.append('image-file', $('#image-file')[0].files[0]);
$.ajax({
url: "<?php echo base_url('home/add')?>",
data: formData,
contentType: false,
processData: false,
type: 'POST',
beforeSend: function() {
$('.loder_img').show();
},
success: function ( data ) {
$('.loder_img').hide();
var val = JSON.parse(data);
//you can apply alerts or anything to show validation on
view and in val all mesg of validation yon can see here in console.
console.log(val);
},
error: function (request, status, error) {
$('.loder_img').hide();
alert(request.responseText);
}
});
});
and in your controller
并在你的控制器
public function addPackage()
{
$this->load->library("form_validation");
//left side form
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('txt_desc', 'Remarks', 'required|trim');
$this->form_validation->set_rules('txt_store', 'Store', 'required|trim');
//upto so on according to your values
if( $this->form_validation->run() == false){
$error = array(
"check_1" => form_error('check_1'),
"txt_desc" => form_error('txt_desc'),
"txt_store" => form_error('txt_store'),
"txt_couple_name" => form_error('txt_couple_name'),
"txt_couple_case" => form_error('txt_couple_case'),
"txt_phone" => form_error('txt_phone'),
"txt_date" => form_error('txt_date'),
"txt_location" => form_error('txt_location'),
"txt_address" => form_error('txt_address'),
"txt_email" => form_error('txt_email'),
);
$msg = array('status' => 'invalid', 'msg'
=>$error,'allerror'=>validation_errors());
echo json_encode($msg);
}else{
//insert it into database all file and values
if($_FILES["image-file"]["size"] != 0){
$path= './uploads/image';
$img = "image/".$this->Upload_model->image_upload($path, "", '', '', '',"image-file");
}
$data = array(
"basket" => $this->filter($this->input->post("check_1",true))........
);
//your insert query
}
}
and in your model to upload image and it will return the uploaded image if it is not upload hen it will return false or you can print the display errors and dont forget to change the path of storing image
并在你的模型中上传图像,它将返回上传的图像,如果它没有上传母鸡它将返回false或你可以打印显示错误,不要忘记更改存储图像的路径
model code
public function image_upload($upload_path, $max_width, $max_height, $min_width, $min_height, $filename)
{
$config['upload_path'] = $upload_path;
$config['file_name'] = date('Ymd_his_').rand(10,99).rand(10,99).rand(10,99);
$config['allowed_types'] = "gif|jpg|png|jpeg|JPG|JPEG|PNG|bmp";
$config['overwrite'] = FALSE;
$config['max_size'] = '0';
$config['max_width'] = $max_width;
$config['max_height'] = $max_height;
$config['min_width'] = $min_width;
$config['min_height'] = $min_height;
$config['max_filename'] = '0';
$config['remove_spaces'] = FALSE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($filename))
{
/*$data['upload_data']['file_name'] = '';
$msg = $this->upload->display_errors('');
$this->session->set_flashdata('msg',$msg);
$url = $_SERVER['HTTP_REFERER'];
redirect($url); */
return false;
//return $error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$config['source_image'] = $config['upload_path'].$data['upload_data']['file_name'];
$config['quality'] = '100%';
$this->load->library('image_lib', $config);
return $data['upload_data']['file_name'];
}
unset($config);
$this->image_lib->clear();
}
#3
2
Files cannot be uploaded with serialize()
function, as it does not serialize files. Please try this approach:
无法使用serialize()函数上载文件,因为它不会序列化文件。请尝试这种方法:
var data = new FormData(this);
$.ajax({
url : me.attr('action'),
dataType : 'json',
contentType : false,
processData : false,
type : 'POST',
data : data,
success: function(resp) { ... etc.
#4
1
Jquery serialize() method not able to post file data.
Jquery serialize()方法无法发布文件数据。
Please used jquery plugin for post file data using ajax. which are given below.
请使用jquery插件使用ajax发布文件数据。以下给出。
dmuploader.js
dmuploader.min.js
for simple example click here
举个简单的例子点击这里
#1
7
serialize() method not able to post file data.
serialize()方法无法发布文件数据。
For sending file using ajax use FormData instead of serializing
对于使用ajax发送文件,请使用FormData而不是序列化
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
HTML5引入了FormData,允许开发人员动态构建表单对象,然后通过AJAX发送此表单对象。
View
<form action="Your controller method name" method="post" id="form_img" enctype="multipart/form-data" accept-charset="utf-8">
<div>
username : <input type="text" name="name">
<span class="error name"></span>
</div>
<div>
password : <input type="text" name="password">
<span class="error password"></span>
</div>
<div>
file : <input type="file" name="image">
<span class="error image"></span>
</div>
<input type="submit" name="submit" value="submit">
</form>
Jquery call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").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);
});
}
}
});
});
});
</script>
controller
function test_image() {
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'name', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run() == TRUE) {
if($_FILES['image']['error'] != 0) {
$result['status'] = false;
$result['message'] = array("image"=>"Select image to upload");
} else {
$config['upload_path'] = 'images';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload',$config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data['upload_data'] = $this->upload->data('file_name');
$image_name = $data['upload_data'];
}
else
{
$image_name = '';
}
$data = array(
'name' => $this->input->post('name'),
'password' => $this->input->post('password'),
'image' => $image_name,
'joined_date' => date('Y-m-d H:i:s')
);
$result['status'] = true;
$this->Perfect_mdl->c_insert($data);
$result['message'] = "Data inserted successfully.";
}
}else {
$result['status'] = false;
// $result['message'] = validation_errors();
$result['message'] = $this->form_validation->error_array();
}
echo json_encode($result);
}
Try this flow for upload image using ajax
尝试使用ajax上传图像
#2
3
try this codein view
试试这个代码视图
$('#formElement').submit(function () {
var formData = new
FormData(document.getElementById("formElement"));
formData.append('image-file', $('#image-file')[0].files[0]);
$.ajax({
url: "<?php echo base_url('home/add')?>",
data: formData,
contentType: false,
processData: false,
type: 'POST',
beforeSend: function() {
$('.loder_img').show();
},
success: function ( data ) {
$('.loder_img').hide();
var val = JSON.parse(data);
//you can apply alerts or anything to show validation on
view and in val all mesg of validation yon can see here in console.
console.log(val);
},
error: function (request, status, error) {
$('.loder_img').hide();
alert(request.responseText);
}
});
});
and in your controller
并在你的控制器
public function addPackage()
{
$this->load->library("form_validation");
//left side form
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('txt_desc', 'Remarks', 'required|trim');
$this->form_validation->set_rules('txt_store', 'Store', 'required|trim');
//upto so on according to your values
if( $this->form_validation->run() == false){
$error = array(
"check_1" => form_error('check_1'),
"txt_desc" => form_error('txt_desc'),
"txt_store" => form_error('txt_store'),
"txt_couple_name" => form_error('txt_couple_name'),
"txt_couple_case" => form_error('txt_couple_case'),
"txt_phone" => form_error('txt_phone'),
"txt_date" => form_error('txt_date'),
"txt_location" => form_error('txt_location'),
"txt_address" => form_error('txt_address'),
"txt_email" => form_error('txt_email'),
);
$msg = array('status' => 'invalid', 'msg'
=>$error,'allerror'=>validation_errors());
echo json_encode($msg);
}else{
//insert it into database all file and values
if($_FILES["image-file"]["size"] != 0){
$path= './uploads/image';
$img = "image/".$this->Upload_model->image_upload($path, "", '', '', '',"image-file");
}
$data = array(
"basket" => $this->filter($this->input->post("check_1",true))........
);
//your insert query
}
}
and in your model to upload image and it will return the uploaded image if it is not upload hen it will return false or you can print the display errors and dont forget to change the path of storing image
并在你的模型中上传图像,它将返回上传的图像,如果它没有上传母鸡它将返回false或你可以打印显示错误,不要忘记更改存储图像的路径
model code
public function image_upload($upload_path, $max_width, $max_height, $min_width, $min_height, $filename)
{
$config['upload_path'] = $upload_path;
$config['file_name'] = date('Ymd_his_').rand(10,99).rand(10,99).rand(10,99);
$config['allowed_types'] = "gif|jpg|png|jpeg|JPG|JPEG|PNG|bmp";
$config['overwrite'] = FALSE;
$config['max_size'] = '0';
$config['max_width'] = $max_width;
$config['max_height'] = $max_height;
$config['min_width'] = $min_width;
$config['min_height'] = $min_height;
$config['max_filename'] = '0';
$config['remove_spaces'] = FALSE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($filename))
{
/*$data['upload_data']['file_name'] = '';
$msg = $this->upload->display_errors('');
$this->session->set_flashdata('msg',$msg);
$url = $_SERVER['HTTP_REFERER'];
redirect($url); */
return false;
//return $error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$config['source_image'] = $config['upload_path'].$data['upload_data']['file_name'];
$config['quality'] = '100%';
$this->load->library('image_lib', $config);
return $data['upload_data']['file_name'];
}
unset($config);
$this->image_lib->clear();
}
#3
2
Files cannot be uploaded with serialize()
function, as it does not serialize files. Please try this approach:
无法使用serialize()函数上载文件,因为它不会序列化文件。请尝试这种方法:
var data = new FormData(this);
$.ajax({
url : me.attr('action'),
dataType : 'json',
contentType : false,
processData : false,
type : 'POST',
data : data,
success: function(resp) { ... etc.
#4
1
Jquery serialize() method not able to post file data.
Jquery serialize()方法无法发布文件数据。
Please used jquery plugin for post file data using ajax. which are given below.
请使用jquery插件使用ajax发布文件数据。以下给出。
dmuploader.js
dmuploader.min.js
for simple example click here
举个简单的例子点击这里