Danith Kumarasinghe
Danith Kumarasinghe

Reputation: 201

after searching button not working in php and jquery ajax

I have created for remove some items in php from DB. I used a search function as well. The search function mechanism is when I search something, existing table hides and searching details is shown. There is a button called remove in search and original table. Original table button is working properly in ajax.

But searched results remove button not work properly. There is no error. When I click search, results remove button not happening. Help me to solve this. My code is below. Original table remove button class is 'mybutton'. Searched button class is 'mybutton21'. Thank you.

    <form action="../PHP/searchrmvcom.php" method="post">
                    <div class="search hidden-xs hidden-sm">
                        <input type="text" placeholder="Search" id="search" name="search">
                    </div>
                    <div>
                        <input type="button" value="Search" id="searchrmvcom" name="searchrmvcom">
                        <script>
                            $("#searchrmvcom").click(function () {
                                var comname=$('#search').val();
                                $.ajax({
                                    type:"post",
                                    url:"../PHP/searchrmvcom.php",
                                    data:{comname:comname},
                                    success:function (data3) {
                                        $('#rmvcomdiv').hide();
                                        $('#ela').html(data3)
                                    }
                                });
                            });
                        </script>
                    </div>
                    </form>
                </div>
                <div class="col-md-5">
                    <div class="header-rightside">
                        <ul class="list-inline header-top pull-right">
                            <li class="hidden-xs"><a href="#" class="add-project" data-toggle="modal" data-target="#add_project">Change Password</a></li>
                        </ul>
                    </div>
                </div>
            </header>
        </div>
        <div class="user-dashboard">
            <h1>Comapny Remove</h1>
            <div class="row">
                <!-- code here -->
                <div class="col-md-10 col-md-offset-1">


                    <div class="panel panel-default panel-table">

                        <div class="panel-heading">
                            <div class="row">

                                <div class="col col-xs-6">
                                    <h3 class="panel-title">Company Removal</h3>
                                </div>

                            </div>
                        </div>

                        <div id="ela"></div>
                        <div class="panel-body" id="rmvcomdiv" name="rmvcomdiv">
                            <table class="table table-striped table-bordered table-list">
                                <thead>

                                <tr>
                                    <th>Action</th>
                                    <th>ID</th>
                                    <th>Registration number</th>
                                    <th>Company Name</th>
                                    <th>Email</th>
                                </tr>
                                </thead>
                                <tbody>

                                <?php
                                include('../PHP/dbconnection.php');
                                if (mysqli_connect_errno()) {
                                    echo "Failed to connect to MySQL: " . mysqli_connect_error();
                                }
                                $sql = "";

                                $sql = "select * from company where activation_code=1";

                                $res = mysqli_query($conn, $sql);

                                while ($row = mysqli_fetch_assoc($res)):

                                    ?>

                                    <tr>
                                        <td align="center"><button type="submit" class="btn btn-default myButton" value="<?php echo $row['companyid']; ?>" id="accept" name="accept">Remove</button></td>
                                        <td><?php echo $row['companyid']; ?></td>
                                        <td><?php echo $row['government_reg_no']; ?></td>
                                        <td><?php echo $row['company_name']; ?></td>
                                        <td><?php echo $row['email']; ?></td>
                                    </tr>

                                    <?php
                                endwhile
                                ?>

                                </tbody>
                            </table>

                        </div>

                    </div>

                </div>


            </div>
        </div>
        <script>
            $(".myButton").click(function () {
                var company_id = $(this).val();
                $.ajax({
                    type:"POST",
                    url:"../PHP/deletecompanycode.php",
                    data:{comid: company_id},
                    success:function (data) {
                        alert(data);
                        location.reload(true);
                    }

                });
            });

        </script>

        <script>
            $(".myButton21").click(function () {
                var company_id2 = $(this).val();
                $.ajax({
                    type:"POST",
                    url:"../PHP/deletecompanycode.php",
                    data:{comid: company_id2},
                    success:function (data2) {
                        alert(data2);
                        location.reload(true);
                    }

                });
            });

        </script>

deletecompanycode.php

    <?php
    include('dbconnection.php');
    $comid=$_POST['comid'];
    if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $sql2="select * from company where companyid='$comid'";
    $res2 = mysqli_query($conn, $sql2);
    $row2 = mysqli_fetch_assoc($res2);

    $sql3="delete from login where 
    username='".$row2['government_reg_no']."'";
    $sql="delete from company where companyid='$comid'";
    $sql4="delete from vacancy where companyid='$comid'";

    $conn->query($sql3);
    if ($conn->query($sql3) === TRUE && $conn->query($sql) === TRUE && $conn->query($sql4)===TRUE ) {
    echo 'Successfully Removed';
    }
    else{
    echo 'Occured Error..Try Again';
    }
    ?>

searchrmvcom.php

    <?php
    session_start();
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    require('../PHP/dbconnection.php');
    $sql="select * from company where company_name like '%".$_POST["comname"]."%' and activation_code=1";
    $res=mysqli_query($conn,$sql);
    if(mysqli_num_rows($res)>0) {
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-striped table-bordered table-list">
    <thead>

    <tr>
        <th>Action</th>
        <th>ID</th>
        <th>Registration number</th>
        <th>Company Name</th>
        <th>Email</th>
    </tr>
    </thead>
    <tbody>
<?php
while ($row = mysqli_fetch_assoc($res)) {
    ?>
        <tr>
            <td align="center"><button type="submit" class="btn btn-default myButton21" value="<?php echo $row['companyid']; ?>" id="accept" name="accept">Remove</button></td>
            <td><?php echo $row['companyid']; ?></td>
            <td><?php echo $row['government_reg_no']; ?></td>
            <td><?php echo $row['company_name']; ?></td>
            <td><?php echo $row['email']; ?></td>
        </tr>
    <?php
}
?>
    </tbody>
</table>
<?php
}
?>

Upvotes: 1

Views: 732

Answers (2)

ADyson
ADyson

Reputation: 61924

The problem is that $(".myButton21").click(function () { runs when the page loads. It finds any elements with the class "myButton" and binds the click event to them.

When your ajax runs, it destroys those buttons, and thus the events that were bound to them. It replaces them with brand new elements, which happen to have the same class, but the code to bind the event handlers does not run again.

The simplest solution is to use delegated events . With this technique you bind the event to an element higher up the DOM which does not get destroyed when the ajax is run. You then tell it to delegate the actual event down to the "myButton" class. This ensures that all elements with "myButton" class have the click event, no matter whether they existed when the page first loaded or not:

Replace

$(".myButton21").click(function () {

with

$("#ela").on("click", ".myButton21", function () {

For more information, see http://api.jquery.com/on/ under the section "Direct and delegated events"

Upvotes: 1

jeremye
jeremye

Reputation: 1388

The Problem

This event listener for ".myButton21" is running before the button is created. Therefore, the function is never bound to the button.

The Solution

Turn this javascript:

$(".myButton21").click(function () {
    var company_id2 = $(this).val();
    $.ajax({
        type:"POST",
        url:"../PHP/deletecompanycode.php",
        data:{comid: company_id2},
        success:function (data2) {
            alert(data2);
            location.reload(true);
        }
    });
});

Into the following, saving your desired onclick function for myButton21 as a variable you can call later rather than binding it now (in the same location is fine):

var myFunction = function() {
    var company_id2 = $(this).val();
    $.ajax({
        type:"POST",
        url:"../PHP/deletecompanycode.php",
        data:{comid: company_id2},
        success:function (data2) {
            alert(data2);
            location.reload(true);
        }
    });
}

And turn this:

$("#searchrmvcom").click(function () {
    var comname=$('#search').val();
    $.ajax({
        type:"post",
        url:"../PHP/searchrmvcom.php",
        data:{comname:comname},
        success:function (data3) {
            $('#rmvcomdiv').hide();
            $('#ela').html(data3)
        }
    });
});

Into this, binding the function for myButton21 on click, after the button is created:

$("#searchrmvcom").click(function () {
    var comname=$('#search').val();
    $.ajax({
        type:"post",
        url:"../PHP/searchrmvcom.php",
        data:{comname:comname},
        success:function (data3) {
            $('#rmvcomdiv').hide();
            $('#ela').html(data3);
            $(".myButton21").click(myFunction);
        }
    });
});

Post

Let me know if this works, or if I need to come up with some other solution.

Upvotes: 0

Related Questions