Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I would like to populate a jQuery listview in a PHP loop, and I attempted to do so by echoing javascript code that populates the list with a PHP variable. This is what I'm working with:

My HTML

<div data-role='page' id='feedPage'>
     <div data-role='content'>
        <ul id='pics' data-role='listview'>
        <li>test</li>
        </ul>
     </div>
</div>

and my PHP / JavaScript

echo "<script type='javascript'>
var pics = \$('#pics')
var pitem = \$('<li/>').html($myArray[element])
var plink = \$('<a/>')
pitem.append(plink)
pics.append(pitem)
pics.listview('refresh')
</script>";

but the list comes up blank. This code is running inside of a PHP for loop, and I am able to access and manipulate all the elements of $myArray just fine in PHP, but I cannot seem to populate the list. I even tried running this code with a simple .html('hello') to no avail. All I get is a blank list with the exception of the test item I hardcoded in the HTML. Is there a way to generate a list in PHP like this, and if so, how can I do it properly?

Thanks!

SOLUTION:

I got this working simply by doing <script type='text/javascript'> and .html('$myArray[element]') (notice the single quotes). This works because the javascript is running inside a PHP echo. Oh, and none of my $ needed to be escaped. Final code:

echo "<script type='text/javascript'>
var pics = $('#pics')
var pitem = $('<li/>').html('$myArray[element]')
var plink = $('<a/>')
pitem.append(plink)
pics.append(pitem)
pics.listview('refresh')
</script>";
share|improve this question
 
it's bad idea. You must you js files for this case –  imRcH Dec 16 '13 at 12:09
add comment

2 Answers

up vote 2 down vote accepted

I think the main problem is in type='javascript', it should be type='text/javascript'.

Another thing to consider is that the content of the $myArray[element] needs to be printed as a javascript string. Running $myArray = array_map('json_encode', $myArray); should do the trick.

share|improve this answer
 
The type='text/javascript' got it working for me! For the PHP variables I didn't need to do anything too special. I added my solution to the OP. –  Amru E. Dec 16 '13 at 12:10
add comment

You forgot to put your JS-code into document.ready event callback

$(document).ready(function($){
  var pics = $('#pics')
  var pitem = $('<li/>').html($myArray[element])
  var plink = $('<a/>')
  pitem.append(plink)
  pics.append(pitem)
  pics.listview('refresh')
});
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.