简体   繁体   中英

How to add PHP Session variable into FormData using AJAX?

I'd like to pass a PHP session variable (called 'profileid') using FormData and AJAX. I thought this below would work, it did not. Why?

var imageData = new FormData();
imageData.append('image', $('#uploadImage')[0].files[0]);
imageData.append('profileid', <?php echo $_SESSION['profileid'];?>);

//Make ajax call here:
$.ajax({
      url: '/upload-image-results-ajax.php',
      type: 'POST',
      processData: false, // important
      contentType: false, // important
      data: imageData,
      //leaving out the rest as it doesn't pertain

You could add the profileid in the $.ajax URL parameter instead of adding it in FormData:

$(document).ready(function (e) {
    $('#uploadImageForm').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            url: "/upload-image-results-ajax.php?profileid=<?= $_SESSION['profileid']; ?>",
            type: "POST",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function(response){
                console.log("success");
                console.log(response);
            },
            error: function(response){
                console.log("error");
                console.log(response);
            }
        });
    }));

    $('#uploadImage').on("change", function() {
        $("#uploadImageForm").submit();
    });
});

Don't forget to place session_start(); at the beginning of your code.

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