Question

I have an input field that I want to populate with a bunch of possible sources, but I need to grab these sources from several different areas: a file on my server and some stuff that is already in jQuery.

The input field is going to show up inside an iFrame, so I have a .php that will echo some html when it is called up as a source.

<?php
$array = array('Louisville, KY', 'Denver, CO');
echo "
<html>
<head>
<link rel='stylesheet' href='//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css'>
  <script src='//code.jquery.com/jquery-1.10.2.js'></script>
  <script src='//code.jquery.com/ui/1.10.4/jquery-ui.js'></script>
  <link rel='stylesheet' href='/resources/demos/style.css'>
  <script>
  $(function() {
    var availableTags = [
      'Boston, MA',
      'New York City, NY',
      'Los Angelos, CA'
    ];
    availableTags = $.merge(availableTags, ".$array.");

    $( '#tags' ).autocomplete({
      source: availableTags
    });
  });
  </script>
  </head>
<body>
Select a voting option.
<br>
<span id='options'>
<form method='post' action='/creations/tools/poll/pollstorage.php' target='mainframe'>
<input id='tags' name='score'/>
<input type='submit' value='Vote'/>
</form>
<br>
</span>
</body>
</html>
"
?>

In the jQuery that I will be echoing to the iframe, you can see that I try to merge together an existing jQuery array and the output of a PHP array: availableTags = $.merge(availableTags, ".$array.");. I tried it and none of the jQuery works.

What am I doing wrong here? How should I go about merging the PHP array and the jQuery array?

Was it helpful?

Solution

Use json_encode():

$.merge(availableTags, ". json_encode($array).");

OTHER TIPS

You can convert php array in to json file and use it in java-Script or jquery. use php json_encode

var php_array = [<?php echo '"'.implode('","',  $array).'"' ?>];
availableTags = $.merge(availableTags,php_array );

I think the best solution is using json.

In PHP create a page than output a json data that you need:

page data.json

<?php 
    $obj['jsArray']= array('Boston, MA','New York City, NY','Los Angelos, CA');
    echo json_encode($obj);
?>

In your Html page using getJSON from load your page with json data (I am used a pseudo code not tested):

$.getJSON( "data.json", function( data ) {
  var availableTags = data.jsArray 
});

or, if you have availableTags and will add new data:

$.getJSON( "data.json", function( data ) {
  availableTags.push(data.jsArray)
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top