tags:

views:

32

answers:

1

Hello everyone,

This has been driving me nuts for a few days. I am desperate for help.

I have 2 files, index.php and test.php, simplied version to follow.

index.php

<div id="div-hi"></div>
<div id="div-bye"></div>

<script>
$(document).ready(function(){ setInterval(function(){
$( function() 
{
$.ajax( 
{
url : 'test.php',
type : 'post',
success : function( resp ) 
    {
    $('#div-hi').html(resp);
    $('#div-bye').html(resp);
    }
});return false;}
);}, 1000);});  
</script>

test.php

<div id="hi">
<script type="text/javascript">
---
</script>
</div>

<div id="bye">
<script type="text/javascript">
----
</script>
</div>

I want #div-hi in index.php to contain the result of my javascript from #hi from test.php and #div-bye from index.php to contain the result from #bye from test.php.

I have ran out of ideas. Please help.

+1  A: 

Your Javascript:

You've got a few extra brackets and parens, and I don't know what the return false is doing in this case...

The format for setInterval() is

setInterval( CODE, DELAY);

using an anonymous function with $.ajax() that's:

setInterval( function() { $.ajax( ... ) }, 1000);

Also, return false is usually used to cancel defualt behavior in jQuery.... it doesn't apply here.

If your response is HTML, you can extract a div from it with find() or a context.

Try something like this:

<div id="div-hi"></div>
<div id="div-bye"></div>

<script type="text/javascript">
$(document).ready(function() { 
    setInterval(function() {
        $.ajax( 
        {
            url : 'test.php',
            type : 'post',
            success : function( resp ) 
            {
                  // Find the #hi and #bye divs in resp
                  //   and display them in #div-hi and #div-bye
                $('#div-hi').html($("#hi", resp).html());
                $('#div-bye').html($("#bye", resp).html());
            }
        });       
    } , 1000);
});  
</script>

Working jsFiddle

( note how the {}s appear after a few secs )


Extracting DIVs from a page:

Use the .load() function if you simply want to load pieces of another page onto the current page.

For example if you're on index.php and you want to grab the contents of #hi and #bye from test.php and display them in #div-hi and #div-bye

$('#div-hi').load('test.php #hi');
$('#div-bye').load('test.php #bye');

The above is two calls though, but I just wanted to illustrate the use of .load().

Peter Ajtai
Thank you for your help.
Bastien
@Bastien - You're welcome ;)
Peter Ajtai