Jelly Jelly - 5 days ago 5
Javascript Question

Jquery and AJAX post to php data attribute?

Hello I have the following AJAX code:

var formData = new FormData($('form')[0]);
$.ajax({
url: 'saveImage.php', //Server script to process data
type: 'POST',
data: formData,
processData: false,
success: function(data){
console.log(data);
}

});


It works great and it loads up the PHP page it the background like it should:

<?php
include_once "mysql_connect.php";
$imageName = mysql_real_escape_string($_FILES["Image1"]["name"]);
$imageData = '';
$imageext = '';
if($imageName != null){
$imageData = mysql_real_escape_string(file_get_contents($_FILES["Image1"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$imageSize = getimagesize($_FILES["Image1"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$FileSize = FileSize($_FILES["Image1"]["tmp_name"]);
$imageext = mysql_real_escape_string($imageSize['mime']);
}
$query=mysql_query("INSERT INTO pictures (`id`, `imagedata`, `imageext`) VALUES ('', '$imageData', '$imageext');");


echo $imageext;


?>


The only problem is that the PHP page cant find the variable Image1 which is the name of the input in the form. Have I done something wrong. I was thinking that maybe in the data parameter in the Ajax it would be something like this but correct:

data: "Image1"=formData,


Is that a thing, if not why cant my PHP see that input field?

Answer

You forgot cache and contentType properties in your Ajax function. Try that it should work :

var formData = new FormData($('form')[0]);
$.ajax({
   type: "POST",                
   url: "saveImage.php",
   processData: false,
   contentType: false,
   cache:false,
   data: formData,
   success: function(data){
        console.log(data);
    }
});
Comments