Search code examples
javascriptphpjqueryajaxform-data

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

Solution

  • 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.