codeigniter get ajax post files - javascript

am trying to upload multiple files using ajax in codeigniter. my ajax post is working fine but i don't know how to get the post files in my controller.
I tried this way but its not working. please help. Thank you.
HTML
<form method="post" name="upload_files" action="<?php echo base_url(); ?>home/upload_files" id="form_files" enctype="multipart/form-data">
<h4 style="float: left">Add files. (file types .png, .jpeg, .dwg, .pdf, jpg) max: 10Mb <span style="color:red;" id ="err_type"> * </span></h4>
<div class=from-section>
<div class="row">
<div class="span4" id="image" >
<div class="cart-total" id="clone_image" data-provides="fileupload">
<div class="form-group has-success has-feedback">
<input class="form-control" type="file" name="files[]" accept="image/*" />
</div>
</div>
</div><!-- /.span4 -->
</div><!-- /.row -->
</div>
<div class="cart-total">
<a id="another_image" class="btn btn-default" style="height: 45px;padding: 12px 12px; margin-right: 10px; ">+ Add More Files</a>
<a id="submit_files" class="rx-bottom" >Submit Files</a>
</div>
</form>
AjAX
<script type="text/javascript">
$('#submit_files').click(function() {
var formData = new FormData($('#form_files')[0]);
$.ajax({
url: "<?php echo base_url('home/upload_files/'); ?>",
type: "POST",
data: formData,
mimeType: "multipart/form-data",
processData: false,
contentType: false,
success: function(res) {
console.log("success");
},
error: function(res) {
console.log("error");
}
});
});
</script>
My console is logging success message
CONTROLLER
public function upload_files(){
$order_id = 123;
if(!$order_id){
redirect('home/instant_quote', 'refresh');
}else{
$this->load->library('upload');
//$files = $this->input->post();
$files = $_FILES;
if($files){
for( $i = 1; $i < 20; $i++) {
$config = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|png|pdf|dwg|zip';
$config['max_size'] = '11000';
$config['file_name'] = 'order_'.$order_id.'_'.$i;
$config['overwrite'] = false;
$this->upload->initialize($config);
$this->upload->do_upload('files'.$i);
$image_data = array('upload_data' => $this->upload->data());
if($image_data["upload_data"]["file_size"]){
$inserted['order'] = $i ;
$inserted['name'] = $image_data["upload_data"]["file_name"];
$inserted['extension'] = $image_data["upload_data"]["file_ext"];
$inserted['type'] = $image_data["upload_data"]["file_type"];
$inserted['size'] = $image_data["upload_data"]["file_size"];
$prop = $this->home->insert_files($inserted);
}
}
}else{
$this->load->view('comman/header.php');
$this->load->view('home/add_files.php');
$this->load->view('comman/footer.php');
}
}
}
This is what i see when i log the form data

You can use this in your controller:
function upload(){
if(!empty($_FILES)){
$type= $_FILES["files0"]["type"]; //files0 is your input file name
$size= $_FILES["files0"]["size"];
$file_name = $_FILES["files0"]["name"];
$source = $_FILES['files0']['tmp_name'];
$dir = "./uploads/";
$file = $dir . $file_name;
if(!file_exists ($file ))
{
move_uploaded_file($source,$file );
exit("File has been uploaded");
}
else
{
echo "File exist";
}
}
$this->load->view('v_test');
}
And for your ajax jquery:
//add this to your head html
<script>
var base_url = "<?php echo base_url(); ?>";
</script>
and, this is your ajax call :
$("#submit_files").click(function() {
var formData = new FormData($("#form_files")[0]);
$.ajax({
url: base_url + "home/upload_files",
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Please test with single file first, and if it worked. Try to dynamically upload multiple files. Hope this help you out. :D

Related

id undefined when details are passed to a modal

I have a table of recipes created by a particular user, and when the pencil mark on each row of the table is clicked, a modal is displayed, showing the details of this particular recipe and it should allow the user to edit the recipe and save the updated version to the database. However, although the details are correctly being passed to the modal, the recipe id doesn't seem to be passed to the modal, since I have tried to output the recipe id into the console and it says the recipe id is undefined. I have tried to debug this error but to no avail. Can anyone provide any insight into why this might be?
//Recipe.js
$('.editThis').on('click', function() {
var recipe_id = $(this).attr('data-id');
var request = $.ajax({
url: "ajax/displayRecipe.php",
type: "post",
dataType: 'json',
data: {recipe_id : recipe_id}
});
request.done(function (response, textStatus, jqXHR){
console.log("response " + JSON.stringify(response));
$('#name').val(response.name);
$('#date').val(response.date);
});
});
$('#editRecipe').click(function() {
var recipe_id = $(this).attr('data-id');
var name_input = $('#name').val();
var date_input = $('#date').val();
var request = $.ajax({
url: "ajax/updateRecipe.php",
type: "post",
data: {name : name_input, date : date_input, recipe_id : recipe_id},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
});
//Recipe.php
<?php
$recipeObject = new recipeList($database); //Lets pass through our DB connection
$recipe = $recipeObject->getUserRecipes($_SESSION['userData']['user_id']);
foreach ($recipe as $key => $recipes) {
echo '<tr><td>'. $value['name'].'</td><td>'. $value['date'].'</td><td>'.'<a data-id = '.$value['recip_id'].' data-toggle="modal" class="edit editThis" data-target="#editRecipe"><i class="fa fa-pencil"></i></a>'.'</td></tr>';
}
?>
// editRecipe Modal
<div id="recipe" class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header recipe">
<h1 class="modal-title">Edit Recipe</h4>
</div>
<div class="modal-body">
<form method="post" id="updateRecipeForm">
<?php
require_once('classes/recipes.classes.php');
$recipeObject = new recipeList($database);
$recipe = $recipeObject->getRecipeDetails(recipe_id);
if(isset($_POST['submit'])) {
$updateRecipe = $recipeObject ->updateRecipe($_POST['name'], $_POST['date'], $_POST['recipe_id']);
if($updateRecipe) {
echo ("Your recipe has been updated!";
}
}
?>
<div class="form-group">
<input type="text" class="control-form" id="name" value = "<?php echo $recipe['name']; ?>">
</div>
<div class="form-group">
<input type="date" class="control-form" id="date" value = "<?php echo $recipe['date']; ?>">
</div>
</div>
<div class="form-group">
<input type="hidden" class="form-control" data-id=".$recipe['recipe_id']." id="recipe_id" name="recipe_id" value = "<?php echo $recipe['recipe_id']; ?>">
</div>
<button type="submit" class="btn recipe" id="editRecipe" data-dismiss="modal">Save</button>
</form>
</div>
</div>
</div>
</div>
//ajax - updateRecipe.php
<?php
require_once('../includes/database.php');
require_once('../classes/recipes.classes.php');
if($_POST['name'] && $_POST['date'] && $_POST['trans_id']){
$recipeObject = new recipeList($database);
echo $recipeObject->updateRecipe($_POST['name'], $_POST['date'], $_POST['recipe_id']);
}
?>
//recipes.classes.php
...
public function getRecipeDetails($recipeid){
$query = "SELECT * FROM recipe WHERE recipe_id = :recipe_id";
$pdo = $this->db->prepare($query);
$pdo->bindParam(':recipe_id', $recipeid);
$pdo->execute();
return $pdo->fetch(PDO::FETCH_ASSOC);
}
public function updateRecipe($name, $date, $recipe_id){
$query = "UPDATE recipe SET name = :name, date = :date WHERE recipe_id = :recipe_id";
$pdo = $this->db->prepare($query);
$pdo->bindParam(':name', $name);
$pdo->bindParam(':date', $date);
$pdo->bindParam(':recipe_id', $recipe_id);
$pdo->execute();
}
Try the following:
$(document).on('click', '.editThis',function() {...});
$(document).on('click','#editRecipe',function() {...});
Try this onclik function
Some time you cant get the apt value from this So Try this method.
we can use id but in your case you foreach the a tag so we cant repeat id. Hope Its Works
<a data-toggle="modal" class="recipe_<?php echo $value['recipe_id']; ?> edit editThis" onclick="editRecipe('<?php echo $value['recipe_id']; ?>')" ><i class="fa fa-pencil"></i></a>
function editRecipe(txt) {
var recipe_id = $('.recipe_'+txt).val();
var name_input = $('#name').val();
var date_input = $('#date').val();
var request = $.ajax({
url: "ajax/updateRecipe.php",
type: "post",
data: {name : name_input, date : date_input, recipe_id : recipe_id},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
};

How to send data from PHP to HTML

Is there any way to send data from php to html without refreshing page.
i open html to upload images..
so i will go to process.php and i got target-path of that images when it has success uploaded.
my problem is. how can i send that target-path to my html back without refreshing page.
This is my javascript:
function startUpload(){
..
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
.. //get data from php
} else {
..
}
return true;
}
process.php
$destination_path = "../dir/";
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
//$target-path need to send to input in html
}
sleep(1);
My suggestion would be ajax. It's cleaner and efficient.
Example is how you parse the data
This is for HTML to PHP
$('#submit').click(function()
{
$.ajax({
url: send_email.php,
type:'POST',
data:
{
email: email_address,
message: message
},
success: function(msg)
{
alert('Email Sent');
}
});
});
If you want to pass a value from PHP to HTML
An example would be :
<?php
if( isset($_GET['submit']) )
{
//be sure to validate and clean your variables
$val1 = htmlentities($_GET['val1']);
$val2 = htmlentities($_GET['val2']);
//then you can use them in a PHP function.
$result = myFunction($val1, $val2);
}
?>
<?php if( isset($result) ) echo $result; //print the result above the form ?>
<form action="" method="get">
Inserisci number1:
<input type="text" name="val1" id="val1"></input>
<?php echo "ciaoooo"; ?>
<br></br>
Inserisci number2:
<input type="text" name="val2" id="val2"></input>
<br></br>
<input type="submit" name="submit" value="send"></input>
</form>
In your case it would be :
$destination_path = "../dir/";
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
$val1 = htmlentities($_GET['val1']); // this value could be obtain via HTML
}
sleep(1);
If your Javascript will handle upload event through AJAX. you can return back correct image url and append back to your webpage.
Try this before add jquery to your html page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Html Form:
<span id="returnImage"></span>
<form id="uploadImage">
<label id="img">Upload Image<label>
<input name="images" type="file" class="img"/>
<input type="submit"/>
</form>
JS:
$("#uploadImage").submit(function(e){
e.preventDefault();
var data = new FormData();
$.each($('.img'), function(i, obj) {
$.each(obj.files,function(j, file){
data.append('upload_files['+i+']', file);
});
});
$.ajax({
type: 'post',
data: data,
url: "image_processor.php",
cache: false,
contentType: false,
processData: false,
success: function(data){
var dataArray = $.parseJSON(data);
$("#returnImage").html('<img src="'+dataArray["img"]+'"/>')
});
});
});
image_processor.php
<?php
$array_add_counter = 0;
foreach ($_FILES['upload_files']['name'] as $imageNameArray){
$NewImage[$array_add_counter]['name'] = $imageNameArray;
$array_add_counter++;
}
$array_add_counter = 0;
foreach ($_FILES['upload_files']['type'] as $imageTypeArray){
$NewImage[$array_add_counter]['type'] = $imageTypeArray;
$array_add_counter++;
}
$array_add_counter = 0;
foreach ($_FILES['upload_files']['tmp_name'] as $imageTmpArray){
$NewImage[$array_add_counter]['tmp_name'] = $imageTmpArray;
$array_add_counter++;
}
$array_add_counter = 0;
foreach ($_FILES['upload_files']['error'] as $imageErrorArray){
$NewImage[$array_add_counter]['error'] = $imageErrorArray;
$array_add_counter++;
}
$array_add_counter = 0;
foreach ($_FILES['upload_files']['size'] as $imageSizeArray){
$NewImage[$array_add_counter]['size'] = $imageSizeArray;
$array_add_counter++;
}
foreach ($NewImage as $images) {
move_uploaded_file($images["tmp_name"], "ImageLocation/".$images["name"]);
$return['img'] = "ImageLocation/".$images["name"];
}
echo json_encode($return);
?>
I tested and it work in my localhost.

How to upload multiple image with Ajax?

I have a website using the Kohana framework. I have a problem when I tried upload multiple image using AJAX. I tried with many methods but without success. I think the problem is in function _save_images($image) at line:
if ($file = Upload::save($image, NULL, $directory))
Because I tried echo this values but receive result like:
Website not support width less than 900px on Computer
A function to save image with parameter $image is array list image.
In ProductImage.php:
protected function _save_images($image)
{
$directory = DOCROOT.'uploads/';
if ($file = Upload::save($image, NULL, $directory))
{
$filename = strtolower(Text::random('alnum', 20)).'.jpg';
Image::factory($file)
->resize(200, 200, Image::AUTO)
->save($directory.$filename);
// Delete the temporary file
unlink($file);
return $filename;
}
}
And I have a function to upload multiple image.
public function action_create()
{
$user = Auth_Jelly::instance()->get_user();
$iduser = $user->id;
if($user->has_role('admin') || $user->check_permission($iduser,'CREATE_PRODUCT')==1){
$this->auto_render = false;
if(Request::$is_ajax)
{
$name_img = Security::xss_clean($_POST['name_img']);
$type_img = Security::xss_clean($_POST['type_img']);
$size_img = Security::xss_clean($_POST['size_img']);
$new_array = array();
foreach($name_img as $item){
$new_array['name'][] = $item;
}
foreach($type_img as $item){
$new_array['type'][] = $item;
}
foreach($size_img as $item){
$new_array['size'][] = $item;
}
$files = $new_array;
unset($new_array);
$ilosc = count($files['name'])-1;
for($i=0; $i<=$ilosc; $i++) {
$_FILES['image_list'.$i]['name'] = $files['name'][$i];
$_FILES['image_list'.$i]['type'] = $files['type'][$i];
$_FILES['image_list'.$i]['size'] = $files['size'][$i];
$array_new[] = array(
'name'=>$_FILES['image_list'.$i]['name'],
'type'=>$_FILES['image_list'.$i]['type'],
'error'=>0,
'size'=>$_FILES['image_list'.$i]['size'],
);
}
foreach ($array_new as $key => $value) {
$this->_save_images($value);
if($this->save_images($value)==FALSE){
echo "Faild Upload";
}else{
echo "Upload Success";
}
}
}
}else{
// Request::current()->redirect('admin/home/denied');
}
}
And in ProductImage.js:
$("#"+form).click(function(){
var image_list = Array();
var imageFiles = document.getElementById("image_list"),
filesLength = imageFiles.files.length;
for (var i = 0; i < filesLength; i++) {
image_list[i] = imageFiles.files[i].name;
}
var myFileList = document.getElementById('image_list').files;
var file ;
var name_img= Array();
var type_img= Array();
var size_img= Array();
// loop through files
for (var i = 0; i < myFileList.length; i++) {
// get item
file = myFileList.item(i);
//or
file = myFileList[i];
name_img[i]= file.name;
type_img[i]= file.type;
size_img[i]= file.size;
}
var local = window.location;
var val_content = tinyMCE.editors[0].getContent();
var language = $.trim($('#product-create-language option:selected').val());
var category = $.trim($('input[name=category]').val());
var status = $.trim($('input[name=createstatus]:checked').val());
var position = $.trim($('input[name=createposition]:checked').val());
var matches = [];
$(".addcheck:checked").each(function() {
matches.push(this.value);
});
if(matches.length>0)
matches=matches;
else
matches=null;
if(validateSpace(title,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",titleinfo) && validateSpace(image,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imageinfo) && validateSpace(imagebig,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imagebiginfo) && validateSpace(imagemobile,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imagemobileinfo) && validateSpace(keywords,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",keywordsinfo) && validateSpace(description,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",descriptioninfo) && validateSpace(date,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",dateinfo)){
var data = {name_img:name_img,type_img:type_img,size_img:size_img,category:category,mycolor: matches,language:language,title:$("#"+title).val(),image:$("#"+image).val(),imagebig:$("#"+imagebig).val(),imagemobile:$("#"+imagemobile).val(),fileupload:$("#"+fileupload).val(),price:$("#"+price).val(),pricesale:$("#"+pricesale).val(),idproduct:$("#"+idproduct).val(),color:$("#"+color).val(),packing:$("#"+packing).val(),cbmpsc:$("#"+cbmpsc).val(),size:$("#"+size).val(),container:$("#"+container).val(),excerpt:$("#"+excerpt).val(),content:val_content,keywords:$("#"+keywords).val(),description:$("#"+description).val(),date:$("#"+date).val(),status:status,position:position};
$(".product-content-create-total").fadeOut(); // hidden div content field register // children div of div class //register-form-center\\
$(".product-content-create").css("height","auto"); // set height/auto after hidden div class //register-form-center\\
$(".product-content-create-alert").html(""); // remove text div alert register // parent div of div id //register-form-content\\
$(".product-content-create-alert").css("margin-bottom","25px");
$(".product-content-create-alert").fadeIn("slow");
$(".product-content-create-alert").html('<img src="'+base_url+'themes/admin/images/loader.gif" alt="loader">');
$.ajax({
url: admin_url +"product/create",
type: "POST",
data: data,
cache: false,
success: function(html) {
console.log(html);
}
});
}else{
return false;
}
});
});
That seem many code, so, I hope anyone can be help me.
Updated:
Here my code of form include submit button:
<form enctype="multipart/form-data" name="form-product-create" method="post">
<input type="file" id="image_list" name="image_list[]" multiple>
<input type="button" name="btnproductcreateclick" value=" " id="btn-product-create-click" style="margin-left:119px;" class="form-btn-create-click" />
</form>
HTML
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" value="Upload File" id="upload"/>
</form>
Javascript
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
PHP
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Ajax
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
})
Source : How to upload multiple files using PHP, jQuery and AJAX
In your code error looks like near,
foreach ($array_new as $key => $value) {
$this->_save_images($value);
if($this->save_images($value)==FALSE){
echo "Faild Upload";
}else{
echo "Upload Success";
}
}
when you call $this->_save_images($value); you don't save file name for uploaded image. $file_name = $this->_save_images($value); and than save this $file_name,
foreach ($array_new as $key => $value) {
$file_name= $this->_save_images($value);
if($this->save_images($file_name)==FALSE){
echo "Faild Upload";
}else{
echo "Upload Success";
}
}
HTML form must be have the “method” attribute with the “post” value. Because the file will only send to the server when the value of the method attribute of the form is post.
<form method="post" name="multiple_upload_form" id="multiple_upload_form" enctype="multipart/form-data" action="upload.php">
<input type="hidden" name="image_form_submit" value="1"/>
<label>Choose Image</label>
<input type="file" name="images[]" id="images" multiple >
<div class="uploading none">
<label> </label>
<img src="uploading.gif"/>
</div>
</form>
PHP
Demo

Using only one js file for multiple php ajax calls

First of all, my intention is to have 1 js file where there are multiple ajax calls. I want these ajax calls, which are php files, to have the same js file inside of it but not doing another request, which makes it to run slow after any click.
Some of my main php file:
<head>
<script src="<?php echo $_SESSION['url'] ?>js/direcinfo.js"></script>
</head>
<body>
<div class="direcciones">
<a href="javascript:void(0)" id="c_menu_direcciones" class="c-menu c_menu_direcciones">
<p>
Direcciones
</p>
</a>
</div>
<div id="cuenta_menu_direcciones" class="c-menu-content">
<h1>Direcciones de correo</h1>
<div id="expand_wrapper_dir">
</div>
</div>
</body>
Js file (direcinfo.js):
$('#c_menu_direcciones').click(function(){
$.ajax({
dataType: "html",
type: "POST",
url: "direcalias.php",
success: function(cntnt){
$("#expand_wrapper_dir").html(cntnt);
}
});
return false;
});
$(".alias-dir-a").click(function(){
var useremail=$("#useremail").val();
var alias=$(this).html();
if(alias==="+")
{
$.ajax({
dataType: "html",
type: "POST",
url: "direcnew.php",
data: "email="+useremail,
success: function(cntnt){
$("#direc-content").html(cntnt);
}
});
return false;
}
});
Ajax loaded file (direcalias.php)
<?php
session_start();
header("Content-Type: text/html; charset=ISO-8859-1");
include_once 'connection.php';
$conn = bbddconnect();
$email=$_SESSION['useremail'];
$query = "SELECT CODIDIR,ALIAS"
. " FROM CLIENTE C,DIRECCION D"
. " WHERE EMAIL LIKE '$email' AND C.CODICNT = D.CODICNT;";
$result3 = mysqli_query($conn,$query)or die(mysqli_error());
$recount = mysqli_num_rows($result3);
echo '<div class="menu-alias madir">';
for($i=0;$i<$recount;$i++)
{
$row = mysqli_fetch_array($result3);
echo '<div class="alias adir ali-'.$i.'">
'.$row['ALIAS'].'
</div>';
}
echo '<div class="alias adir ali-nuevo">
+
</div>
</div>
<div id="direc-content"></div>';
//echo '<script>'.
// 'var url = "'.$_SESSION['url'].'js/direcinfo.js";'.
// '$.getScript(url);'.
// '</script>';
?>
The problem I have is that when the direcalias.php file is called I need to call the js file again (edited part) because if I don't, it does not recognize when I click on $(".alias-dir-a").click(function()). Is what I want to do possible?
It beacuse you call .alias-dir-a before it create. you can use on method
$(document).on("click", ".alias-dir-a", function() {
var useremail=$("#useremail").val();
var alias=$(this).html();
if(alias==="+")
{
$.ajax({
dataType: "html",
type: "POST",
url: "direcnew.php",
data: "email="+useremail,
success: function(cntnt){
$("#direc-content").html(cntnt);
}
});
return false;
}
});

jquery onchange event not working for file uploading in php

I am using file uploading from php using jquery ajax method .I have achieved file uploading using submitting a form when clicked on a button but it doesn,t work for onchange event when input field is change . Here's the code i am using,
<div id="photo">
<img id="image" src="<?php echo $uploadedfile;?>" width=100% height=100%>
</div>
<form id="myform" method="post" enctype="multipart/form-data">
<div id="pick">Change Photo
<input type="file" name="files" id="upload">
</div>
<input type="submit" value="send" name="submit">
</form>
jquery used
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$("form#myform").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url : "main.php",
type: 'POST',
datatype : "JSON",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
$("#image").attr({
'src' : returndata.uploadedfile
});
}
});
return false;
});
</script>
php code here
<?php
$uploadedfile = "default.jpg";
if(isset($_POST['submit'])){
if(isset($_FILES["files"]["name"])){
$filename = $_FILES["files"]["name"];
$tmppath = $_FILES["files"]["tmp_name"];
$ext = pathinfo($filename,PATHINFO_EXTENSION);
$targetfile = "uploads/".basename($filename);
if($_FILES["files"]["size"] > 0)
{
if($ext == "jpg")
{
if(file_exists($targetfile)){
$uploadok = false;
$error = "file already exists";
}
else {
$uploadok = true;
}
}
else
{
$uploadok = false;
$error = "only jpg format is allowed";
}
}
else {
$uploadok = false;
$error = "filesize is too short";
}
if($uploadok == true){
move_uploaded_file($tmppath,$targetfile);
$uploadedfile = $targetfile;
$error = "no errors!";
}else{
$uploadedfile = "default.jpg";
}
header("Content-type: text/x-json");
$data = array('error'=>$error, 'uploadedfile'=>$uploadedfile);
echo json_encode($data);
exit();
}
}
?>
I want to achieve this on changing only not by clicking on a button . any idea ??
Change this:
$("form#myform").submit(function (event)
to this:
$("form#myform").change(function (event)

Categories