Viewed   85 times

From time to time I have to pass some variables from PHP to JS script. For now I did it like this:

var js-variable = "<?php echo $php-variable; ?>";

But this is very ugly and I can't hide my JS script in .js file because it has to be parsed by PHP. What is the best solution to handle this?

 Answers

2

If you don't want to use PHP to generate your javascript (and don't mind the extra call to your webserver), use AJAX to fetch the data.

If you do want to use PHP, always encode with json_encode before outputting.

<script>
    var myvar = <?php echo json_encode($myVarValue); ?>;
</script>
Friday, August 19, 2022
 
5

I've never heard of a standard way to "pass" information between PHP and Javascript, as they are a server-side and client-side language, respectively. I would personally use a hybrid of your second and third solutions.

Store the post id in a data-postindex attribute (data attributes are newish, and the "right" way to store small amounts of data). But I would still just use a JSON array for the rest, as storing lots of data in data-attributes (and escaping them!) is potentially problematic. PHP has a json_encode function that takes care of all the escaping and such for you - just build a PHP array (say, $postdata) like you normally would, and then throw this in your post template:

<script type="text/javascript">
    globalPostArray.push(<?php echo json_encode($postdata) ?>);
</script>

Where $postdata is something like the following:

$postdata = array(
    'nid' => 5,
    'authorId' => 45
    ...etc...
);

It should be easy enough to generate such an array from your existing code.

I wrote a blog post a while back about my implementation of this kind of thing, but it sounds like all you need is a pointer at json_encode.

Monday, August 8, 2022
4

This is a simple logic as follows

<li class="<?php echo (!empty($this->params['action']) && ($this->params['action']=='controlpanel') )?'active' :'inactive' ?>">
  <?php echo $this->Html->link('Dashboard', array('controller'=>'users','action' => 'controlpanel'), array('title' => 'Dashboard','class' => 'shortcut-dashboard'));?>
</li>

<li class="<?php echo (!empty($this->params['action']) && ($this->params['action']=='index') )?'active' :'inactive' ?>">
  <?php echo $this->Html->link('Contacts', array('controller'=>'contacts','action' => 'index'), array('title' => 'Contacts','class' => 'shortcut-contacts'));?></li>
Thursday, October 13, 2022
4

Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value} and get in controller

 function openPrompt()
{
var cancelled = true;

$.modal.prompt('Please enter a value:', function(value)
{

    $.ajax({
        type:"POST",
        data:{value_to_send:value}, 
        url:"/cakephp/controller/action/",
        success : function(data) {
           alert(data);// will alert "ok"

        },
        error : function() {
           alert("false");
        }
    });


    }, function()
   {

    });
    };
</script>

 public function action(){
    if( $this->request->is('ajax') ) {
     // echo $_POST['value_to_send'];
     echo   $value = $this->request->data('value_to_send');

     //or debug($this->request->data);
        echo "ok"
      die();
    }
   }

For more see accessing-post-data

Monday, December 5, 2022
3

There are broadly 3 ways to hold onto this kind of information:

Session (my suggestion for your situation)

Just stuff the data you want into the request.session dictionary; it'll persist per-user, and you can access it easily:

# view1
request.session['name1'] = male_results
request.session['userid1'] = male_pic_userid

# view2 (or elsewhere in view1)
male_results = request.session.get('name1')
male_pic_userid = request.session.get('userid1')

Advantages

  • No changes needed to your templates (except removing your now-unnecessary forms).
  • Clean URLs
  • Persists even through closing and re-opening the browser window
  • You don't need to worry about users modifying or even seeing the session data (it's way more secure)

Disadvantages

  • As with POST, page content is dictated by the URL and session data — URLs are no longer unique, and users can't share a particular page that relies on session info

Query parameters

Something like /match/?name1=foo1&userid1&name2=bar&userid2=2. You can either add these manually (<a href='/match/?name1={{ male_results }}...) or by changing your POST form to GET.

Advantages

  • These URLs can be shared and bookmarked; if it's a list with filtering options, this is probably desirable ("Here's the list of cars I like" posted to Facebook, etc.)

Disadvantages

  • As you've already noted, these can be freely modified by the user
  • Adding these to every URL is a massive pain

POST form (your current approach)

Advantages

  • A little more hidden (nothing user-visible without some kind of browser extension)
  • Slightly harder to manipulate (though don't rely on this security-through-obscurity)
  • Cleaner URLs

Disdvantages

  • Leads to "this page has expired" messages on Internet Explorer if you use your browser's "back" button ...
  • ... and "Are you sure you want to re-send this data" messages on most browsers if users try to reload any of your pages
  • All this state information will be lost if a user re-opens the page (pressing "return" in the URL bar, for instance)
  • Users can't share the exact page they're looking at; the content is partly determined by non-user-visible information
  • Adding POST data to every navigation action is a huge pain.
Saturday, December 24, 2022
 
koni
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :