Trying to get PHP/Server variable in javascript object

Right now, I have something similar to the following in my PHP file :

<form >
    First name: <input type="text" name="FirstName" value="Mickey"><br>
    Last name: <input type="text" name="LastName" value="Mouse"><br>
    </form>
<div id="submitParagraphID">
    <img src="myImage.png" alt="Success" /> Thank you for submitting your request.
</div>
<div class="row"style="margin-top: 15px;" >
    <div class="col-sm-3" id="downloadSetsButtonDiv">
    <button  class="btn btn-primary" onclick="submitUsingjQuery()">Submit</button>
    </div>
</div>

And something like the following in my Javascript file :

function submitUsingjQuery(){  
            $("#submitParagraphID").show("fast");
            console.log("Is console log printing?");
            var formdata = $("form").serializeArray();
            alert(JSON.stringify(formdata));
}

And I can see the name value pair of the Javascript object. Here’s working JSFiddle example:

[{"name":"FirstName","value":"Mickey"},{"name":"LastName","value":"Mouse"}]

Since I am using PHP, I am able to get some server variables like the username of the person who has logged into the system. For example, var_dump($_SERVER['MELLON_username']); displays the username.

I am wondering how can I include the above server variable also into the javascript object so that the output would look like the following:

[{"name":"FirstName","value":"Mickey"},{"name":"LastName","value":"Mouse"},{"name":"MELLON_username":"value":"myusername"]

I want to include the server variable above so that I could call a java webservice using Ajax by sending this javascript obeject in the Ajax call.

So the important thing to note is that PHP and JS have completely seperate runtimes.

PHP is executed at the server end of the transaction, before data is sent to the browser.

Because of that, Javascript is completely unaware of anything PHP related.

BUT.

PHP is perfectly capable of echoing text into a HTML or JSON string before Javascript even sees it.

[{“name”:“FirstName”,“value”:“Mickey”},{“name”:“LastName”,“value”:“Mouse”},{“name”:“MELLON_username”:“value”:“myusername”]
=>
[{“name”:“FirstName”,“value”:“Mickey”},{“name”:“LastName”,“value”:“Mouse”},{“name”:“MELLON_username”:“value”:“<?php echo $_SERVER['MELLON_username']; ?>”]

or in form… form… (to fit into your stringify example)

<input type='hidden' name='MELLON_username' value="<?php echo $_SERVER['MELLON_username']; ?>">

Do note that anything put into the form is visible to a user’s inspection and Man in the Middle attacks, so it’s best to leave anything that is sensitive sitting in the PHP Session, and let the session exchange handle it.

2 Likes

Thanks for your reply.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.