Using a href onclick to update div without reloading page?

前端 未结 4 785
长情又很酷
长情又很酷 2021-01-20 04:40

I used this existing question to help me out: HTML - Change\\Update page contents without refreshing\\reloading the page

The template-comparison.php file fetches the

4条回答
  •  死守一世寂寞
    2021-01-20 05:22

    I have a longer answer below but one thing you can do to prevent it from acting like an anchor tag is to just call event.preventDefault(); on the onclick() before your function:

    template-comparison.php

    link text
    link text 2
    

    Use AJAX like this:

    template-comparison.php

    link text
    link text 2
    

    header.php

    jQuery(document).ready(function(){
        jQuery('a.query-link').on('click', function(e){    
            //Prevent the link from working as an anchor tag
            e.preventDefault();
    
            //Make AJAX call to the PHP file/database query
            jQuery.ajax({
                url:'{PATH TO FILE}/templatecode.php',
                type:'POST',
                data:{id:jQuery(this).data('id')},
                success:function(data){
                    jQuery('#myStyle').append(data);
                }
            });
        });
    });
    

    templatecode.php

    connect_error) {
        die("Connection failed: " . $mysqli->connect_error);
    } 
    
      $ID = $_POST['ID'];
      $results = $mysqli->query("SELECT * FROM PresidentialCandidate WHERE  ID='$ID'");   
      if( $results->num_rows > 0 )
      {
       $row = mysqli_fetch_array($results,MYSQLI_ASSOC);
    
        //Instead of just echoing out the ID, you need to build the result/data that you want in the div right here. The success function of the AJAX call will append whatever you echo out here
        echo $row['ID'];
      }
    ?>
    

    BTW, I updated your PHP code to use MySQLI properly instead mixing MySQL with MySQLi.

    After seeing your site (WordPress), you're not going to want to load this in the header.php directly. One of the issues is that jQuery is being loaded AFTER this script so it doesn't have the jQuery variable to use yet when it loads. You can try by putting it in the footer.php file but the 'right' way to do it is to put it in an external script and then load it using wp_enqueue_script in your functions.php file.

提交回复
热议问题