Single file upload jquery php - php

I'm sure I've made a simple error on this one. The file isn't being passed to the php page (I get the "Not uploaded:File error. Please try again." error passed back from the PHP page.)
The code works fine without the JQUERY so I guess the PHP is not the problem.
I've checked the field name / id & it seems OK. I tried testing to see if the value of the button was being passed and it wasn't, that's when I came to the conclusion it was probably the JQUERY but then I was stumped.
I know similar posts have been submitted (I've read them) but I'm desperate!!
Thank you in advance.
Here's the HTML:
<form action="upload.php" name="formname" ENCTYPE="multipart/form-data" id="formid">
<fieldset>
<legend>File info</legend>
<p>
<label for="file1">Files<span class="red"> *</span></label>
<input name="file1" type="file" />
</p>
</fieldset>
<p><label> </label><input type="button" id="submit" value="Add" /></p>
</form>
<div id="output"></div>
<script>
$(function(){
$('#submit').on('click', function(){
var fd = new FormData($("#formid"));
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>
and the PHP
<?php
$strName = 'JoeBloggs';
$intId = 1045;
$missing = '';
date_default_timezone_set("Europe/London");
error_reporting(E_ALL);
include('class.upload.php');
// where to put the images?
$dir_dest = '../'.$intId.'/';
$xcount = 0;
if (!file_exists($dir_dest)) { mkdir($dir_dest, 0777, true);}
# upload 1400px
$handle = new upload($_FILES['file1']);
if ($handle->uploaded) {
$y = $handle->image_src_y;
$height = $y/2;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 700;
$handle->image_y = 260;
$handle->image_convert = jpg;
$handle->Process($dir_dest);
if ($handle->processed) {
// everything was fine !
$strFilename1 = $handle->file_dst_name;
rename( $dir_dest . $strFilename1, $dir_dest . $strName . '.jpg' );
$missing .= 'File uploaded';
} else {
$missing .= $missing. 'Not processed:' . $handle->error . '<br />';
}
} else {
$missing .= 'Not uploaded:' . $handle->error . '<br />';
}
echo $missing;
//header('Location: ../index.php?missing='.$missing);
?>
<img src="<?= $dir_dest . $strName?>.jpg" />

Try this will may help you,
<script>
$(function(){
$('#submit').on('click', function(){
var form = $('#formid')[0];
var formData = new FormData(form);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>

try adding to the ajax function:
contentType: multipart/form-data

Related

How to insert file and other input type using php and ajax using function

I am trying to insert file and text to database using ajax but it is not working.
the main problem is file which is not inserting in database
Here is my code
<form id="descriptionsubmit" enctype = "multipart/form-data">
<textarea class="form-control" id="textarea-description" placeholder="Write Something"></textarea>
<input type="file" name="upload-pic" id="upload-pic" class="inputfile" >
<button type="submit" class="update-btn">Next</button>
</form>
Ajax for same
the alert(data)is showing nothing
$(function(){
$('form#descriptionsubmit').on('submit', function (e) {
e.preventDefault();
var file_data = $('#upload-pic').prop('files')[0];
var formData = new FormData(this);
$.ajax({
method: "POST",
url : "AJAXSubmitClientData.php",
data :formData,
dataType : "html",
contentType: false,
enctype: 'multipart/form-data',
cache: false,
processData:false,
success:function(data)
{
alert(data);
}
});
Php code Here the description is inserting but file not
if(isset($_POST['formData']))
{
$file = array(
"name" => $_FILES['form_data']['name'],
"tmp_name" => $_FILES['form_data']['tmp_name']
);
print_r($file);
$fileinserted = $objMaster->imageinsert($file);
$dataDescription = array(
"description" => $_POST['description'],
"projectProfile" => $fileinserted,
);
echo $insertdata = $objMaster->updateJobPostTable($dataDescription,$_SESSION['lastinsertid']);
echo 1;
}
imageinsert Function
public function imageinsert($file, $path = "") {
$fname = "";
$uploadpath = "";
if ($path == "") {
$uploadpath = $this->upload1;
} else {
$uploadpath = $this->upload1 . $path . "/";
}
$current_timestamp = $this->timeStamp();
$filename = basename($file['name']);
$newname = $current_timestamp . $filename;
if ((move_uploaded_file($file['tmp_name'], $uploadpath . $newname))) {
$fname = $newname;
}
return $fname;
}
Any help is appreciated
HTML Page :-
change the button property value to type="button" instead of type="submit" & add onclick Event Attribute.
<form id="descriptionsubmit" action="" method="post" enctype = "multipart/form-data">
<textarea class="form-control" name="textarea-description" placeholder="Write Something"></textarea>
<input type="file" name="upload-pic" id="upload-pic" class="inputfile" >
<button type="button" onclick="addData()" class="update-btn">Next</button>
</form>
JS AJax Code:-
function addData() {
var formData = new FormData($('#descriptionsubmit')[0]);
formData.append('action', 'add');
$.ajax({
method: 'post',
processData: false,
contentType: false,
cache: false,
enctype: 'multipart/form-data',
url: 'AJAXSubmitClientData.php',
data: formData,
success:function(msg){
alert(msg);
}
});
}
AJAXSubmitClientData.php
<?php
include('dbconn.php');
if(isset($_POST["action"]) && $_POST["action"]=="add"){
echo $a = $_POST["textarea-description"];
echo $g = $_FILES["upload-pic"]["name"];
// insert code here.
}
?>

How to upload image and move in folder using jquery ?

View:
<script>
$("#team_image").change(function(){
var file_data = $('#team_image').prop('files')[0];
var member_name = $("#member_name").val();
var form_data = new FormData();
form_data.append('file', file_data);
$('#imgs').html("<img src='<?php echo base_url(); ?>resource/loading.gif' />");
$.ajax({
url: '<?php echo base_url(); ?>upload',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
$("#imgs").html(php_script_response);
}
});
});
</script>
<input id="team_image" type="file" name="team_image" />
<input id="member_name" type="text" name="member_name" />
Controller:
public function upload()
{
if ( 0 < $_FILES['file']['error'] )
{
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else
{
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$allowed = array("jpg", "jpeg", "png");
if(!in_array($ext, $allowed))
{
echo '<p id="red">Only jpg, jpeg, and png files are allowed.</p>';
}
else
{
$data = array(
'member_name'=>$this->input->post('member_name'),
'team'=>$filename
);
$sql = $this->db->insert('team',$data);
move_uploaded_file($_FILES['file']['tmp_name'], ''.FCPATH.'image/team_image/'.$_FILES['file']['name']);
if($sql==true)
{
echo '<p style="color:green;font-weight:bold;">File uploaded Successfully</p>';
}
else
{
echo '<p id="red">Unable to proceed!</p>';
}
}
}
}
In this code I have simple two file i.e. type="file" and type="text". Now, What I actually want when I click on type=" file" image and member_name will insert into database and image should be moved into a folder. I don't know where am I doing wrong? So, How can I do this? Please help me.
Thank You
Please change AJAX code, don't need to use prop method to get files data, with FormData() method, it will send $_POST & $_FILES data on the server. Also, use form tag.
Please follow below code:-
<script>
$("#team_image").change(function(){
var form_data = new FormData();
$('#imgs').html("<img src='<?php echo base_url(); ?>resource/loading.gif' />");
$.ajax({
url: '<?php echo base_url(); ?>upload',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
$("#imgs").html(php_script_response);
}
});
});
</script>
<form method="post" enctype="multipart/form-data">
<input id="team_image" type="file" name="team_image" />
<input id="member_name" type="text" name="member_name" />
</form>
On server side (on PHP script) you can get data by using $_FILES (Array) & $_POST (Array).
Please use this.

how to fix image input value "null" in laravel 5.6?

in my laravel application I am using dropzone programmatically to upload images. this is my Controller to store images in VehicleController
$photos = $request->file('file');
dd($photos);
if (!is_array($photos)) {
$photos = [$photos];
}
if (!is_dir($this->photos_path)) {
mkdir($this->photos_path, 0777);
}
for ($i = 0; $i < count($photos); $i++) {
$photo = $photos[$i];
$name = sha1(date('YmdHis') . str_random(30));
$save_name = $name . '.' . $photo->getClientOriginalExtension();//this is line 75
$resize_name = $name . str_random(2) . '.' . $photo->getClientOriginalExtension();
Image::make($photo)
->resize(250, null, function ($constraints) {
$constraints->aspectRatio();
})
->save($this->photos_path . '/' . $resize_name);
$photo->move($this->photos_path, $save_name);
$upload = new Upload();
$upload->filename = $save_name;
$upload->resized_name = $resize_name;
$upload->original_name = basename($photo->getClientOriginalName());
$upload->save();
}
return Response::json([
'message' => 'Image saved Successfully'
], 200);
and programatically jquery is
Dropzone.autoDiscover = false;
// Dropzone class:
var myDropzone = new Dropzone("div#my-dropzone", { url: '/form'});
routes
Route::post('form','VehicleController#store');
My blade file is
<div class="dropzone" id="my-dropzone">
<div class="dz-message">
<div class="col-xs-8">
<div class="message">
<p>Drop files here or Click to Upload</p>
</div>
</div>
</div>
<div class="fallback">
<input type="file" name="file" multiple>
</div>
</div>
but when my form submit button clicked following errors occurred,
1/1) FatalErrorException
Call to a member function getClientOriginalExtension() on null
in VehicleController.php line 75
when I use dd(photos); on
$photos = $request->file('file');
result comming in 'null' massage then, how can fix this problem?
Please try using below AJAX Code.
<form method="post" action="{{url('form')}}" enctype="multipart/form-data">
Remove the Action(action="{{url('form')}}") from your form Tag.
var datastring = $('#fromid').serialize();
$.ajax({
url: "controller url",
type: 'post',
contentType: "application/x-www-form-urlencoded",
data: datastring,
success: function(data){
if(data == '100'){
if($('#file').val() != ''){
var form = $('#fromid')[0];
var formData = new FormData(form);
var imageurl='controller image upload url';
$.ajax({
url:imageurl,
type:"post",
data:formData,
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
setTimeout(function(){
window.location.href="redirect url";
},4000);
}
});
}else{
setTimeout(function(){
window.location.href="redirct url";
},4000);
}
}else{
alert(data);
}
}
});
-------- Controller code.
Print_r($_FILES); //You got the result.
Need to add enctype attribute as:
<form action="" method="post" enctype="multipart/form-data">input here</form>
Please add enctype="multipart/form-data" in form. Like this:
<form action="" method="post" enctype="multipart/form-data">

Need fix on stopping page reloading after file uploading

I'm trying to upload files to the server without page refresh. The uploading works but the page reloads after the uploading is done which is not what I wanted. I'm redirecting to an iframe ("myFrame") to stop the page reloading but it appears this doesn't work correctly. What did I do wrong?
HTML
<form id="upload" target="myFrame" action="sql/main-pix-upload.php" method="post" enctype="multipart/form-data">
<input id="main-pix" class="hidden" name="main_pix" type="file" onchange="uploadPix()" accept="image/*"/>
<label class="gi gi-camera mb-0 text-white" for="main-pix" type="button" title="Change Picture"></label>
</form>
<iframe class="hidden" name="myFrame"></iframe>
SCRIPT
function uploadPix(){
var form = document.getElementById('upload');
form.onsubmit = function(e){
e.preventDefault()
var formData = new FormData(this);
$.ajax({
url: 'sql/main-pix-upload.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
})
});
};
PHP
$account = $_SESSION['account'];
$order = $_SESSION['order'];
$id = $_SESSION['id'];
$pathPix = ('../accounts/'.$account.'/'.$order.'/pix/'.$id.'/');
if(!is_dir($pathPix)){
mkdir($pathPix, 0777, true);
}
$file_name = $_FILES['main_pix']['name'];
$file_size = $_FILES['main_pix']['size'];
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$new_name = "main-pix.png";
$temp = ($_FILES["main_pix"]["tmp_name"]);
$target_file = ($pathPix.$new_name);
if(0 < $_FILES['main_pix']['error']){
echo 'Error: ' . $_FILES['main_pix']['error'] . '<br>';
}else{
move_uploaded_file($temp, $target_file);
}
Either use:
form.onsubmit = function(e) {
e.preventDefault()
};
or:
form.addEventListener("submit", function(e) {
e.preventDefault();
});
And then you have to make the HTTP-Call by yourself using AJAX.

Yet another jquery ajax file upload issue

This is probably repost as I might not searched deep enough in stackoverflow, though a few posts that I found haven't helped me enough. So I'm trying to do a simple thing - upload an image using ajax. I've got this HTML:
<form class="form-inline" id="navigationLinkCreationForm" >
<input type="text" class="form-control" placeholder="Nuorodos pavadinimas" id="linkName" />
<label class="btn btn-default btn-file">
Įkelti ikoną(1:1)<input id="selectNavigationIcon" name="navigationIcon" type="file" style="display: none;">
</label>
<input type="submit" class="btn btn-success" id="createLinkButton" value="Sukurti nuorodą" />
</form>
Then I've got this ajax:
$('#createLinkButton').on('click', uploadFiles);
function uploadFiles(event)
{
event.preventDefault();
var formData = new FormData($('#navigationLinkCreationForm'));
$.ajax({
type: 'POST',
url: '../php_includes/uploadNavigationIcon.php',
data:formData,
success: function (data)
{
console.log(data);
},
processData: false,
contentType: false,
cache: false
});
}
And finally I've got a simple uploadNavigationIcon.php file which just outputs "S" if files have been submitted
<?php
if(isset($_GET['files']))
{
echo "S";
}
After running this I'm just getting empty output, which just means that files weren't submitted.
Try this, its a tested and working code:
$(document).ready(function(){
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
});
upload.php
<?php
if ( $_FILES['file']['error'] > 0 ){ // file data can't be fetched by using $_GET
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>

Categories