简体   繁体   中英

AJAX does not send FormData Correctly?

I'm working on something to send one image file and few data to PHP file. So I'm using a Form to do that. This is my JS code;

var pictureForm = new FormData();
var imgFile = $('#avatarSelect')[0];
pictureForm.append('email', email);
pictureForm.append('firName',editfirName);
pictureForm.append('lstName',editlstName);
pictureForm.append('newPass',editpass);
pictureForm.append('newPhn', editphnNum);
pictureForm.append('pictureFile', imgFile.files[0]);

$.ajax({
        type: "POST",
        url: "php/accountUpdate.php",
        dataType:'json',
        data:{pictureForm},
        processData: false,
        contentType: false,
        success : function(response)
        {
            if(response==1)
            {
                alert("Success");

            }
            else
            {
                alert(response);

            }
        }
    });

And accountUpdate.php;

<?php
if($_POST)
{
$userEmail= $_POST['email'];
$userPass= $_POST['newPass'];
$userPhone = $_POST['newPhn'];
$userFName= $_POST['firName'];
$userLName = $_POST['lstName'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";

// Some code
}
else
 echo json_encode("Error");
?>

My Problem

However this always alert me "Error". Means $_POST isn't set properly. I couldn't find the reason. But all the variables such as email,editfirname...etc are properly set and have values.

Also when I run that on my local server (removing PHP if($_POST) condition ) console log says undefined index : email. Any guesses?

您尚未关闭if / else语句,因此它每次都会回显错误,并使用isset($ _ POST)

Try changing the 1 with boolean value ( true )

var pictureForm = new FormData();
var imgFile = $('#avatarSelect')[0];
pictureForm.append('email', email);
pictureForm.append('firName',editfirName);
pictureForm.append('lstName',editlstName);
pictureForm.append('newPass',editpass);
pictureForm.append('newPhn', editphnNum);
pictureForm.append('pictureFile', imgFile.files[0]);

$.ajax({
        type: "POST",
        url: "php/accountUpdate.php",
        dataType:'json',
        data:{pictureForm},
        processData: false,
        contentType: false,
        success : function(response)
        {
            if(response==true)
            {
                alert("Success");

            }
            else
            {
                alert(response);

            }
        }
    });

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