Home » Php » javascript – Passing form data and file to php using ajax

javascript – Passing form data and file to php using ajax

Posted by: admin July 12, 2020 Leave a comment

Questions:

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 />";
How to&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();
    ...
});

Answer:

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)

Answer:

This line

if ($_FILES["file"]["error"] > 0)

Should be

 if ($_FILES["image"]["error"] > 0)