DevSerge
DevSerge

Reputation: 41

Send file input through jquery to php

Dear programmers and rescuers,

I am facing a problem with my sign-up page. I use jquery to send all the form information to my PHP file. Now I want to add the function that people can also upload their profile picture. But, when I add it, it won't work.

This is my current code:

<script>
  $(function () {
    $('button').bind('click', function (event) {

    event.preventDefault();

      $.ajax({
        type: 'POST',
        url: '../includes/register.inc.php',
        data: $('form').serialize(),
        success: function(data){
         document.getElementById("notification").innerHTML = (data);
        }
      });
    });
  });
</script>

In my PHP file I handle it like;

$fname  = $_POST['voornaam'];
$lname  = $_POST['achternaam'];
$gebr   = $_POST['gebruikersnaam'];
$email  = $_POST['email'];
$gdatum = $_POST['gdatum'];
$pass   = $_POST['wachtwoord'];
$pass2  = $_POST['herhaal-wachtwoord'];

$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];

But my PHP code gives an error that index user_image is not defined. How can I send the file upload to my PHP file with my jquery code?

Thanks for helping me.

Kind regards, Serge

Upvotes: 1

Views: 52

Answers (2)

DevSerge
DevSerge

Reputation: 41

EDIT (MY SOLUTION):

After using Google for a while and searching every website I came to my solution. This is the code that I use now:

<script>
  $(document).on("click", "#registreer", function (e) {
    e.preventDefault();

    var formData = $("#signupform").submit(function (e) {
        return;
    });

    var formData = new FormData(formData[0]);
    $.ajax({
        url: '../includes/register.inc.php',
        type: 'POST',
        data: formData,
        success: function (data) {
            document.getElementById("notification").innerHTML = (data);
        },
        contentType: false,
        processData: false,
        cache: false
    });
    return false;
});
</script>

This works for me. It now sends the file to my PHP file. Thanks for the help, anyways. I will definitely look at your suggestion to improve it. Thanks!

Upvotes: 1

Ramon Maldio
Ramon Maldio

Reputation: 92

A while ago I did something similar and used Base64 for the images.

Below are a couple of link that can help on that matter:

https://ourcodeworld.com/articles/read/322/how-to-convert-a-base64-image-into-a-image-file-and-upload-it-with-an-asynchronous-form-using-jquery

Upload base64 image with Ajax

I hope this helps.

Ramon

Upvotes: 0

Related Questions