在javascript中调用变量的正确语法

I need help.

I have this piece of javascript code:

           // Upload image to sever 
        document.getElementById("upload").addEventListener("click", function(){
            var dataUrl = canvas.toDataURL("image/jpeg", 0.85);
            $("#uploading").show();
            $.ajax({
              type: "POST",
              url: "html5-webcam-save.php",
              data: { 
                 imgBase64: dataUrl,
                 user: "example",
                 userid: " USERNAME "
              }
            }).done(function(msg) {
              console.log("saved");
              $("#uploading").hide();
              $("#uploaded").show();
            });
        });
    }, false);

Within "USERNAME" I need to insert a variable to call the username of the user who is sending the photo.

What is the correct syntax? Thank You

If you really want to do what your are doing, this might help.

I am assuming you have a separate js file.

Place your USERNAME into a hidden input.

<input type="hidden" id="USERNAME" value="<? echo $USERNAME; ?>">

Then call the value and place that value in your ajax code.

var USERNAME = $('#USERNAME').val();
  1. If you use Cookie or Session:

    There isn't a difference between an AJAX request and a regular page request. It's just another request to the server. When the request is made, the PHP session might still be active and you could reuse the username from there - on server side. Same applies to cookies.

    Having that said: most of the time you simply don't need to fetch and insert the username on client-side and pass it to server-side via the ajax request.

  2. If you are not using Cookie or Session:

    Then you need a mechanism to (a) insert/pass the username or id into the page and (b) fetch it for the ajax request (this is your question).

    There are multiple ways to the transfer data from PHP to JS. One would be to use a hidden input box and insert the username as a value, like explained in the other answer. But you might also insert the username as the value of a JS variable or fill the value into a JSON element. In general, this question has been thoroughly answered before: How to pass variables and data from PHP to JavaScript?

    You find good examples on how to get the values from an input box in the following answer: https://stackoverflow.com/a/11563667/1163786 The answer also contains how to fetch the value by using jQuery Selector's, like with ID, Class or Name.

    Keep in mind, that you need to secure this, because someone could just insert another id or name into the ajax request on client-side.