Add a phparray variable inside javascript dynamically

154 views Asked by At

I am using the impromptu jquery plugin. I have options to insert html under "html" option, but i need to populate an array of values that i get from php. Iam not able to insert it.

What i want is to populate a select box with values that are in php variable. I tried with:

JSFIDDLE

var statesdemo = {
    state0: {
        title: 'Terms of Use',
        html:'<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"><tr><td><strong>Data1</strong></td><td>:</td><td id=\'Data1\'>   <select name=\'Data1\' id=\'cart_wonid\' class=\'Data1\'><?php echo $options;?> </select></td></tr></table>',
        buttons: { Cancel: false, Agree: true },
        focus: 1,
        submit:function(e,v,m,f){
            if(v){
                e.preventDefault();
                $.prompt.goToState('state1', true);
                return false;
            }
            $.prompt.close();
        }
    },

Update 1:

1- Main idea is dropddown list inside the popup.
2- I want to get the dropdown list data from the mysql query that i wrote in the server side ( php ). So without this popup, the idea @tomloprod suggested works perfectly. Now coming back to the popup, i can add html contents like

 html : '< table > < /table > '  

But i want to insert the php variable inside it like

html : '< table > < ?php $myvariable ?> < /table >'
2

There are 2 answers

0
AudioBubble On BEST ANSWER

thank God... i got the answer... its the " json_encode($options) " does the work.... Thanks you stackoverflow and thanks for the support @tomloprod & Juan Mendes

14
tomloprod On

METHOD 1: Use json_encode (recommended)

You can add a php array to a javascript array as follow:

var javascript_Array = <?php json_encode($php_Array); ?>;

METHOD 2: Put elements of php array into select directly

Try doing it directly with the array in PHP; I do not really see the need to pass it to JS...

<select name="data1" id="cart_wonid" class="Data1">
  <?php
     $len = count($options);
     for($c=0;$c<$len;$c++){
        echo '<option value="'.$options[$c].'">$options[$c]</option>';
     }
  ?>
</select>

METHOD 3: Put elements of javascript array into select

HTML:

<select name="data1" id="cart_wonid" class="Data1"> </select>

Javascript:

// Define the array
var javascript_Array = []; 

// Push elements
javascript_Array.push("Hi");
javascript_Array.push("Bye");

// Get the select with id cart_woneid
var sel = document.getElementById('cart_wonid');

// Fill the "select" with the elements of array
var i, len = javascript_Array.length;

for(i = 0; i < len; i++) {
    var opt = document.createElement('option');
    opt.innerHTML = javascript_Array[i];
    opt.value = javascript_Array[i];
    sel.appendChild(opt);
}

JSFiddle: http://jsfiddle.net/1dpud00v/