简体   繁体   中英

How do I include content from an external PHP page into a DIV with onlick event?

I have a form with this in it:

<button type="button" name="viewRecords" id="viewRecords" class="activeButton" onClick= 
  "<?php include ("") ?>"

I wish to populate a div with content from an external PHP file when the button is clicked.

<div id="admin-content">
<?php include ("view-records.php");?>
</div>

Is there a way to do this?

There's no way to do this directly with PHP as PHP runs when the page is generated, not in response to User Interface Events (unless you load a new page of course).

Read up on Ajax and to make things a bit easier, use jQuery, although other libraries are available.

eg with jquery/Ajax its as simple as

// Javascript

function success(data) {
    // Assuming you return raw HTML from the ajax call...
    $('#admin-content').html(data); // inserts the html into the div.
}

$.ajax({
  url: url,
  data: data, // URLencoded query string (google encodeURIComponent() if you don't know this)
  success: success,
  dataType: 'html'
});

read more: http://api.jquery.com/jquery.get/

You can use jQuery's .post method to achieve this. Make sure to include jQuery in the head of the webpage.

   $("#viewRecords").click(function() {
     $.post( "view-records.php", function( data ) {
        $( "#admin-content" ).html( data );
     });
   });

More information on the JQuery .load method here .

Alternatively, if you would like to avoid using the jQuery solutions provided by others (which are perfectly fine as well), then you can achieve the same results in pure JavaScript (just place this code somewhere in your <head> tag):

<script type="text/javascript">
    function viewRecords() {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("admin-content").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "view-records.php", true);
        xmlhttp.send();
    }
</script>

Then call the function on the onClick handler of your button:

<button type="button" name="viewRecords" id="viewRecords" class="activeButton" onClick="viewRecords();" value="View Records" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM