skip to Main Content

The following code is to reload a div(with id=”r”) in the html document. At first it loads the data correctly as “Logitech”. However, on clicking the button, Fetch, which was designed to reload the data in the div mentioned above. Now I know I have not changed the value of the property $variable, and don’t expect any changes in the div to happen, but what happens actually on clicking the button Fetch is all of the data in the div disappears. Can someone tell me what changes should I do in the $("div#r").load(location.href+" div#r>*",""); part of the code(or some other part where the mistake lies, I said this because I think this is where the problem is present).

<?php
class Some_class{
public static $variable = 'Logitech';
}
?>

<div id="r"><?php echo Some_class::$variable?><?div>
<button id="t">Fetch</button>

<script>
$(document).ready(function(){
$("#t").click(function(){
        $("div#r").load(location.href+" div#r>*","");
    });
});
</script>

2

Answers


  1. $.load(url), Load data from the server and place the returned HTML into the matched elements JQuery docs – but your url does not return any content,hence the disappearing of div content. Since, content of div#r comes from php code, you can referesh content of the div by refreshing the whole page with window.location.reload();

    or implementing an API that return value of Some_class::$variable and pass API url to $("div#r").load()

    Login or Signup to reply.
  2. Your php url does not return anything so you won’t be able to reload the data.

    What I would suggest it, keep all your HTML code in index.html and write a fetchdata.php which would basically return the response (in this case – Logitech)

    And Now in index.html you could use XMLHttp or use the fancy $.get of jquery.

    <script>
           function fetchdata(){
                var xmlhttp = new XMLHttpRequest();
               xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                 document.getElementById("r").innerHTML = this.responseText;
               }
             };
             xmlhttp.open("GET","fetchdata.php",true);
             xmlhttp.send();
         }
        </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search