How to properly send FormData() with AJAX - php

There seems to be a problem when I try to send my FormData with AJAX from my LTS server (not on my local machine). I suspect that FormData is not supported to all browser but it does work perfectly on my local machine with the same browser I used when I tried it on my server (LTS). I'm a bit lost here and don't know what to do.
To explain further:
index
<form class="image" enctype="multipart/form-data" accept-charset="utf-8" method="post">
<input id="image-value" data-id="{{id}}" name="{{picture}}" class="image-box-{{id}}" data-type="{{type}}" type="file" value="{{picture}}" />
<p id="{{id}}" class="label" >Update</p>
</form>
I need to get the file here and upload it into a server directory
script
$('[id="image-value"]').change(function(e) {
var data = new FormData();
var file_data = this.files[0];
data.append('file', file_data);
e.preventDefault();
$.ajax({
url: './someController/upload_picture/',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function(data){
if (data.success == true) {
console.log(data.image_name);
} else {
var error = data.error_message;
$(".question-message").fadeIn("fast").html(error);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error("The following error occured: " + textStatus, errorThrown);
}
});
});
controller
function __construct() {
parent::__construct();
$config['upload_path'] = './data/picDir/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
}
function upload_picture() {
if ($this->check_authorization()) {
if ($this->ion_auth->get_user_id()) {
if ($this->upload->do_upload('file')) {
$data = $this->upload->data();
echo json_encode(array(
"image_name" => $data["file_name"],
"success" => true
));
} else {
echo json_encode(array(
"success" => false,
"error_message" => $this->upload->display_errors()
));
}
}
}
}
when triggered, the request just keeps on waiting for a response from the php controller which I think is not responding.

I believe your "echo json_encode..." should be in a response - something like $this->response(json_encode...). echo will not return a response to the ajax request. Please, check your framework or lib for the correct response and share it.

Related

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 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/

How to pass extra fields for post with file upload in ajax codeiginter

I am upload a file in php codeigniter project using a ajax. The file is uploading succesfully. But I also want to post some extra values to database with this. I am not sure how to do it. Can anybody please tell me how to pass another data fields while saving a file in php
Here is my js code
$("#btnupdatecover").click(function(event){
alert(coverPostion);
if($("#fileuploadcover").val() != ''){
if (typeof FormData !== 'undefined') {
var form = $('#formname').get(0);
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "Userpage/updatedp",
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){
toastr8.info({
message:'Profile Picture Updated',
title:"New Image Uploaded",
iconClass: "fa fa-info",
// imgURI: ["https://unsplash.it/120/120?image=20"]
});
clearAll();
}
});
//
event.preventDefault();
}
}
else
{
toastr8.info({
message:'Error Occured',
title:"Please try again",
iconClass: "fa fa-info",
// imgURI: ["https://unsplash.it/120/120?image=20"]
});
}
});
My PHP Code
public function updatedp()
{
$var = $_FILES ['fileUp'];
$img=$_FILES ['fileUp'];
$config['upload_path'] = 'webim/dp_images';
$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('fileUp'))
{
$this->data['error'] = $this->upload->display_errors();
echo json_encode(array("result"=>$this->data['error']));
exit;
}
else
{
$data=array('active'=>0);
$this->db->where('userid','1');
$this->db->update('music_user_dp',$data);
$uname['uname'] =$this->session->all_userdata('uname');
$uname['id'] =$this->session->all_userdata('id');
$post_data = array(
'id' => '',
'userid' => $uname['id']['id'],
'profilepic'=>$var['name'],
'updatedate' => date("Y-m-d H:i:s"),
'active' => '1'
);
$this->Userpage_model->insert_dp_to_db($post_data);
echo json_encode(array("result"=>"Success"));
exit;
}
}
I just pass extra fields with this to post in database.
Thanks
You can achieve this:
Approach 1
Use hidden fields into the form.
Approach 2
$.ajax({
type: "POST",
url: "Userpage/updatedp",
data: {formData: formData, var1: 'value', var2: 'value'},
dataType: 'json',
success: function(result){
toastr8.info({
message:'Profile Picture Updated',
title:"New Image Uploaded",
iconClass: "fa fa-info",
// imgURI: ["https://unsplash.it/120/120?image=20"]
});
clearAll();
}
});
Now these value you will get your controller.

How to debug a non-working response from AJAX in CodeIgniter?

I want to upload photo with jquery-ajax in CodeIgniter. First I want to pass file to my controller for just check my AJAX call properly working or not.
My code is not posting anything to my controller. I posting my code here, please show me my fault
Here is my code
jQuery and my input of my view is here (profile_view.php)
<script type="text/javascript">
$(document).ready(function() {
$("#file1").on("change", (function() {
$("#showimage").fadeIn("slow").html('');
$("#showimage").fadeIn("slow").html('Plaese Wait...');
alert('hello');
$("#frm1").ajaxForm({
target: '#showimage',
success: function(response) {
alert(response);
},
error: function(err) {
alert(err);
}
}).submit();
}));
</script>
My input code is here
<div id="photoframe">
<form name='frm1' id="frm12" enctype="multipart/form-data" method="post" action="upload_photo">
<input type="file" name="file1" id="file1" style="visibility:hidden" />
</form>
<a style="color:white"><i class="fa fa-edit" id="img1">Edit Photo</i></a>
<div id="showimage" name='showimage'>
</div>
</div>
My controller is Here (upload_photo.php)
class Upload_photo extends CI_Controller {
function __construct() {
parent::__construct();
$this - > load - > helper(array('form', 'url'));
}
public
function index() {
$config['upload_path'] = '/user';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
if (isset($_POST['frm1'])) {
echo 'Image Uploaded';
echo "post".$_FILE['frm1'];
} else {
echo 'Image Upload Failed';
}
}
}
My output is : Image Upload Failed
I think there is problem with your request, You have not passed any data with that request, You can use following data method to pass data with ajax:-
$.ajax({
url: "post.php",
data: {
id: 123
},
type: "GET",
dataType : "json",
success: function( json ) {
// Do your code here for success
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
},
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
And you can not send image file with these AJAX request.
Please change your PHP code also, something like following :-
if (isset($_FILES['frm1'])) {
// Do your upload code here
}
else
{
echo 'Image Upload Failed';
}
This is the ajax call for non processed data (in your case upload images):
var form = $('frm12');
var formdata = false;
if (window.FormData){
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url: formAction,
data : formdata ? formdata : form.serialize(),
cache : false,
contentType : false,
processData : false,
dataType: "json",
type : 'POST',
resetForm: true,
})
.done(function(data) {
//returned response
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
Please note the "processData: false", this is needed to tel ajax to not act as a standard data transfer.
"By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false." from http://api.jquery.com/jquery.ajax/. You can find here explaination about the jquery.ajax settings.
Is worth to mention that if you want to make some checks before sending the data to the server (and I reccoment this) you can also use the "beforeSend: beforeSubmit," setting where "beforeSubmt" is a function that you can implement where you will make all the needed checks (e.g. allowed file type, allowed file size and more...). If something fails than the data will not be uploaded.

ajax jquery file upload not working

I am using jQuery ajax to upload files. When I clicked upload button,it fails and the error section of ajax is showing Uncaught TypeError: Cannot read property 'length' of undefined. I have checked the code and found that alerting the jqXHR shows success in the first ajax call,but the ajax call in submitForm() is not working.The controller stops before the $.each(event,data) and it shows the above error in the console.Please help me.
My code is below:
$(document).ready(function()
{
//for checking whether the file queue contain files or not
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files
function prepareUpload(event)
{
files = event.target.files;
alert(files);
}
$("#file-form").on('submit',uploadFiles);
function uploadFiles(event)
{
event.stopPropagation();
event.preventDefault();
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
//alert(key+' '+ value);
});
$.ajax({
url: 'module/portal/filesharing/upload.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
console.log('ERRORS: ' + data.error);
}
}
});
function submitForm(event, data)
{
// Create a jQuery object
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();//controller stops here
// sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'update.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
}
});
</script>
Html:
<form id='file-form' action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="filename" ><br>
<input type="submit" id='upload' value="Upload file">
</form>
My update.php:
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
$uploaddir = 'module/portal/filesharing/upload/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
If you want it works on cross-browser, i recommend you use iframe like this http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
Or there is some jquery modules using flash for upload they are also good option for older version of internet explorer
Maybe your problem is this one, please check this out
how to get the uploaded image path in php and ajax?

Categories