aryanknp
aryanknp

Reputation: 1167

Php Ajax file upload, always getting undefined index error

Submitting file through ajax not working. I have followed other posts to create this but it appears formdata is not containing the file as a result i always get the error of undefined index 'image'

<form  enctype: 'multipart/form-data'>
<div class="add_category">
<label style="font-size:20px;">Add categories</label>
<input type="text" name="category" id="category" placeholder="Enter Here" style="border-style:solid;height:30px;">
<label style="font-size:20px;">Choose image</label>
<input type="file" id="file" name="image" style="border-style:solid;height:25px;">
<button name="add_category" type="button" onclick="addcategory()" >ADD Category</button>
</br>
</br>
</div>
</form>


function addcategory(){
//var1=document.getElementById("category").value;
var formData = new FormData();

formData.append('image', $('input[id=file]')[0].files[0]); 


$.ajax({
       url : 'performcategoryserver.php',
       type : 'POST',
       enctype: 'multipart/form-data',
       data : formData,
       processData: false,  // tell jQuery not to process the data
       contentType: false,  // tell jQuery not to set contentType
       success : function(data) {
             alert(data);
       }
});

}

performcategoryserver.php:

<?php
$imagename=$_FILES['image']['name'];
echo($imagename);
?>

This always return undefined index image error ,please help.

Upvotes: 1

Views: 849

Answers (3)

aryanknp
aryanknp

Reputation: 1167

Finally found the working code, Changed this:

    <form id="myform"  enctype= 'multipart/form-data'>

Changed this:

function addcategory(){
var formData = new FormData( $("#myform")[0] );


var xhr = new XMLHttpRequest();

// Open connection
xhr.open('POST', 'performcategoryserver.php', true);

// Set up handler for when request finishes
xhr.onload = function () {
    if (xhr.status === 200) {
        //File(s) uploaded
        alert(xhr.responseText);
    } else {
        alert('An error occurred!');
    }
};

// Send data
xhr.send(formData);
}

Upvotes: 1

Tarık Filiz
Tarık Filiz

Reputation: 11

Your form tag opened in wrong way firstly can you fix that and try again ?

<form  enctype: 'multipart/form-data'>

Should be

<form method="post" enctype="multipart/form-data">

Upvotes: 1

Sachin
Sachin

Reputation: 397

Change

<form  enctype: 'multipart/form-data'> 

to

<form id="myform"  enctype= 'multipart/form-data'>

Change your function to:

function addcategory(){
var formData = new FormData( $("#myform")[0] );


$.ajax({
       url : 'performcategoryserver.php',
       type : 'POST',
       data : formData,
       async : false,
       processData: false,  // tell jQuery not to process the data
       contentType: false,  // tell jQuery not to set contentType
       dataType:"json",
       success : function(data) {
             alert(data);
       }
});

}

Upvotes: 1

Related Questions