S4NDM4N
S4NDM4N

Reputation: 924

Getting data from a HTML table using JavaScript

I'm using PHP to draw a table of uses in my login system below is the HTML/PHP code,

session_start();
include_once("../iConnect/handShake.php");

$getUsers = "SELECT * FROM userlogin ORDER BY uId ASC";
$getUsersQuery = $dbConnect -> query($getUsers);
?>
<html>
<head>
    <title></title>

<!-- Style sheets   -->
    <link rel="stylesheet" type="text/css" href="../../CSS/main.css">

<!--  JavaScritps  -->
    <script language="JavaScript" type="text/javascript" src="../../jScripts/jquery-3.2.0.min.js"></script>
    <script language="JavaScript" type="text/javascript" src="../../jScripts/userListFunctions.js"></script>
</head>
<body>
<div id="divCenter" class="box">
    <div style="width: 166px; position: absolute; left: 642px; top: 20px; height: 44px;">
        <img src="../../images/logo.png" width="142" height="33">
    </div>
    <div id="mainDiv">
        <div id="navi"></div>
        <div id="infoi"></div>
        <table id="hor-minimalist-b">
            <div id="bgDimmer"></div>
            <div id="divContent"></div>
            <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">First Name</th>
                <th scope="col">Last Name</th>
                <th scope="col">Team</th>
                <th scope="col">Created By</th>
                <th scope="col">Created Date</th>
                <th scope="col"></th>
                <th scope="col"></th>
            </tr>
            </thead>
            <tbody>
            <?php while ($row = $getUsersQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
                <tr>
                    <td id="uId"><?php echo $row["uId"]; ?></td>
                    <td id="fName"><?php echo $row["fName"]; ?></td>
                    <td id="lName"><?php echo $row["lName"]; ?></td>
                    <td id="team"><?php echo $row["uTeam"]; ?></td>
                    <td id="cBy"><?php echo $row["createdBy"]; ?></td>
                    <td id="uCd"><?php echo $row["uCreateDate"]; ?></td>
                    <td><input type="button" class="uEdit" name="uEdit" id="uEdit" value="Edit" /></td>
                    <td><a href="deleteUser.php?id=<?php echo $row["uId"] ?>"><input type="button" name="uDelete" id="uDelete" value="Delete" /></a></td>
                </tr>
            <?php } ?>
            </tbody>
        </table>
    </div>
</div>
<div id="msg"></div>
</body>
</html>

Problem 1: I'm trying to use a java script to pull the user ID from the column ID it does pull it by using document.getElementById("uId").innerText but it just takes the first row only even if I click on other edit buttons.

My Java Script Code:

$(document).ready(function () {
     $('.uEdit').click(function (){
         // getUserId();
        var uId = document.getElementById("uId").innerText;
            if(window.XMLHttpRequest)
            {
                xmlhttp=new XMLHttpRequest();
            }
            else
            {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function(){
                if(xmlhttp.readyState==4 && xmlhttp.status==200){
                    document.getElementById("msg").innerHTML = xmlhttp.responseText;
                }
            };
            xmlhttp.open("POST","editUser.php?uId="+uId,true);
            xmlhttp.send();
            $('#bgDimmer').show();
            $('#divContent').show().load('editUser.php');
        });

    $(document).mouseup(function(x) {
        var container = $("#divContent"),
            dimmer = $('#bgDimmer');
        if (container.is(":visible")) {
            if (!container.is(x.target) //check if the target of the click isn't the container...
                && container.has(x.target).length === 0) {
                container.hide();
                dimmer.hide();
            }
        }
    });

    $('#close').click(function () {
        $('#bgDimmer').hide();
        $('#divContent').hide();
    });

});

Problem 2: I also have another problem with the above code it's like this when I send data to another PHP other than the editUSer.php through the same function it doesn't get submitted but when I send to another php then echo the data it just shows up but I want to just send the ID directly to the editUser.php file and fill the current existing data in to the fields.

Can some help me to solve this issue.

UPDATE: I tried the below answer but still the problem is there.

UPDATE 2: Below code is picking up the ID but it's not getting sent to the processing php for some reason can some one tell me why?.

var uId = $(this).data("uid");
// alert(uId);
$.post("test.php?uId="+uId,function() {
    $('#bgDimmer').hide();
    $('#divContent').load('test.php',function(){
        $(this).show();
        $('#bgDimmer').show();
    });
});

UPDATE 3:

SUCCESS! I managed solve the problem below is the description what happened and how I solved it.

So this what was happening with the code I posted above as you can see I was trying to send just one value to a page called editUser.php which will capture that and use it to get details from that data base and file the fields of the user editing form.

But it was not working I use @mplungjan's code but still nothing. When the form get loaded there was no data sent from the main button click event. I was echoing the sent value in editUser.php.

After almost pulling my hair out I looked at the browser console specially the network tab. Oh my god there were 2 instances where on looked like this http://editUser.php?uId=1 and the other http://editUser.php.

Actually what was happening is the first one sent the data but second one loaded in with no data which was called by the '#divContent').load('editUser.php' which led to the error undefined index due to there was no data to be captured.

Well the solution was simple and my logic was flawed (human error - Yey, I'm still human). What I've to do is to send the data via the same command which loaded the page. I still have a small code part from @mplungjan's code but rest is mine below is the solution which made it work.

$('.uEdit').click(function (){
    var uId = $(this).data("uid");       

      $('#bgDimmer').show();
      $('#divContent').show().load('editUser.php?uId='+uId);
   });
});

Hope this helps some one in future.

Upvotes: 1

Views: 921

Answers (1)

mplungjan
mplungjan

Reputation: 177684

  • IDs must be unique.
  • use jQUery and $.ajax now you have it. You are mixing DOM and jQuery in a very unhealthy manner
  • NEVER link to delete!!! One crawl of GoogleBot and your DB is empty

One example with little change

$('.uEdit').on("click",function (){
  // getUserId:
   var uId = $(this).parent().siblings(":first").text();
   $.post("editUser.php?uId="+uId,function() {
     $('#bgDimmer').show();
     $('#divContent').show().load('editUser.php');
   });
});

Better example

<td><input type="button" class="uEdit" value="Edit" 
 data-uid="<?php echo $row["uId"] ?>" /></td>
<td><input type="button" class="uDel" value="Delete" 
 data-uid="<?php echo $row["uId"] ?>" /></td>

and have

$('.uEdit').on("click",function (){
  // getUserId:
   var uId = $(this).data("uid");
   $('#bgDimmer').show();
   $('#divContent').load('editUser.php',function(){ // this is a GET!
     $(this).show();
   });
});
$('.uDel').on("click",function (){
  // getUserId:
   var uId = $(this).data("uid");
   $.post("deleteUser.php?uId="+uId,function() { // OR $.get if needed
     // show deleted         
   });
});

Upvotes: 1

Related Questions