ykn121 ykn121 - 5 months ago 45
PHP Question

How the javascript getElementById in another php?

I want to apply facebook login to my web application.

In order to split different parts, navigation bar, sidebar and content, into different php files, I need to use multiple

include('xxx.php');


in index.php

The script of facebook SDK is in index.php. When I use
getElementById()
in the script, it cannot find the element in
navigation.php
. The javascript can only find the element I needed when remove
include('xxx.php');
and move everything from
xxx.php
to index.php at the line that I removed
include('xxx.php');


If I want to keep using
include('xxx.php');
, how can I use
getElementById()
to find the elements in
xxx.php
when I call the function in
index.php
?

(I guess this kind of question has been asked before but I don't know how to call this kind of problem such that I don't know how to search for the solution)

Here are the codes in
index.php
:

<body>
<script>
...
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
// Logged into your app and Facebook.
document.getElementById('container').innerHTML = 'Please log ' +
'into Facebook.';
}
...
</script>
include('xxx.php');


The id
container
is in xxx.php.

Answer

Where are you calling statusChangeCallback() from? The inclusion of php files in your code takes place on the server side and is done before any output takes place. The javascript is executed in the user's browser once the completed page has been sent. So php include can not break this!

It is likely you are calling statusChangeCallback() in the wrong place so the function can not be found. You should either put the function after the call i.e. at the end of the included php content. Or you should wrap it in a document.ready function so that it is available only once the document has finished loading.