Ahmadz Issa Ahmadz Issa - 2 years ago 93
HTML Question

insert image into database with ajax using formData

I'm having some difficulties with uploading an image from an html form. the form should be able to send the image name with other data to php page.

I used formData instead of serialized function, since it can't handle files data.

$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);

type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
success: function (data) {



return false;

html form

<form id="insert_post" action="includes/widgets/insert.php" method="post" enctype="multipart/form-data" >

<div class="row">
<div class="medium-6 columns">
<label>First name
<input type="text" name="first_name" id="first_name" contenteditable>
<div class="medium-6 columns">
<label>Last name
<input type="text" name="last_name" id="last_name" contenteditable>

<div class="medium-12 columns">
<label>Last name
<input type="file" name="file" id="image" multiple contenteditable>
<button type="button" name="btn_add" id="btn_add" class="button btn btn-xs btn-success" >Submit</button>


php page

$connect = mysqli_connect("localhost", "root", "", "myaddboard");

echo $_POST['first_name'];
echo $_POST['last_name'];

echo $image = $_FILES['file']['name'];
echo $image_tmp = $_FILES['file']['tmp_name'];
echo 'error';

//$sql = "INSERT INTO posts(post_content, post_author) VALUES('".$_POST["first_name"]."', '".$_POST["last_name"]."')";

if(mysqli_query($connect, $sql))
echo 'Data Inserted';
} else {
echo 'error';

The php form is just to test if the ajax send the data correctly.

When I click on the button I always get errors that the php variables is not defined

The errors i get each time I submit the form

undefined index: frist_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 4
undefined index: last_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 5
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 8
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 9

what should I do to make the ajax send the data to the php page ?

Answer Source

This won't work because of how your selector is created.

$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);

In the above scenario, $(this)[0] is getting you the raw HTML interpretation of the button.

What you actually want is to change your button to a submit type, capture the form submit event, and then process your request.

button type="submit" <-- change

$(document).on('submit', '#insert_post', function(e){
    e.preventDefault(); //stop default form submission

    //do the rest of your stuff here

Now $(this)[0] is actually the form and not the button.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download