fpolloa
fpolloa

Reputation: 109

Change innerHTML from an external php file

I've got a script in an HTML file that runs a php file every 30 seconds. The php file is intended to change a div's innerHTML. I don't seem to find the way to replace it.

I was using load() but there are several divs I want to keep updating every 30 seconds and I don't want to make the server GET that much requests. So I'm looking for one only php get and then change the innerhtml in those several divs

This is what i've got:

HTML:

<script type="text/javascript">
$(document).ready(function () {
    $.get('php.php');
});
setInterval(function(){
    $.get('php.php');
}, 30000);
</script>

<div id="foo"></div>

php.php:

document.getElementById("foo").innerHTML = '<?php
// some php code
 ?>';

I think the problem is I'm not being able to get the element from the parent HTML file. I don't know how to solve this... Any suggestions will be more than aprecciated!

Upvotes: 1

Views: 2692

Answers (2)

epascarello
epascarello

Reputation: 207511

You are reinventing jQuery's load()

function fetchContent() {
     $("#foo").load('php.php');
     window.setTimeout(fetchContent, 30000);
}
$(fetchContent);

The server should just return the HTML content that you want to display.


EDIT

Since your comment is different from the original question.

function fetchContent() {
     $("#foo").get('php.php', function(data) {
         var html = $("<div/>").html(data);             
         $("#foo").html( html.find("#Section1").html() );
         $("#bar").html( html.find("#Section2").html() );
         $("#asd").html( html.find("#Section3").html() );
         window.setTimeout(fetchContent, 30000);
     });
}
$(fetchContent);

You would want to add an onError handler and might want to set the no cache option for the Ajax calls.

Upvotes: 2

nbsp
nbsp

Reputation: 2291

what you probably want is for your php.php to return some data, and then you use the success of the $.get to update your #foo; taking an example from http://api.jquery.com/jQuery.get/ and modifying it for your example

$.get("php.php", function( data ) {
    $( '#foo' ).html( data );
});

hope that helps :)

Upvotes: 1

Related Questions