tags:

views:

75

answers:

3

I'm using PHP to generate some HTML,

<?php
$news = NewsDat();

foreach($news as $single_new)
{
    echo $single_new[0] . " - " . $single_new[2] . "\n";
}
?>

I want to insert the results of this to a specific div in the page <div class="main">.

How can I take the results and insert it into that div?

I cant edit the body of the page only the Header so i'm doing all this work in the header.

+1  A: 

Use the .html jQuery method to set HTML contents.

<?php
$news = NewsDat();

$html = '';
foreach($news as $single_new)
{
    $html .= $single_new[0] . " - " . $single_new[2] . "\n";
}
?>

and then in your head's script tag:

$(function() {
  $('div.main').html('<?php echo str_replace("'", "\\'", $html); ?>');
});
Cryo
But make sure to escape single quotes in `$html`.
Max Shawabkeh
Excellent point, I've updated my example.
Cryo
Great but the HTML just appears in the javascript not in the page.
danit
You would also have to escape backslashes, and `</` sequences if you're in a script block. For creating JavaScript string literals, use `json_encode`, with the `JSON_HEX_TAG` option.
bobince
Are you getting any JavaScript errors? Is there a public URL you could share so we can see what's going on?
Cryo
A: 

appendTo() would probably be the method you are looking for.

There are still multiple ways to provide the necessary data to the form.

  1. You could build the whole commands inside the header in a script tag and do the appending there
  2. you could build a javascript array holding the data and loop through it and then append the contents
  3. You could make an ajax call and pass the data as a structure easily appendable to your form

4-n.: Other ways I did not think of right now

tDo
A: 

Use the .html() jQuery to get the current then prepend the new stuff if that is what you want. put what you want in some variable $newstuff

var current = $(".main").html();
$(".main").html($newstuff + current);
Mark Schultheiss