简体   繁体   中英

PHP loop value sent to javascript

I'm avoiding using a database for my latest project and so I am using files and folders. I list folders of a directory as buttons and each one loads a screen with a list of files within it. I'm now trying to load in the file's contents dynamically without refresh to avoid loosing the menu (list of files shown on screen as buttons). I'm trying to use ajax but because the file buttons are created using a foreach php loop, the value I pass to javascript/ajax when I click one of the file buttons is incorrect as it always wants to pass the first button's value in the list!

Here is the PHP code:

<?php                                                                                               
        if(isset($_POST['FolderContent'])) {

            foreach (glob($_POST['FolderContent']."/*.*") as $file) {

                if(is_file($file)){                                                             
                    $fileNoExt = substr($file, 0, -4);  //Remove file extension so the menu item shows only the name of the file
                    $character = explode('/', $fileNoExt);
                    $filePathTrimmed = trim(end($character));
                    echo    "<form method='POST'>
                            <input type='submit' ID='selectBtn' value='$filePathTrimmed' onclick='return displayData();'/>
                            <input type='hidden' id='dataField' name='content' value='$file'/>
                            <input type='hidden' name='title' value='$filePathTrimmed'/>
                        </form>";

                } else {
                    echo "Files not found!";
                }
            }
        }

    ?>

And this is the JS:

<script>
function displayData()
     {

        var btnData = document.getElementByID('selectBtn').value;

        alert("The currently selected button is "+btnData);
        });

    }   
</script>

As you can see the PHP loops and creates a form for each button plus hidden fields. The JS just tries to grap the value of the button clicked and alert it. Problem is that the value is always the first file in the list.

What am I doing wrong please? If I use a class on the button instead of an ID then I will need to state the number in the array:

var btnData = document.getElementsByClassName('selectBtn')[0].value;

But this means I'd need to know the place within the array and make using the value pretty pointless.

I'm pretty stuck - or thick!

Thanks.

You need to use this inside onclick='return displayData(); and then use it in your function like below:-

Working snippet:-

 function displayData(ele){ var btnData = ele.value; alert("The currently selected button is "+btnData); return false; } 
 <form method='POST'> <input type='submit' value='hi' onclick='return displayData(this);'/> <input type='hidden' name='content' value='$file'/> <input type='hidden' name='title' value='$filePathTrimmed'/> </form> 

You are setting the same id value for each separate form. You should ensure that all the id attribute values are unique for all html elements as a rule of thumb to avoid unpredictable behaviours in the dom.

<?php                                                                                               
    if(isset($_POST['FolderContent'])) {

        foreach (glob($_POST['FolderContent']."/*.*") as $idx => $file) {

            if(is_file($file)){                                                             
                $fileNoExt = substr($file, 0, -4);  //Remove file extension so the menu item shows only the name of the file
                $character = explode('/', $fileNoExt);
                $filePathTrimmed = trim(end($character));
                echo    "<form method='POST'>
                        <input type='submit' id='selectBtn-{$idx}' value='$filePathTrimmed' onclick='return displayData(this.id);'/>
                        <input type='hidden' id='dataField' name='content' value='$file'/>
                        <input type='hidden' name='title' value='$filePathTrimmed'/>
                    </form>";

            } else {
                echo "Files not found!";
            }
        }
    }

?>

And javascript:

<script>
function displayData(clicked_id)
 {

    var btnData = document.getElementByID(clicked_id).value;
    alert("The currently selected button is "+btnData);
    return false;

}   
</script>

Solution: I used 'return false' at the end of the javascript/ajax code block, and 'this' in the php code to pass current data held in 'value' - thanks Alive to Die.

I also I made use of the 'name' attribute to store and access further data data.

PHP:

echo    "<form method='POST'>
                            <input type='submit' id='selectBtn' name='$file' value='$filePathTrimmed' onclick='return displayData(this);'/>
                        </form>";

JS:

<script>
function displayData(fileName)
     {

        var btnData =fileName.name;
        var name = fileName.value;

        $.ajax({
            type : "POST",
            url : "DisplayFileContents.php",
            data : {"data": btnData, "name": name},
            success : function(result) {

                $('.page-content').html(result);
                $('body').animate({scrollTop: 0}, 200);
            }
        });
        return false;

    };  

DisplayFileContents.php:

<?php 

$filename=$_POST['data'];   
$title = $_POST['name'];

echo "<h2>".$title."</h2>"; 
echo "<pre>";
Include $filename;
echo "</pre>";

?> 

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