Good day. I have to say that a newcomer to AJAX. I rummaged through the whole Internet, but I didn’t find a worker.

Need help with data output from the database using AJAX + PHP. There are several fields in the table - id , name . There are several <button id=""> , which, when clicked, should display the corresponding name for the corresponding id .

For example, there are 2 rows in the table of the form id, name : 1, name1 , 2, name2 . When you click on the <button id="1"> name1 was displayed.

A little googling, put together something like a script that should work, but it does not work. What is wrong here?

I get buttons with id-s:

 <div id="buttons"> <?php if ($stmt = $mysqli->query('SELECT * FROM `table` ')) { while ($row = $stmt->fetch_assoc()){ echo '<button type="button" id="'; echo $row['id']; echo '">'; echo '</button>'; } } ?> </div> <div id="info"> <!-- Здесь должен быть вывод name при нажатии --> </div> 

Ajax script, which should be responsible for the output after clicking on the defined. button:

 <script> $(document).ready(function(){ $('#buttons').change(function(){ $.ajax({ type: "POST", url: "file.php", data: "buttons="+$("#buttons").val(), success: function(html){ $("#info").html(html); } }); return false; }); }); </script> 

file.php

 $query = "SELECT * FROM `table`"; if ($stmt = $mysqli->query($query)) { while ($row = $stmt->fetch_assoc()) { print $row['name']; } } 

    1 answer 1

    A little reading the documentation, a little googling, came to the only solution:

    html:

     <div id="buttons"> <?php if ($stmt = $mysqli->query('SELECT * FROM `table` ')) { while($row = $stmt->fetch_assoc()){ echo '<button type="button" id="'; echo $row['id']; echo '" onClick="func('; echo "'"; echo $row['id']; echo "'"; echo '); return false;">'; echo '</button>'; } } ?> </div> <div id="info"> <!-- Здесь должен быть вывод name при нажатии --> </div> 

    Script:

     <script> function func(id) { $.ajax({ type: "POST", url: "show.php", data: { id : id }, success: function(data) { $('#info').html('<div>'+data+'</div>'); }, error: function(request, status, errorT) { alert('error'); } }); } </script> 

    show.php

     <?php include_once 'modules/config.php'; include_once 'modules/connect.php'; $id = $_POST['id']; $query = "SELECT * FROM `projects` WHERE id = ". $id; if ($stmt = $mysqli->query($query)) { while ($row = $stmt->fetch_assoc()) { print $row['name']; } } ?> 
    • Well this is how it was necessary to google to find nothing about json - Ipatyev
    • @ Ipatiev give an example of code through json? - phen0menon