How to upload image and move in folder using jquery ? - php

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.

Related

image upload using jquery ajax php mysqli

using ajax to upload image url in database but i got error when submit form. I want upload image url im database without page refresh. Error is GET https://api.ciuvo.com/api/analyze?url=http%3A%2F%2Flocalhost%2F&version=2.1.3&tag=threesixty&uuid=C473346A-075C-48CD-A961-F4B68EFE2C4F 400 (Bad Request)
**html code**
<form id="form" enctype="multipart/form-data">
<label>Image:</label>
<input type="file" name="txtimg">
<input type="submit" value="INSERT IMAGE" name="btnimage">
</form>
<div id="message"></div>
**ajax request**
<script type="text/javascript">
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#message").html(data);
}
});
}));
});
php code
<?php
$host="localhost";
$user="root";
$pass="";
$db="test";
$con=mysqli_connect($host,$user,$pass);
mysqli_select_db($con,$db);
if (isset($_FILES["file"]["type"])) {
$dir = "images/";
$imagelocation=$dir.basename($_FILES['txtimg']['name']);
$extension = pathinfo($imagelocation,PATHINFO_EXTENSION);
if($extension != 'jpg' && $extension != 'png' && $extension != 'jpeg')
{
echo"plzz upload only jpg,jpeg And png";
}
else
{
if(move_uploaded_file($_FILES['txtimg']['tmp_name'],$imagelocation) )
{
if(mysqli_query($con,"Insert into img (img_url) values($imagelocation')"))
{
echo"SUCCESSFULLY";
}
}
else {
echo"ERROR";
}
}
}
?>
You should not call FormData object inside ajax request,
html code
<form id="form" enctype="multipart/form-data">
<label>Image:</label>
<input type="file" name="txtimg">
<input type="submit" value="INSERT IMAGE" name="btnimage">
</form>
<div id="message"></div>
**ajax request**
<script type="text/javascript">
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
var fdata = new FormData(this);
$.ajax({
url: "upload.php",
type: "POST",
data: fdata,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#message").html(data);
}
});
}));
});

Upload file with AJAX jquery

I'm trying to upload a single file with JQUERY AJAX. I found this old thread - Jquery ajax single file upload
I followed the codes, but I kept getting the "Not Set" error on my php script.
Here's my HTML
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File:</label>
<input type="file" name="file" required />
</form>
<input type="button" id="upload" value="Upload"></input>
<div id="output"></div>
Here's my Jquery code. I
used latest uncompressed CDN - https://code.jquery.com/jquery-3.3.1.js
$( document ).ready(function() {
$('#upload').on('click', function(){
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
Here's my php script (upload.php)
<?php
if(isset($_GET['file'])){
$filename = $_FILES['file']['name'];
if(isset($filename) && !empty($filename)){
echo 'File available';
}else{
echo 'please choose a file';
}
} else{
echo 'No file';
}
?>
Update: Changed my PHP code with below and it fixed the issue.
<?php
$info = pathinfo($_FILES['file']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "newname.".$ext;
$target = 'files/'.$newname;
move_uploaded_file( $_FILES['file']['tmp_name'], $target);
if (file_exists("files/{$newname}")) {
echo "Uploaded!";
}
?>

send post data input text and file ( php, jquery, ajax) event click

I have one form html then I have 2 input( input text and input file)
my problem input text cannot send post to upload php.
I using jquery ajax to post data
upload.php
<?php
$nama = $_POST['name'];
$filename = $_FILES['file']['name'];
var_dump($nama);
var_dump($filename);
form
<form method='post' action='' enctype="multipart/form-data">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required />
Select file : <input type='file' name='file' id='file' class='form-control' ><br/>
<input type='button' class='btn btn-info' value='Upload' id='upload'>
</form>
<script type="text/javascript" >
$(function() {
$("#upload").click(function() {
var name = $('#name').val();
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
$.ajax({
type: "POST",
url: "upload.php",
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: fd,
success: function(){
}
});
return false;
});
});
</script>
Just remove dataType:text. Or you can use dataType:"json" as per your requirement. Well, you can read more on this dataType here also: $.ajax - dataType
And for name parameter, you are missing to append that variable in fd variable.
So, your script should be like this:
<script type="text/javascript" >
$(function() {
$("#upload").click(function() {
var name = $('#name').val();
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
fd.append('name',name); // you were missing this, that's why $_POST['name'] was blank
$.ajax({
type: "post",
url: "upload.php",
cache: false,
contentType: false,
processData: false,
data: fd,
success: function(){
}
});
return false;
});
});
</script>
Now try by printing below code into your upload.php file:
<?php
echo $nama = $_POST['name'];
echo $filename = $_FILES['file']['name'];
?>

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";
}
}
?>

Single file upload jquery 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

Categories