0

I'm trying to get javascript to know when my PHP echoes something into an empty div. I tried the code below

<div id = "container" onchange = "changeHandle()" style = "display: none">
   <?php

      if($condition){ //condition was something from a different section of my PHP
        echo "stuff from a database";  
      }
   ?>
</div>
<script>
 function changeHandle(){
    alert("div has changed");
 }
</script>

But the changeHandle() function doesn't run. I tried looking up documentation on W3 schools about Jquery but can't find anything that could help with this (I'm also a beginner at this stuff, so maybe I misunderstood things). Any help would be appreciated!

EDIT: So Bit of context, I'm using this in conjunction with some forms. My user inputs data in some forms and I'm using PHP to query a database after they click enter, then put some of the data I get back into the container. Is there a way to take the data I echo'd and have it in JS?

Nakul Upadhya
  • 494
  • 4
  • 16
  • Check the length of `textContent` of the div, and you've also to call the function. – Teemu Apr 23 '20 at 05:12
  • @Teemu Well I trust you, but I have no idea how the OP is expecting this to work... – Alon Eitan Apr 23 '20 at 05:16
  • 2
    @AlonEitan Well, I didn't notice the `onchange` in the div tag. If OP expects that to work, then the dup really takes its place. – Teemu Apr 23 '20 at 05:17
  • I already wasted my CV :) – Alon Eitan Apr 23 '20 at 05:18
  • 1
    @Teemu the OP clearly does not understand the difference between server and client side code. Yes, this is legitimate PHP code, but the `onchange` handler isn't going to do what OP expects. – patrick3853 Apr 23 '20 at 05:20
  • @patrick3853 So how would I have JS understand what's in that container after PHP has updated the contents? – Nakul Upadhya Apr 23 '20 at 05:23
  • 1
    @NakulUpadhya PHP can't update the content, unless you're reloading the page (submitting the form to the same page). If you can confirm you're reloading, then this is solvable. – Teemu Apr 23 '20 at 05:24
  • @NakulUpadhya Maybe this is what you're looking for: https://stackoverflow.com/questions/3644585/html-change-update-page-contents-without-refreshing-reloading-the-page – patrick3853 Apr 23 '20 at 05:27

1 Answers1

2

PHP is server side code and runs on the server before the request is sent to the client. JS is client side code and runs on the client (i.e. the web browser) after the request is sent to the client.

In other words, as far as JS is concerned the value of your div hasn't changed. It was already set from PHP when the page first loaded.

patrick3853
  • 1,100
  • 9
  • 17