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() 
            {
            }           
       });
    }));
});
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Sanju Menon
  • 625
  • 1
  • 6
  • 16
  • `data: {id: id},` – Zain Farooq Oct 07 '19 at 12:07
  • 1
    Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Dave Oct 07 '19 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`. – Martin Oct 07 '19 at 12:09
  • `var id = '';` is ok, but you not use `id` any where after that – Devsi Odedra Oct 07 '19 at 12:09
  • @Devsi, no iam not – Sanju Menon Oct 07 '19 at 12:11

2 Answers2

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() 
            {
            }           
       });
    }));
});
Devsi Odedra
  • 5,244
  • 1
  • 23
  • 37
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() 
        {
        }           
   });
}));

});

arimas
  • 21
  • 1