How to upload file and insert data with php jquery ajax - php

I cannot send via ajax to php file upload and data with ajax. This my code just send file upload. data not send to my php code. I create form and the function send on click using ajax to post on php. I'm using codeigniter
This my form:
<form action="<?php echo site_url('home/send_chat');?>" method="post" enctype="multipart/form-data">
<input name="message" id="message" type="text" class="form-control input-sm" />
<input type="file" id="file" name="file" />
<br />
<span class="input-group btn">
<button type="submit" class="btn btn-info btn-sm" id="submit">Enkripsi</button>
</span>
</form>
This javascript to send post on php using ajax:
$('#submit').on('click', function(){
var message = $('#message').val();
var fd = new FormData(this);
fd.append('file',$('#file')[0].files[0]);
$.ajax({
method:"POST",
url:"<?php echo site_url('home/send_chat');?>",
data: {fd,message:message},
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
I'm already try using $_POST['message']; and $this->input->post("message"); its not work both
This php to proces code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
public function send_chat()
{
$name = $_FILES['file']['name'];
$error = $_FILES['file']['error'];
$size = $_FILES['file']['size'];
// $message = $_POST['message'];
$message = $this->input->post("message");
$user = $this->session->userdata('username');
$iduser = $this->session->userdata('userID');
$insert="insert into chat (user,message,id_user,fileupload) VALUES ('$user','$message','$userid','$name')";
$this->db->query($insert);
}
}
In database i'm just send name file upload.user, message, and iduser its not send.

i think your problem may be in ajax code
since you are using formData object . try append the message variable with it
$('#submit').on('click', function(){
var fd = new FormData(this);
fd.append('file',$('#file')[0].files[0]);
fd.append('message ',$('#message').val());
$.ajax({
method:"POST",
url:"<?php echo site_url('home/send_chat');?>",
data: fd,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});

try to make ajax code like this.
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file', file);
});
$.ajax({
type : "POST",
url : "<?=base_url()?>home/send_chat",
data : data,
cache: false,
contentType: false,
processData: false,
success: function(data) {
}
});
and your controller make like this it's working code for me
class Home extends CI_Controller {
function singleImageUpload($upload_name,$folder,$extension,$bnr,$filename)
{
if($folder == '')
{
$config['upload_path'] = 'images/agent';
}
else
{
$config['upload_path'] = 'upload/'.$folder."/";
}
$config['allowed_types'] = '*';
if($bnr == 2)
{
$config['max_width'] = '3000';
$config['max_height'] = '3000';
}
elseif ($bnr == 1)
{}
// $config['file_name'] = $user_name.date('YmdHis').".".$extension;
$config['file_name'] = $filename;
$this->upload->initialize($config);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($upload_name))
{
$arrayRetutn['upload'] = 'False';
$arrayRetutn['error'] = $this->upload->display_errors();
}
else
{
$arrayRetutn['upload'] = 'True';
$arrayRetutn['data'] = $this->upload->data();
}
//echo '<pre>';print_r($arrayRetutn);echo '</pre>'; die;
return $arrayRetutn;
}
public function send_chat()
{
$user = $this->input->post("user");
$message = $this->input->post("message");
$iduser = $this->input->post("iduser");
if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '')
{
$image_name = explode(".",$_FILES['file']['name']);
$imgData = $this->singleImageUpload('file','your folder name',$image_name[1],'2',$_FILES['file']['name']);
if($imgData['upload']=='True')
{
$name = $imgData['data']['file_name'];
}
}
$insert="insert into chat (user,message,id_user,fileupload) VALUES ('$user','$message','$iduser','$name')";
$this->db->query($insert);
}
}

I think the point #kunal was making was that you should not add potentially sensitive data as hidden inputs ( anyone can change it ) but should reference the values held in those fields directly within your class before adding to the db. In addition using embedded variables opens your app to sql injection so use a prepared statement.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
public function send_chat(){
$name = $_FILES['file']['name'];
$error = $_FILES['file']['error'];
$size = $_FILES['file']['size'];
$user = $this->session->userdata('username');
$iduser = $this->session->userdata('userID');
$message = $this->input->post("message");
$sql="insert into `chat` ( `user`, `message`, `id_user` ,`fileupload` ) values (?,?,?,?)";
$stmt=$this->db->prepare( $sql );
if( $stmt ){
$stmt->bind_param('ssss',$user,$message,$userid,$name);
$stmt->execute();
}
}
}
I played around with your original javascript/jQuery code but could not get the function to work ( I don't use jQuery so I was guessing ) but using regular, vanilla javascript you can do it like this ~ the portion of php code at the top is not really relevant as you would be sending the ajax request to home/send_chat
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* send some sort of response... */
echo json_encode( $_POST );
exit();
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>xhr upload - no jquery</title>
<script>
document.addEventListener('DOMContentLoaded',function(){
var callback=function( data ){
alert( data )
}
document.getElementById('submit').onclick=function(e){
e.preventDefault();
var url='<?php echo site_url('home/send_chat');?>';
var _file=document.querySelector('input[type="file"]');
var _form=document.querySelector('form[id="usr-upload"]');
var xhr = new XMLHttpRequest();
var fd=new FormData( _form );
fd.append('file', _file.files[0]);
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )callback.call( this, xhr.response );
};
xhr.onerror=function(err){
alert(err);
};
xhr.open('POST',url,true);
xhr.send( fd );
};
},false );
</script>
</head>
<body>
<form id='usr-upload' method='post' enctype='multipart/form-data'>
<input name='message' type='text' />
<input type='file' name='usrfile' />
<br />
<span class='input-group btn'>
<input type='button' value='Enkripsi' id='submit' />
</span>
</form>
</body>
</html>

Submit all the data with or without file using ajax
<form method="post" action="" enctype="multipart/form-data" id="form"/>
// your own input fields
</form>
$("#form").submit(function (event) {
event.preventDefault();
//tinyMCE.triggerSave();
$.ajax({
url: "<?php echo base_url('your_own_controller/your_own_method'); ?>",
type: "post",
data: new FormData(this),
processData: false,
contentType: false,
cache: false,
async: false,
beforeSend: function () {}, //if you like to do something before submit
complete: function () {}, //if you like to do something before submit
success: function (response) {
//check response and do some your own stuff
};
});

Related

PHP upload image through AJAX issue

I want to upload the image to a /uploads/ directory in my root file but here's the problem: my AJAX does not get a response from the server, and I don't think I'm accessing the image's data for upload. Please take a look at my code:
HTML form:
<form action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method = 'post' id="dashboard_create_BPost_form" onsubmit="return false" enctype="multipart/form-data">
<input type="file" name="file" id="file">
</form>
Javascript (jQuery ajax)
$("#dashboard_submit_new_BPost").on('click', function(){
var property = document.getElementById("file").files[0];
var image_name = property.name;
var image_extension = image_name.split(".").pop().toLowerCase();
if(jQuery.inArray(image_extension, ['gif', 'png', 'jpg', 'jpeg']) == -1){
alert("Invalid Image File");
}
var image_size = property.size;
if(image_size > 6000000){
alert("File size exeds 6 MB");
}else{
var form_data = new FormData();
form_data.append("file", property);
$.ajax({
url: './includes/functions.php',
method: 'POST',
data:{
publishBlogPost : 1,
data : form_data,
},
contentType: false,
cache: false,
processData: false,
success: (res)=>{
console.log(res)
},
error: (jqxhr, status, exception)=> {
alert('Exception:', exception);
}
});
}
});
And this is my back-end in functions.php
if(isset($_POST['publishBlogPost'])){
if($_FILES["file"]["name"] != ''){
$test = explode(".", $_FILES["file"]["name"]);
$extension = end($test);
$name = rand(100, 999). '.' .$extension;
$location = './uploads/'.$name;
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
}
echo '123';
}
Note that I am not receiving 123 in console in the success method within the AJAX call.
Thank you in advance
The following POSTS to the same page for demonstration purposes - the PHP at the top emulates whatever code you have in /includes/functions.php to process the upload.
Rather than appending the FormData object to another Object Literal as the POST payload in the ajax function, send the FormData object as the entire payload but append whatever other fields you wish to process in PHP.
<?php
error_reporting( E_ALL );
$debug=false;
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$publishBlogPost=isset( $_POST['publishBlogPost'] );
if( isset( $_FILES['file'] ) ){
$obj=(object)$_FILES['file'];
$tmp=$obj->tmp_name;
$name=$obj->name;
$size=$obj->size;
/* process upload ... */
exit( $name );
}
exit( false );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<script>
document.addEventListener('DOMContentLoaded',function(){
$('#dashboard_submit_new_BPost').on('click', function(e){
var oFiles=document.getElementById('file').files;
var property=oFiles[0];
if( !property ){
alert('No file selected');
return false;
}
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if( jQuery.inArray( image_extension, ['gif', 'png', 'jpg', 'jpeg'] ) == -1 ){
alert('Invalid Image File');
}
var image_size = property.size;
if( image_size > 6000000 ){
alert('File size exeds 6 MB');
return false;
}else{
var form_data = new FormData();
form_data.append('file', property );
form_data.append('publishBlogPost',1);
$.ajax({
url:location.href,
method:'POST',
data:form_data,
contentType:false,
cache: false,
processData: false,
success:( res )=>{
console.log( res );
alert( 'ok' )
},
error: (jqxhr, status, exception)=> {
alert('Exception:', exception);
}
});
}
});
});
</script>
</head>
<body>
<form method='post'>
<input type='file' name='file' id='file' />
<input type='button' id='dashboard_submit_new_BPost' value='Submit' />
</form>
</body>
</html>

file upload get null value in Codeigniter controller

i am trying to upload image using ajax in Codeigniter without form Submit my html code is
<div class="profile-img">
<img class="" src="<?php echo base_url() ?>assets/dist/img/<?php echo $adminData->image ?> " alt="User profile picture">
<div class="file btn btn-lg btn-primary">
Change Photo
<input type="file" name="profile_img" id="profile_img"/>
</div>
<span id="uploaded_image"></span>
</div>
using this code i am send ajax on change event using given code
$('#profile_img').change(function () {
var file_data = $('#profile_img')[0].files;
var form_data = new FormData();
form_data.append('profile_img',file_data);
var admin_id= <?php echo (int)$adminData->admin_id ?>;
$.ajax({
url: "<?php echo base_url(); ?>admin/upload_image",
method: "GET",
data: {admin_id: admin_id, form_data: form_data},
contentType: false,
cache: false,
processData: false,
beforeSend: function ()
{
$('#uploaded_image').html("<label class='text-success'>Uploading...</label>");
},
success: function (data)
{
$('#uploaded_image').html(data);
}
})
});
it working fine but when we have hit controller its get null value both admin_id and form_data
my actual problem here i am still to trying get value but it always given null value
my controller code is
function upload_image() {
$data['admin_id'] = $this->input->post('admin_id');
if (isset($_FILES['form_data']['name'])) {
$config1['upload_path'] = 'assets/dist/img/';
$config1['overwrite'] = TRUE;
$config1['allowed_types'] = 'gif|jpg|png|jpeg';
$config1['file_name'] = $_FILES['form_data']['name'];
$this->load->library('upload', $config1);
$this->upload->initialize($config1);
if (!$this->upload->do_upload('form_data')) {
$error = array('error' => $this->upload->display_errors());
} else {
$fileData = $this->upload->data();
$data['image'] = $fileData['file_name'];
}
}
$this->admin_mod->update_image($data);
}
can anyone suggest me where am i wrong.
You're passing a FileList to FormData.append you have to pass a File. You can pass the first file in the list like in an array.
var file_data = $('#profile_img')[0].files[0];
Also your file is sent as profile_img you're trying to read it as form_data
if (isset($_FILES['profile_img']['name'])) {

unable to upload file in codeigniter using AJAX

I'm trying to upload the file in CodeIgniter using Ajax but the problem is the file is uploading in the database but unable to do it without loading the page. Every time I upload a file it uploading successfully but navigating to its controller address with JSON code. I just want to upload the file without refreshing page.
View FILE
<?php echo form_open_multipart('maker/Checkout/docs', array('id'=>'upload_file')); ?>
<div class="form-group">
<label for="userfile">Upload existing CV</label>
<input class="form-control" type="file" name="userfile" id="userfile" size="20" />
</div>
<div class="form-group">
<button class="btn btn-info" type="submit">Upload</button>
</div>
<?php echo form_close() ?>
Ajax Code
<script>
$(function() {
$('#upload_file').unbind('submit').bind('submit', function() {
e.preventDefault();
var form = $(this);
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
secureuri :false,
fileElementId :'userfile',
dataType : 'json',
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
}
alert(data.msg);
}
});
return false;
});
});
</script>
Controller
public function docs() {
$status = "";
$msg = "";
$file_element_name = 'userfile';
if ($status != "error")
{
$config['upload_path'] = dirname($_SERVER["SCRIPT_FILENAME"])."/assets/img/posts";
$config['upload_url'] = base_url()."/assets/img/posts";
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|docx|docs|txt|xml';
$config['max_height'] = 102048;
$config['max_width'] = 102048;
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
$file_id = $this->Checkout_model->newcheckout($data['file_name']);
if($file_id)
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
I just want to upload the file without refreshing the page. Currently, it's uploading the file but after upload its navigating to the controller address.
The reason why you're navigating to controller is because your call to preventDefault is from a non existent identifier e causing an error, you can remove it since you have return false later or just define the e.
Now when you're trying to upload a file with ajax you use a FormData object
$(function() {
$('#upload_file').unbind('submit').bind('submit', function(e) {//<-- e defined here
e.preventDefault();
var form = $(this);
var data = new FormData(this);
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: data,
processData: false,
contentType: false,
dataType : 'json',
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
}
alert(data.msg);
}
});
return false;
});
});
Slightly different variation of solution that worked for me is given below:
<script type="text/javascript">
$(function() {
$('#upload_file').unbind('submit').bind('submit', function(e) {
e.preventDefault();
var file = document.getElementById('userfile').files[0];
if(file==undefined){
return false;
}
var formData = false;
if (window.FormData) {
formData = new FormData();
formData.append("userfile", file);
}
var form = $(this);
if(formData!==false){
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: formData,
processData: false,
secureuri: false,
contentType: false,
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
}
alert(data.msg);
}
});
}
return false;
});
});
</script>

Image is always NULL on upload form

I'm trying to upload image on user registration via ajax. This is how it's look like the form + some fields for name, password and email which are working good.
<form method="post" class="registerForm" enctype="multipart/form-data" id="login-form">
<div class="form-group">
<label><b>Profile Image <span class="required">*</span></b></label>
<input accept="image/*" type="file" id="picture" name="picture" required>
</div>
<div class="clearfix">
<button type="submit" id="login" class="signupbtn">Sign Up</button>
</div>
</form>
I have found on another thread here on SO that I need to put this on my ajax script
var data = $("#login-form").serialize();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
And this is whole ajax
function submitForm()
{
var data = $("#login-form").serialize();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
$.ajax({
type : 'POST',
url : 'registration.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#login").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success : function(data)
{
if(data=="registered")
{
}
}
});
return false;
}
And the server side for the picture part and the query
if(!empty($_FILES['picture']) && $_FILES['picture']['size'] >0 ){
$profilePic = $randomString. basename($_FILES['picture']['name']);
$uploadfile = $uploaddir .$randomString. basename($_FILES['picture']['name']);
if (move_uploaded_file($_FILES['picture']['tmp_name'], $uploadfile)) {
} else {
$error = "error\n";
}
}else{
$error ='Please add your Picture!';
}
var_dump($_FILES['picture']);
try
{
$stmt = $db_con->prepare("SELECT * FROM users WHERE email=:email");
$stmt->execute(array(":email"=>$email));
$count = $stmt->rowCount();
if($count==0){
$stmt = $db_con->prepare("INSERT INTO users (picture) VALUES (:picture)");
$stmt->bindParam(":picture",$profilePic);
if($stmt->execute()) {
echo "registered";
}
else { echo "Query could not execute !"; }
}
else{ echo "1"; }
}
catch(PDOException $e){
echo $e->getMessage();
}
I've removed other fields in order keep the code simple as much as possible. All fields got inserted and saved in database except the image name.
What can be the problem? No errors at all. I've got registered on the console and NULL for var_dump($_FILES['picture'])
jQuery processes the data as a string if you don't use proccessData: false. Bellow code will work just fine. Also included some comments in code
$(document).ready(function (e){
$("#login-form").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "registration.php",
type: "POST",
data: new FormData(this), // Data sent to server
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data){
if(data=="registered"){}
},
error: function(){}
});
}));
});
You must set the contentType option to false, so jQuery won't add a Content-Type heade also set processData flag set to false otherwise jQuery will try to convert your FormData into a string, which will fail.
So ajax code will look like
$(".signupbtn").click(function(e){
e.preventDefault();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
$.ajax({
type : 'POST',
url : 'registration.php',
data : form,
contentType: false,
processData: false,
success : function(data){}
});
});

Image is not uploading using jquery in codeigniter

I am trying to upload the image to the folder in codeginter using jquery. But I am not able to get what is the exact issue why the image is not getting upload and showing me message
You did not select a file to upload.
I am not able to get why the file is not selected to upload here. Her is my php code
public function add_new_book()
{
$image = $this->input->post('bookfile');
$img=$this->input->post('bookfile');
$config['upload_path'] = '/uploads';
$config['overwrite'] = 'TRUE';
$config["allowed_types"] = 'jpg|jpeg|png|gif';
$config["max_size"] = '1400';
$config["max_width"] = '1400';
$config["max_height"] = '1400';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('bookfile'))
{
$this->data['error'] = $this->upload->display_errors();
echo json_encode(array("result"=>$this->data['error']));
exit;
}
}
And I write jquery code here
$( document ).ready(function() {
$("#btnsavebook").click(function(){
if($("#bookfileid").val() != ''){
if (typeof FormData !== 'undefined') {
var formData = new FormData($("#form-upload")[0]);
console.log("formdata:",formData)
$.ajax({
type: "POST",
url: "CreateBook/add_new_book",
data: formData,
mimeType:"multipart/form-data",
dataType: 'json',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
cache:false,
contentType: false,
processData: false,
success: function(result){
}
});
} }
});});
Anybody please tell me how can I achieve this process??
Thanks
Try this
View file
<html>
<head>
<title>Ajax Image Upload Using PHP and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="my_image" id="my_image" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
<h4 id='loading' >loading..</h4>
<div id="message"></div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
$.ajax({
url: "<?php echo base_url('test/hello'); ?>", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
});
</script>
Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends CI_Controller {
public function __construct ()
{
parent::__construct();
}
public function index()
{
$this->load->view('test');
}
public function hello()
{
// print_r($_FILES['file']); die;
$config['upload_path'] = 'uploads';
$config['allowed_types'] = 'gif|jpg|png|jpeg'; // allowed file formats
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('my_image'))
{
echo $this->upload->display_errors(); // It will return errors if file not uploaded
}
else
{
echo "uploaded";
}
}
}
Source : https://www.formget.com/ajax-image-upload-php/

Categories