skip to Main Content

when clicking (.refresh)button、how would you pass $data_name to ajax which you’ll get by for() in body field of php script?
I would like to pass the variable for selecting data from database.

2Scripts:
(1) html formated .php file>
ajax written in header field,
php for() written in body field
(2) SQL select script in php, added 
$dataname= $_POST['dataname']; 

In for() I’m getting data from DB and showing data tables, DATA A~C.
When clicking the button for each data, I would want to get the new data from data base.
I was able to get it, just writting "A" for Ajax, but I would want to pass variable for many tables.
[enter image description here][1] [1]: https://i.stack.imgur.com/zpJ7B.png

<head>
<script>
$(document).ready(function(){
  $('.refresh').click(function(){
    $.ajax({
        // 通信先ファイル名
        url: "select.php",
        type: "POST",
        data: ({"data_name": $data_name}),
        success: function(data) {
        //more code
        },
        error: function(data) {         
        //more code
        }
});
</script>
</head>
<body>
<?php
        //more code for(){  getting $data_name(A、B、C)here >
        echo <<<EOD
        <button class='refresh'>REFRESH DATA</button>
        <table class='show'></table>
EOD;
?>
</body>

2

Answers


  1. You can use a different PHP to return the JSON or the same.
    So if you want to use the same script you basically want to send a JSON with the data when your PHP script gets a POST.
    So you have to check:

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         // The request comes from Javascript doing POST
         // Query Database and return a JSON with the field "data_name"
    } else {
         // Render your form like now you're doing now, the request com from the browser loading the page
    }
    
    Login or Signup to reply.
  2. //select.php
    <?php 
     $data= $_POST["data_name"];
    
     echo  json_encode( $data);
    ?>
    
    <script>
    $(document).ready(function(){
      $('.refresh').click(function(){
        $.ajax({
            // 通信先ファイル名
            url: "select.php",
            type: "POST",
            data: ({"data_name": $data_name}),
            success: function(data) {
            
             // getting $data_name(A、B、C)here
    
    
            },
            error: function(data) {         
            //more code
            }
    });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search