简体   繁体   中英

AJAX Uploading Image on form submit

I'm trying to upload an image with some other variables and on the form submit, do my php code to save the image to the users profile_picture table.

I want to make my image upload in the same form as saving my data changes.

This is a picture of what it looks like so you can have a better understanding :

图像在这里

I did it before where I used the POST method, but for AJAX i'm not sure how to do it.

My Javascript code is (note that this doesn't work, I just tried having a go - It returns Illegal invocation in the console.log) :

<script>
function updateMyAccount() {
  var fd = new FormData($("#fileinfo"));
  var password = document.getElementById("myAccountNewPassword").value;
  var profilePicture = document.getElementById("myAccountNewProfilePic").value;

  $.ajax({
      type: "POST",
      url: "includes/form_submit.php",
      data: {
        SaveAccountChanges: true,
        securePassword_Val: password,
        fd
      },
      success: function(msg){
        if(msg == 1) {
          update_myAccount_success();
        } else {
          general_error_forms();
        }
      },
  });
  return false;
}
</script>

My PHP code is :

//My account AJAX POST
if(($_POST['SaveAccountChanges']) == true & isset($_POST['securePassword_Val']))
{
    $member_config->doUpdateAccountInfo($con);
}

Then my function to upload the image and save it to the database :

function doUpdateAccountInfo($con)
{
    //Upload users image to our /uploads directory
    $uploaddir        = 'uploads/';
    $uploadfile       = $uploaddir . basename($_FILES['fileToUpload']['name']);
    $save_to_database = ("uploads/" . $_FILES["fileToUpload"]["name"]);
    $normalPassword   = mysqli_real_escape_string($con, $_POST["securePassword_Val"]);
    $pwd              = password_hash($normalPassword, PASSWORD_DEFAULT);
    $username         = $_SESSION["username"];

    if(!empty($_FILES['fileToUpload']) & !empty($_POST['securePassword_Val']))
    {
        if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {} else { die('Could not upload file.<br>Contact the Administrator of the website for more infomration.'); }
        $query = "UPDATE users SET password = '$pwd', profile_picture = '$save_to_database' WHERE username='$username'";
        $result = mysqli_query($con, $query) or die('error');
        echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>password and profile picture</i></b>!</p></div>';
        //echo '1';
    }
    else if (empty($_FILES['fileToUpload']) & empty($_POST['securePassword_Val']))
    {
        $query = "UPDATE users SET password = '$pwd' WHERE username='$username'";
        $result = mysqli_query($con, $query) or die('error');
        echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>profile picture</i></b>!</p></div>';
        //echo '1';
    }
    else if (empty($_POST['securePassword_Val']) & !(empty($_FILES['fileToUpload'])))
    {
        if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) { echo 'Successfully uploaded image'; } else { die('Could not upload file.<br>Contact the Administrator of the website for more infomration.'); }
        $query = "UPDATE users SET profile_picture = '$save_to_database' WHERE username='$username'";
        $result = mysqli_query($con, $query) or die('error');
        echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>password</i></b>!</p></div>';
        //echo '1';
    }
    else if (empty($_POST['securePassword_Val']) & empty($_FILES['fileToUpload']))
    {
        $result = mysqli_query($con, $query) or die('error');
        //echo '<div class="panel -danger"><div class="panel-body"><p>You have failed to update your <b><i>password and profile picture</i></b>!</p></div>';
        echo '0';
    }
    else
    {
        //echo '<div class="panel -danger"><div class="panel-body"><p>An error occured!</p></div>';
        echo '0';
    }
}

I have looked a the link that was posted and now have this code :

<script>
function updateMyAccount() {

  var fdata = new FormData($("#data"));
  fdata.append("securePassword_Val",$("#myAccountNewPassword").val());
  fdata.append("SaveAccountChanges",true);

  $.ajax({
      type: "POST",
      url: "includes/form_submit.php",
      data: 
        //SaveAccountChanges: true,
        //securePassword_Val: password,
        fdata
      ,
      async: false,
      success: function(msg){
        if(msg == 1) {
          update_myAccount_success();
        } else {
          general_error_forms();
        }
      },
       cache: false,
       contentType: false,
       processData: false
  });
  return false;
}
</script>

How would I go about making the image upload through this method ?

Normally, I wouldn't answer this question because it gets asked many times. But I see few issues in your code, so I'm going to make an attempt.

JavaScript

(1) Ensure that you have included jQuery script

(2) Ensure that you have a form element (preferrably give it an ID attribute eg myform for referencing) and all your inputs have name attributes.

(3) Pass the native form element (not jQuery object) into FormData constructor. This will allow you to pass all the input elements with name attributes from your form -- so you don't need to manually add them. Exception is your SaveAccountChanges field that you want to pass, here you need to use FormData.append() .

(4) Set $.ajax data option to only the FormData object. Set contentType and processData options to false .

    function updateMyAccount() {
        // document.getElementById('myform') === $("#myform")[0] === myform
        var fd = new FormData($("#myform")[0]);
            fd.append('SaveAccountChanges', true);

        $.ajax({
            type: "POST",
            url: "includes/form_submit.php",
            data: fd,
            contentType: false,
            processData: false,
            success: function(msg){
                if(msg == 1) {
                    update_myAccount_success();
                } else {
                    general_error_forms();
                }
            },
        });

        return false;
    }

And this should be the minimum that you need on the client-side. When debugging, use your browser's web tools.

PHP

(6) Turn on your PHP error reporting .

(7) Learn the difference between && and & -- they are not the same.

(8) Because you are uploading using FormData, you need a stronger validation for your upload fields. $_FILES['fileToUpload'] will not be empty even when you don't select a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM