简体   繁体   中英

Variable is not passed from PHP to JavaScript

I have this snippet which loads categories

<?php
    $filtered = array_filter($categories, function($cat) {
        return $cat['name']; 
    });
    foreach (array_slice($filtered, 0, 5) as $cat) : ?>
        <li class="category">
            <a id="cat_<?php echo $cat['name']?>" href="?tag=<?php echo $cat['name']?>"><?php echo $cat['name']?></a>
        </li>

<?php endforeach ?>

And this in the JS

$(document).ready(function(){
    $('#cat_<?php $cat[0]['name'];?>').find('a').trigger('click');      
});

I'm trying to trigger a click on the first category when the categories are loaded.

I get the following HTML as output:

<ul class="navigation">
    <li class="category">
        <a id="cat_cars" href="?tag=cars">Cars</a>
    </li>                           
    <li class="category">
        <a id="cat_people" href="?tag=people">People</a>
    </li>                           
    <li class="category">
        <a id="cat_animal" href="?tag=animal">Animal</a>
    </li>                           
    <li class="category">
        <a id="cat_web" href="?tag=web">Web</a>
    </li>                           
    <li class="category">
        <a id="cat_forum" href="?tag=forum">Forum</a>
    </li>                        
</ul>

And JS:

$(document).ready(function(){   
    $('#cat_').find('a').trigger('click');     
});

Why is the cat name not passed to the JS function?

Edit: The array. It has a lot of names in it but I'm selecting 5 of them

Array
(
[0] => 
[1] => 
[2] => 
[3] => 
[4] => 
[5] => Array
    (
        [freq] => 11
        [name] => Cars
    )

[6] => 
[7] => 
[8] => 
[9] => Array
    (
        [freq] => 5
        [name] => People
    )

[10] => 
[11] => 
[12] => Array
    (
        [freq] => 22
        [name] => Animal
    )

[13] => 
[14] => Array
    (
        [freq] => 6
        [name] => Web
    )

[15] => Array
    (
        [freq] => 14
        [name] => Forum
    )

[16] => 
...
) 

Either use echo to print the variable or use short open tag: Edit, If you want the first index then:

<?php
    $array = array_slice($filtered, 0, 5);
    $test = $array[0];
?>
<?php foreach ($array as $cat) : ?>
    <li class="category">
        <a id="cat_<?php echo $cat['name']?>" href="?tag=<?php echo 
$cat['name']?>"><?php echo $cat['name']?></a>
    </li>

<?php endforeach ?>

And then:

$(document).ready(function(){
    $('#cat_<?php echo $test['name'];?>').find('a').trigger('click');      
});

First, the php:

Based on comments and later question edits, the intended filtering criteria is to only retain subarrays which contain a freq value greater than 5. To do that, here is the array_filter() syntax:

Code: ( Demo )

$filtered = array_filter($categories, function($row) { return $row['freq'] > 5; } );
$limited = array_slice($filtered, 0, 5);

foreach ($limited as $row) {
    echo "<li class=\"category\">";
        echo "<a id=\"cat_{$row['name']}\" href=\"?tag={$row['name']}\">{$row['name']}</a>";
    echo "</li>";
}

The error in your attempt to pass the first subarray's name value to javascript failed because there was no [0] index to access -- this should have been producing Notice: Undefined offset . The good news is that you don't even need to pass a variable to js if you adjust your jquery selector -- but more about that in a minute.

Now the javascript:

To trigger the click event, use click() instead of .trigger('click') .

To mitigate the issue of infinite page loads via js auto-triggered onclick event and ensure that javascript has an <a> element to click() , run a check that this isn't already a tag key in the url's querystring AND that there is at least one category to be clicked in your unordered list.

The jquery selector is .category a . This means find all of the <a> tags that have a parent with the class value of category . Then from that generated collection of elements, select the first one with [0] .

<?php 
if (!isset($_GET['tag']) && count($limited)) {  // start php condition block
    ?><script>                                 // leave php, enter js
    $(document).ready(function(){              // after the page fully loads
        $('.category a')[0].click();           // trigger the onclick event
    });
    </script><?php                             // leave js, re-enter php
}                                              // close the condition block
?>                                             // leave php if writing more html

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