0

I have a requirement where I am looping through some objects to create tags and have to open another page after setting some session variables.

    for ($i = 0, $count = count($result_array->items); $i < $count; $i++)
    {
        $item = $result_array->items[$i];
        ?>
        <a href="" onclick="<?php itemSelected($item); ?>">View more</a>            
        <?php
    }

    function itemSelected($argItem)
    {
        $_SESSION['selected_item'] = $argItem;
        header('Location: ' . 'item-details.php');
    }
    ?>

It seems that for every loop rotation, the itemSelected() function is firing up. So basically when I'm loading this page, it is getting redirected to item-details.php.

Why is it so and how to handle that?

Nayak
  • 742
  • 6
  • 7
  • PHP runs on the server, JS runs on the users browser. You can't call PHP directly from JS. – Jonnix May 22 '16 at 08:34
  • Not from JS, Its PHP from PHP.... `count($result_array->templates)`. – Murad Hasan May 22 '16 at 08:35
  • _onclick="">_ is invalid. You need to use ajax for your desire work. – Murad Hasan May 22 '16 at 08:36
  • So the onClick() function cann't call a php function. It has to call a JS function only? i.e. - the itemSelected() would be written in a script. – Nayak May 22 '16 at 08:41
  • See this [execute-php-function-with-onclick](http://stackoverflow.com/questions/19323010/execute-php-function-with-onclick) – Murad Hasan May 22 '16 at 08:48
  • Went through the question. Getting some gist of it. I would prefer the ajax approach. Right now, I am looking in to find some way to pass some arguments ($item in my case) to the ajax function. It would be helpful if you post some snippet as an answer, so I might try to mark it as an answer. Many thanks for your help. – Nayak May 22 '16 at 09:07

0 Answers0