I'm having difficulty opening message content for each unique message because I'm struggling to get the PHP variable $message['id'] to a url defined in a javascript file.

My foreach loop that echos out all of the messages for the user:

foreach($mess_data as $message){

        <tr '.(($message["read"] == '0') ? 'class="unread"' : 'class=""').'>
            <td class="inbox-small-cells">
                <input type="checkbox" class="mail-checkbox">
            <td class="inbox-small-cells">'.(($message['read'] == '0') ? '<i class="icon-envelope"></i>' : '<i class="icon-eye-open"></i>').'</td>
            <td class="view-message  hidden-phone">'.$message['from'].'</td>
            <td class="view-message ">'.(($message['subject']) ? ''.$message['subject'].'' : 'This message has no subject.').' </td>
            <td class="view-message  inbox-small-cells"><!--<i class="icon-paper-clip"></i>-></td>
            <td class="view-message  text-right">'.$message['time'].' '.$message['date'].'</td>


including the JS files:

<script src="assets/plugins/jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="assets/plugins/jquery-migrate-1.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="assets/scripts/**inbox.js**"></script>

calling on the JS function:

jQuery(document).ready(function() {       



A snippet from inbox.js (the line I need to get $message['id'] into from PHP is marked out by <----)

var Inbox = function () {

var content = $('.inbox-content');
var loading = $('.inbox-loading');

var loadMessage = function (name, resetMenu) {
    var url = 'inbox_view.php?id=[I NEED TO GET UNIQUE ID HERE FROM PHP];   <---- the problem!


    $.post(url, {}, function (res) {
        if (resetMenu) {
            $('.inbox-nav > li.active').removeClass('active');
        $('.inbox-header > h1').text('View Message');




Recommended Answers

All 19 Replies

I've got this this at the moment:

I've added the unique message ID in inbox.php using:

<input class="inbox-messageId" type="hidden" value="'.$message['id'].'" />

and I'm trying to collect it in inbox.js using:

        var messageId = $('.inbox-messageId');
        var file = 'inbox_view.php?id=';
        var url = document.write(file + messageId); 

then uthe var url is called to load inbox_view.php?id=[unique message ID]

It's obviously not working. Any idead how you do this DW?

To get the value from the hidden input element you can use the .val() method, you need to make a slight modification..try...

var messageId = $('.inbox-messageId').val();
var file = 'inbox_view.php?id=';
var url = document.write(file + messageId); 

You're a god JorgeM! thank you :D that's fixed 90% of the error :) I'll keep updating this topic

please do, its important to document the fix not only for you, but others that come across this thread having a similar issue.

All I'm getting at the moment is the page loading with the content as inbox_view.php?id=4. It's not opening inbox_view.php just opening inbox.php with inbox_view.php?id=4 printed on the page. Nothing else loads or displays. Any ideas?

sorry, i was only focusing on your problem regarding getting the value from the input element.

This line here doesnt make sense or I dont understand what you were trying to do..
var url = document.write(file + messageId);

The document write is used to print something on the page. that is why you are seeing that text. sometimes people use a document write for troubleshooting just to see what the value of your variable is.

I dont know what the inbox.js code is doing overall....but lets say it works.. and you simply needed to build the URL variable, then it should be this...

var url = file + messageId;

OR this is probably more appropriate since you are trying to concatenate strings..

var url = file.concat(messageId);

Your URL variable should now be equal to "inbox_view.php?id=4". You can verify this by using the console.log() method and view the results in your browser's dev tools. I prefer this method over document.write when troubleshooting....

For example...


as seen here using Google Chrome...


Hi Jorge,

Thanks for your solution - it does work indeed. It also reveals that I've been approaching this the wrong way from the beggining. What I would like to do is create a variable on this file so it can be used in another. Whilst this is probably a simple task I'm foreign to JS. At the moment I have the variable available in JS and need to add it into a mysqli where clause.

How would one go about this?

I've thought along the lines of WHERE id = <script>document.write(messageId)</script> but this doesn't work - probably for obvious reasons that I'm unaware of.

I've done a few google searches and everyones doing it differently. I've tried allying their examples and had no luck.

How would you advise I proceed?

Thank you,

Hello m-

So I'm good with ASP.NET and MSSQL, not so much on PHP/MySQL, but regardless, the concept you are looking for should be the same. The only difference will be the syntax.

What I would like to do is create a variable on this file so it can be used in another.

I assume you mean you want to store information (in a variable) on the current page, then send this information back to the server for use in another page?

That's pretty common and there are a few ways of passing information between pages. One way is via an HTTP GET which is done by passing the data via the URL. just like in your example... inbox_view.php?id=4. On the receiving page, you just use your server side scripting to read the query string. and assign that value to a server side variable for further processing. So in ASP.NET i would get that query string like this...

C# example..

int id = Request.QueryString["id"];

I just did a quick look for PHP and its done like this...

$id = $_GET["id"];

Another method is to pass variables via POST. This is common when a form is submitted. You can continue to lookup up how to access form values by checking the PHP manual site.

in any event... once you have access to the data you passed and assigned it to a variable, you can then use that variable in your SQL statement. Again, I dont know PHP that well, but i assume something like..

WHERE id = '.${$id}.'

hope that helps...

also, some advice... in my case, i was interested in web dev and I picked up ASP.NET first which put me in a situation where I had no client-side experience. At some point I stopped the asp.net and began from the beginning. When I went back this is the path I took to get much more acquainted client side... HTML --> CSS --> JavaScript --> (then a brief overview of XML and JSON) --> HTML5 --> CSS3 --> AJAX --> jQuery.

Hi Jorge,

I'm very familiar with $_GET and I've used it thousands of times in my scripts. The issue is that the page doesn't actually get reloaded. I'm dealing with two PHP files that contain a lot of HTML. These files are simply shown and hidden by JavaScript in one single file.

The system is a mailbox, where all the action occurs without a page load.

$id = $_GET["id"] won't work as we're not executing a URL change.

Think of your inbox, you have a list of emails. When a user clicks one of those emails I need to collect the messages unique ID which is currently $messages['id'], store it as a client side variable, and then call on it when javascript has finished loading the next file in order to retreive sql data using that unique ID.

All of this occurs in inbox.php... but inbox.php shows and hides two files:
1) inbox_inbox.php <-- loops users messages
2) inbox_view.php <-- shows the content of one message.

the variable $message['id'] is available in inbox_inbox.php but not inbox_view.php. I need to store the variable client side for use. I just don't know how to store the variable in JS and then call it back in the next file for the SQL query.

I hope that's a little clearer. Thanks for your help!

A few people have told me it's this:

function jstophp(){

var javavar=document.getElementById("text").value;  

echo $phpvar;?>";

But I can't understand how I could use it as this example called on an element called rslt what wasn't a variable to begin with.

What I ultimately need to be able to do is use a javascript variable in a standard mysqli query.

Ok, so I think I have a better understanding on what you are trying to do. looking at the original post, it looks like what you are doing to load the message, and simply send message ID to the other page: inbox_view.php so that the content of the message could be displayed in some container...


A closer look at the approach shows that you are sending the info via an AJAX Post (via jQuery).

If that is the case, this doesn't seem correct to me..

$.post(url, {}, function (res) {

It should be this...

$.post('inbox_view.php', {id: messageId}, function (res) {

where messageId is a variable containing the value from the hidden field...

var messageId = $('.inbox-messageId').val();

Ok, so this passes the value to inbox_view.php. Now in the inbox_view.php code, you dont have access to $message['id'], but that is OK, because you just need to get access to the data you just sent via the AJAX POST. I beleive in PHP its like this....

$id = $_POST["id"]

Please excuse me for writing my message in such lamens terms. I am not familiar with PHP at all so I want to be clear in my thoughts. I am not trying to communicate with you in a manner which implies that you are not a competent programmer/developer. I'm learning some PHP here as we get through your issue(s).

You're such a sexy member it's unreal! You're spot on and that worked a treat. Thank you so very much

lol, thank you.. glad it resolved your issue.

Excuse me for resume this discussion, but I tested the codes and can only get the first value of the table. Where will I be missing, please?

Member Avatar

SHow the code you're using and any output that you get


foreach($result_msgINBOX as $res_msgINBOX){
            <td class="view-message  hidden-phone"><input class="inbox-messageId" type="hidden" value="<?php echo $msgID;?>" /><?php echo $msgFROM;?></td>


    var loadMessage = function (el, name, resetMenu) {
        var messageId = $('.inbox-messageId').val();
        var url = 'toks/toks_ler.php';


        $.post(url, {id: messageId}, function (res) {
                if (resetMenu) {
                    $('.inbox-nav > li.active').removeClass('active');
                $('.inbox-header > h1').text('View Message');



    return {
        //main function to initiate the module
        init: function () {
            // handle view message
            $('.inbox-content .view-message').live('click', function () {


$msgID = $_POST['id'];
echo $msgID;

The closest I could get was:

    var messageID = $('td').click(function(){
        alert( $(this).attr('id') );

But don't work too. Any idea?

Puzzle solved!!!

var messageId = el.attr('id');

Just one line! Bye!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.