Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing form data and file to php using ajax [duplicate]

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

<form id="myForm" method ="post" enctype="multipart/form-data">
    First Name: <input type="text" name="fname" id="fname"> <br>
    Last Name: <input type="text" name="lname" id="lname"> <br>
    Email:  <input type="text" name="email" id="email"> <br>
    Image: <input type="file" name="image" id="image"> <br>
    <button type="button" name="btnSubmit" id="btnSubmit"> Submit </button>
</form>

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"] . "<br>";
}
else
{
    echo "Upload: " . $upload . "<br>";
    echo "Type: " . $type . "<br>";
    echo "Size: " . $size . " kB<br>";
}

$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
echo "You Entered <br />";
echo "<b>First Name:</b> ". $fname . "<br />";
echo "<b>Last Name:</b> ". $lname . "<br />";
echo "<b>Email:</b> ". $email . "<br />";
like image 388
Alex Clark Avatar asked Nov 01 '13 22:11

Alex Clark


2 Answers

Forms by default submit to wherever they're told. In order to stop this, you need to prevent it. Your js should look something like this:

$("form#data").submit(function(event){
    event.preventDefault();
    ...
});
like image 99
Rich Hatch Avatar answered Nov 03 '22 19:11

Rich Hatch


change the submit type button to button type and then use AJAX like this:

<button type="button" name="btnSubmit" id="btnSubmit"> Submit </button>

you need to change the jQuery Code to :

$("#btnSubmit").click(function(){
     var formData = new FormData($("#myForm"));
     $.ajax({
        type: 'POST',
        url: 'form2.php',
        data: formData,
         success: function (data) {
           alert(data)
         },
      });
  });  

and also change the code here if ($_FILES["file"]["error"] > 0) to if ($_FILES["image"]["error"] > 0)

like image 23
Aditya Vikas Devarapalli Avatar answered Nov 03 '22 19:11

Aditya Vikas Devarapalli