0

I am trying to pass a PHP variable to JQUERY. I tried the following script but the var 'id' is not been passed to upload_avatar.php. Guess i am making some mistake. Can anyone help me.

$(document).ready(function (e) {
    $("#uploadForm").on('submit',(function(e) {
        e.preventDefault();
        var id = '<?php echo $id; ?>';
        $.ajax({
            url: "upload_avatar.php",
            type: "POST",
            data:  new FormData(this)
            contentType: false,
            cache: false,
            processData:false,
            success: function(data)
            {
            $("#targetLayer").html(data);
            },
            error: function() 
            {
            }           
       });
    }));
});
5
  • data: {id: id}, Commented Oct 7, 2019 at 12:07
  • 1
    Possible duplicate of What is the difference between client-side and server-side programming? Commented Oct 7, 2019 at 12:08
  • Creating a variable var id = ... does not include it in the form data that you are sending through to your PHP page. You need to explicitly add the id value into the form data, or create an object that contains your form data and the id. Commented Oct 7, 2019 at 12:09
  • var id = '<?php echo $id; ?>'; is ok, but you not use id any where after that Commented Oct 7, 2019 at 12:09
  • @Devsi, no iam not Commented Oct 7, 2019 at 12:11

2 Answers 2

2

Append your id in formData as below

$(document).ready(function (e) {
    $("#uploadForm").on('submit',(function(e) {
        e.preventDefault();
        var id = '<?php echo $id; ?>';
        var frmData = new FormData(this);
        frmData.append('id', id);
        $.ajax({
            url: "upload_avatar.php",
            type: "POST",
            data:  frmData ,
            contentType: false,
            cache: false,
            processData:false,
            success: function(data)
            {
            $("#targetLayer").html(data);
            },
            error: function() 
            {
            }           
       });
    }));
});
Sign up to request clarification or add additional context in comments.

Comments

1

change your code to:

$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
    e.preventDefault();
    var id = '<?php echo $id; ?>';
      var myFormData = new FormData();
       myFormData.append('id', id);
    $.ajax({

        url: "upload_avatar.php",
        contentType: false,
        cache: false,
        processData:false,
        data: myFormData,
        dataType: "json",

        success: function(data)
        {
        $("#targetLayer").html(data);
        },
        error: function() 
        {
        }           
   });
}));

});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.