简体   繁体   中英

a way to access php session data from an external javascript file using DOM

I'm creating a basic web application that simulates a micro blogging site.

When the user logs on some of the account information from the MySql query result is stored in session variable to enable tracking of the user. So userID, userName, userEmail etc..

On the create post page when the user clicks submit, an externally linked javascript file begins to work, it has it's own event handlers and uses AJAX for the rest, before outputting the result to the current "create post webpage".

Obviously, when creating the post I need to store the users ID, but I can't seem to get it to pass to the AJAX.

The solution I am thinking of is to create a hidden input field, and put the users ID (numeric number) in the placeholder, then in the JS file use the DOM and call the doc.getelementby to find out what the user ID is, I can do this fine for the post Title, and post Content, but obviously want the user ID hidden, so is there a way i can keep it hidden from the user on the create post page (it currently is a php session var) and pass it to the Ajax function to create the post?

Perhaps your AJAX script could call a backend PHP file that accesses the session variables via $_SESSION['userName'], $_SESSION['userEmail'], etc. and does whatever you need it to do (eg create a post on behalf of the user).

Put another way, the PHP acts on the currently logged in user (identified by a session variable that is unaccessible to the user) and the JavaScript updates the UI based on any response you send back to it.

You could do your idea with the hidden input and just hash the user id in the hidden field. You can hash it on the server side via PHP and even post the hashed value and decrypt via PHP before saving to the database. With jQuery you can get the value of the hidden field by:

val userID = $('#userID').val();

Slightly less work than the old fashioned document.getElementById method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM