0

I have the following defined in my controller:

$data['is_amazon'] = $product->is_amazon;
$data['is_ebay']   = $product->is_ebay;

Directly below this in the controller I'm calling a .js file (jQuery).

$this->template->add_js('js/is_ebay_amazon_prouct_edit.js');

I'd like to access these php variables in my jQuery script, I've tried this approach:

var amazon = '<?php echo $is_amazon; ?>';
var ebay = '<?php echo $is_ebay; ?>';


jQuery(document).ready(function($) {

    alert(amazon);
    //alert(ebay);

});

Although this just displays my physical text in the alert, I.E:

<?php echo $is_ebay; ?>

What is the best approach here in terms of making these variables accessible in my jQuery?

1
  • 1
    You can't add the php code into js files. PHP code only run in .php files Commented Feb 26, 2016 at 11:53

3 Answers 3

3

Try this

do one thing.. you need to create two input hiddent field in view. like this

<input type='hidden' id="amazon" value="<?php echo $is_amazon; ?>" />
<input type='hidden' id="ebay" value="<?php echo $is_ebay; ?>" />

and call that value in you jquery lik this

$(document).ready(function() {

    //alert($('#amazon').val()+" "+$('#ebay').val());   

     console.log("amazon"+$('#amazon').val());
     console.log("ebay"+$('#ebay').val());    
});

now it will work for u.. try it.

Sign up to request clarification or add additional context in comments.

4 Comments

Still no joy unfortunately, the alert still displays the php code: <?=$is_amazon; ?>
wait I will update my answer
its work or not for you now.
Creating extra DOM elements just to hold on to php variables means unnecessary DOM bloat. I do not recommend this technique.
0

There is no option to directly assign php variables to javascript. To do this you need to assign assign it to html elements like,

<input type="hidden" id ="amazon" value="<?php echo $is_amazon; ?>">

We can get the value in jquery from this html element by using this code,

var amazon = $('#amazon').val();

For security reasons the php variables cant assign to javascript variables.

Comments

0

Try this

<input type="hidden" id="fromAmazon" value="<?php echo $is_amazon ?>"/>
<input type="hidden" id="fromEbay" value="<?php echo $is_ebay ?>"/>

In jquery After loading jquery.js file

jQuery(document).ready(function($) {

    var amazon = $("#fromAmazon").val();
    var ebay = $("#fromEbay").val();

    console.log("amazon",amazon);
    console.log("ebay",ebay);

});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.