简体   繁体   中英

How to get value php on ajax script onclick function using <a href [FINISH]

page one.php

code javascript: for call the function

    <script>               
    function chartmin(event) {
    var mn = event.target.value;
    var request = $.ajax({
            type: "get",
            url: "two.php",   
            data: {mn: mn}
           });

        request.done( function( msg ) {
            $("#myboxmin").html(msg); 
        });
        request.fail(function(jqXHR, textStatus) {
            alert( "Request failed: " + textStatus );
        });
    }
    </script>

This my php code:

    <?php
    include '../koneksi.php';


    $q=mysql_query("SELECT DISTINCT id_bab,name_bab FROM nama_pasal_topik") or die (mysql_error());
    while($qq=mysql_fetch_array($q)){
        $id_bab=array();
        $id_bab[]=$qq['id_bab'];
        $bab=$qq['id_bab'];
        $nama_bab=$qq['name_bab'];
        echo "<font color='blue'>".$bab."-->".$nama_bab."</font><br>";
    ?>


    <a href="#" class="leftlinks" id="mn" name="mn" onclick="chartmin(event);"  value="<?php echo $bab; ?>"><?php echo $nama_bab; ?></a>

    <?php
    }
?>

Then I want to data print on this div

  <div id="myboxmin">
  </div> <!--tutup mybox-->

page two.php

  <?php

   $mn = $_GET['mn'];
   echo $mn."tez"; 
  ?>

I want to use onclick event but I want to using a href . May you know how do it?

What you need is HIJAX (take a look at this )

Basically, as @RayonDabre said in his comment, you have to prevent the default behaviour of the a element.

Listen on a elements and prevent its behaviour with preventDefault()

$("a").click(function(e) {
    e.preventDefault();
    url = $(this).attr("href");
    $.ajax({
        url: url,
        data: yourData,
        type: "get"
    });
});

You may want to add a hash to the location url to keep track of the navigation with this inside the AJAX's success callback (or request.done(function()... in your case).

window.location.hash = hash;

where the hash variable contains the data-hash attribute that you can add on the a elements

<a href="someUrl.php" data-hash="#hashElement">Link</a>

You can retrieve the data-hash value with this

var hash = $(this).data("hash");

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