Monday 8 January 2018

javascript - Passing form data and file to php using ajax

This might have been asked before, but i have search on
here and on google and every answer I have read doesnt
work.



The question I have to solve is make a
form with first name, last name, email and a image. Then pass the data into a database
and upload the file also to a database. Currently my code doesnt do anything after I
press submit. Before I added the file box it would insert the data into my
database.



HTML



            id="myForm" method ="post" enctype="multipart/form-data">
First Name:

Last Name: type="text" name="lname" id="lname">
Email: name="email" id="email">

Image: name="image" id="image">




AJAX/JS



$("#btnSubmit").click(function(){

var formData = new FormData($(this)[0]);
$.ajax({

type:
'POST',
url: 'form2.php',
data: formData,
success:
function (data) {
alert(data)
},
});

});



PHP



$upload
= basename($_FILES['image']['name']);
$type = substr($upload, strrpos($upload,
'.') + 1);
$size = $_FILES['image']['size']/1024;

if
($_FILES["image"]["error"] > 0)
{
echo "Error: " .
$_FILES["image"]["error"] . " />";
}

else
{
echo "Upload: " .
$upload . "
";
echo "Type: " . $type . "
";

echo "Size: " . $size . " kB
";
}

$fname =
$_POST['fname'];
$lname = $_POST['lname'];
$email =
$_POST['email'];

echo "You Entered
";
echo
"First Name: ". $fname . "
";
echo
"Last Name: ". $lname . "
";
echo
"Email: ". $email . " />";

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...