0

I know this is a frequent question but my case is different. Here is My code

PHP

if($mode == "All" || $mode == 'Offline')
        {
                echo "<label>By categories :</label>";
                echo elgg_view('input/pulldown',array(
                        'options' => $options_values,
                        'internalname' => 'event_type',
                        'value' => get_input('event_type'),
                        'js' => 'onchange = set_filter('. $mode .')','internalid' => 'event_cat'

                ));
        }

In same file i have written the script

Java script

function set_filter(mode){

    var url = $('#event_cat option:selected').val();
    alert(mode);    
    if ( mode == "Offline"){
    var off_url = <?php $vars['url'] ?>"pg/event_calendar/filter/?&amp;callback=true&event_type={url}&mode=offline";
    alert(off_url);
    }

}

The problem i am facing is i want to pass the "$mode" variable in "'js' => 'onchange = set_filter('. $mode .')'" function as a argument. But it saying undefined as alert in script. How to pass the variable ?

display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41
UI Dev
  • 689
  • 2
  • 9
  • 31

3 Answers3

0

You need to echo your php variable:

var off_url = "<?php echo $vars['url']; ?>pg/event etc...";

As is, your code is simply a different version of

<?php
true;

which does nothing at all except suck up a bit of cpu time.

As well, be EXTREMELY careful when directly dumping data from PHP into a javascript context. If you have ANY javascript metacharacters in the output data, you risk introducing a syntax error. In general, you should always json_encode() anything PHP is outputting, but this also depends on HOW you're inserting the PHP data into the JS code block.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • I want to pass the variable $mode in php in condition. See the onchange function. I need to pass the variable as a argument. – UI Dev Feb 15 '14 at 05:14
  • You have to remember that you're generating javascript code. Whatever PHP outputs has to be valid when the JS engine comes across it. `some_js_func()` is going to generate `some_js_func(foo)`... unless you've got a variable named `foo` in that scope, this code will fail with undefined variable. `some_js_func('');` (note the extra `'` quotes...) would work: `some_js_func('foo')`. – Marc B Feb 15 '14 at 19:20
0

Try like

var off_url = "<?php $vars['url'] ?>pg/event_calendar/filter/?&amp;callback=true&event_type={url}&mode=offline";

And in your js pass will be like

'js' => 'onchange = set_filter("'. $mode .'")'
GautamD31
  • 28,552
  • 10
  • 64
  • 85
  • I want to pass the variable $mode in php in condition. See the onchange function. I need to pass the variable as a argument. – UI Dev Feb 15 '14 at 05:14
0

Try this

'js' => 'onchange = set_filter("'. $mode .'")'
Adesh Pandey
  • 769
  • 1
  • 9
  • 22