-2

How can i get the whole row based on div ID(or something like this) using Ajax?

<div id="1">something inside</div>
<div id="2">something inside</div>
<div id="3">something inside</div>
<div id="4">something inside</div>
<div id="5">something inside</div>
<div id="6">something inside</div>
<div id="results"></div>

If someone clicks on a div, a row with the same id should be shown from the mysql. When someone clicks on the <div id="3">, it should load a row, with the id "3" from mysql into the result div.

So far i was only able to code this:

$("#smash").click(function(){
        $.ajax({
            url: "loaditems.php",
            success: function(result){
            $("#items").html(result);
        }});
    });

PHP

        <?php
        include "mysql.php";

        $sql = "SELECT * FROM SmiteItems";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
                echo "<div class='item'>";
                // Name
                echo "<h3>" . $row["name"] . "</h3>";
                // DIV INFO
                echo "<div class='info'>";
                // Picture
                echo "<img src='img/" . $row["id"] . ".png'>";
                // Table Values
                echo "<table>";
                // Power
                if($row["power"]>0) {
                    echo "<tr><td>Power:</td><td> " . $row["power"] . "</td></tr>";
                }
                // Attack Speed
                if($row["attspeed"]>0) {
                    echo "<tr><td>Attack speed:</td><td> " . $row["attspeed"] . "</td></tr>";
                }
                // Lifesteal
                if($row["lifesteal"]>0) {
                    echo "<tr><td>Lifesteal:</td><td> " . $row["lifesteal"] . "</td></tr>";
                }
                // Penetration
                if($row["penetr"]>0) {
                    echo "<tr><td>Penetration:</td><td> " . $row["penetr"] . "</td></tr>";
                }
                // Physical Def
                if($row["physdef"]>0) {
                    echo "<tr><td>Physical:</td><td> " . $row["physdef"] . "</td></tr>";
                }
                // Magical Def
                if($row["magdef"]>0) {
                    echo "<tr><td>Magical:</td><td> " . $row["magdef"] . "</td></tr>";
                }
                // Health
                if($row["health"]>0) {
                    echo "<tr><td>Health:</td><td> " . $row["health"] . "</td></tr>";
                }
                // HP regen
                if($row["hp5"]>0) {
                    echo "<tr><td>HP5:</td><td> " . $row["hp5"] . "</td></tr>";
                }
                // Movement Speed
                if($row["mspeed"]>0) {
                    echo "<tr><td>Movement:</td><td> " . $row["mspeed"] . "</td></tr>";
                }
                // Cooldown
                if($row["cdown"]>0) {
                    echo "<tr><td>Cooldown:</td><td> " . $row["cdown"] . "%</td></tr>";
                }
                // Mana
                if($row["mana"]>0) {
                    echo "<tr><td>Mana:</td><td> " . $row["mana"] . "</td></tr>";
                }
                // MP5
                if($row["mp5"]>0) {
                    echo "<tr><td>MP5:</td><td> " . $row["mp5"] . "</td></tr>";
                }
                // Crowd Control Reduction
                if($row["ccr"]>0) {
                    echo "<tr><td>CCR:</td><td> " . $row["ccr"] . "</td></tr>";
                }
                // Stack YES output
                if($row["stack"]==1) {
                    echo "<tr><td>Stack:</td><td> Yes</td></tr>";
                }
                // Item Type Aura Passive etc
                if (!empty($row["itype"])){
                    echo "<tr><td>Type:</td><td> " . $row["itype"] . "</td></tr>";
                }
                // Table Close
                echo "</table>";
                // Item description
                if (!empty($row["text"])){
                    echo "<div class='text'>";
                    //echo "<h4>Description:</h4>";
                    echo "<p>" . $row["text"] . "</p>";
                    echo "</div>";
                }
                echo "</div>"; // CLOSE DIV INFO
                echo "</div>";
            }
        } else {
            echo "<p>0 results</p>";
        }
        $conn->close();
        ?>

I know that my PHP isn't great, i just started learning it. There are also empty rows in my MySQL table, so i need to check if it's empty before adding it to the html.

BotDamian
  • 29
  • 7

2 Answers2

0

First you need an onclick event on the divs. When a div is clicked, their id will be passed to the getrow() function.

<div id="1" onclick="getrow(this.id)">something inside</div>
<div id="2" onclick="getrow(this.id)">something inside</div>
<div id="3" onclick="getrow(this.id)">something inside</div>
<div id="4" onclick="getrow(this.id)">something inside</div>
<div id="5" onclick="getrow(this.id)">something inside</div>
<div id="6" onclick="getrow(this.id)">something inside</div>
<div id="results"></div>

Here is the getrow() function. The div id is passed through the variable divid and sent to loaditems.php

function getrow(clicked_id) {
   $.ajax({
      url: "loaditems.php",
      data: {divid: clicked_id},
      success: function(data){
         $("#result").html(data);
      }
   });
}

Then just change your PHP query like this (presuming each row is represented by an incrementing ID). I have written this in PDO as this is what you should be using to keep your site secure.

$sql = $conn->("SELECT * FROM SmiteItems WHERE ID=:rowid");
$sql->bindParam(':rowid', $_POST['divid']);
$sql->execute();
if($sql->rowCount() > 0) { // if a row is returned
   while($row = $sql->fetch()) {
      // rest of your code
   }
}
The Codesee
  • 3,714
  • 5
  • 38
  • 78
  • I see this "id" attribute doesn't make sense because we use onclick attributes. So we could also do "getrow(1)" "getrow(2)" etc right? – BotDamian Mar 18 '18 at 17:56
  • @G1K777 Hi I don't really get what you mean, but yes you could do that. My line of code `getrow(this.id)` simply got the div's id without you having to type out the number for each. – The Codesee Mar 18 '18 at 17:58
  • Hi, yeah i thought you need to add an id attribute to it, i just forgot that i can pass a value from "onclick" and i didn't even knew that i can add a onclick attribute to a div. I thought it works only with buttons, forms, inputs and anchors. I let PHP add the ID numbers while fetching the database. – BotDamian Mar 18 '18 at 18:18
  • No it works. `echo "
    ";` So i got all items now with the onclick values in it. `function getitem(id) { $.ajax({ url: "loaditems.php", data: {divid: id}, success: function(result){ $("#stats").html(result); }}); }` it doens't work, no idea why.
    – BotDamian Mar 18 '18 at 18:28
  • @G1K777 Can you add `console.log(id)` after `function getitem(id) {` and then go into the console log and click one of the divs. What does it say in the console log? – The Codesee Mar 18 '18 at 18:37
  • I get this here: jQuery.Deferred exception: id is not defined @https://smite.gamecalcs.com/script.js:20:2 l@https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:29373 a/ – BotDamian Mar 18 '18 at 19:19
  • I fixed that error by adding `var id = 0` before the `$.ajax` and adding the `console.log(id)` at the end. All this inside the `getitem(id)` function. – BotDamian Mar 18 '18 at 19:29
  • @G1K777 Any chance you could upload your code somewhere and I'll take a look tomorrow? – The Codesee Mar 18 '18 at 22:06
0

First you'll need a function call on an event such as onclick on each div

<div id="1" onclick="getresult(1)">something inside</div>
<div id="2" onclick="getresult(2)">something inside</div>
<div id="3" onclick="getresult(3)">something inside</div>
<div id="4" onclick="getresult(4)">something inside</div>
<div id="5" onclick="getresult(5)">something inside</div>
<div id="6" onclick="getresult(6)">something inside</div>
<div id="results"></div>

Then use ajax in the function to fetch results from the PHP file and display it into the results div

function getresult(id){
    var xhr= new XMLHttpRequest();
    var params = "id="+id;
    var url = address of your php file
    xhr.open('POST',url,true);
    xhr.onload=function(){
    if(this.status == 200)
        var resultarray = json_decode(this.responseText);
        //now you can access the data like an array in the variable resultarray and display it however you wish
    }
    xhr.send(params);
}

In the PHP file get the id using POST variable and execute your mysql query.

require('mysql.php');
$stmt = $con->prepare("SELECT * FROM SmiteItems WHERE id=?");
$stmt->bind_param("i",$id);
$id=$POST['id'];    //get the id from post variable
$stmt->execute();
$result=$stmt->get_result();
echo json_encode($result);
Lucifyer
  • 158
  • 2
  • 11