问:
PHP jQuery ajax submit button not working
I would like to create a dynamic form with add and remove field using jquery and ajax. but unfortunately,my insert button supposedly go to insert.php wont work.When I click insert button,nothing is happened. When the insert button clicked,it will be redirect to insert.php store data inside the database.Here is my coding

repeater.js

```<code>
    jQuery.fn.extend({
        createRepeater: function (options = {}) {
            var hasOption = function (optionKey) {
                return options.hasOwnProperty(optionKey);
            };

            var option = function (optionKey) {
                return options[optionKey];
            };

            var generateId = function (string) {
                return string
                    .replace(/\[/g, '_')
                    .replace(/\]/g, '')
                    .toLowerCase();
            };

            var addItem = function (items, key, fresh = true) {
                var itemContent = items;
                var group = itemContent.data("group");
                var item = itemContent;
                var input = item.find('input,select');

                input.each(function (index, el) {
                    var attrName = $(el).data('name');
                    var skipName = $(el).data('skip-name');
                    if (skipName != true) {
                        $(el).attr("name", group + "[" + key + "]" + "[" + attrName + "]");
                    } else {
                        if (attrName != 'undefined') {
                            $(el).attr("name", attrName);
                        }
                    }
                    if (fresh == true) {
                        $(el).attr('value', '');
                    }

                    $(el).attr('id', generateId($(el).attr('name')));
                    $(el).parent().find('label').attr('for', generateId($(el).attr('name')));
                })

                var itemClone = items;

                /* Handling remove btn */
                var removeButton = itemClone.find('.remove-btn');

                if (key == 0) {
                    removeButton.attr('disabled', true);
                } else {
                    removeButton.attr('disabled', false);
                }

                removeButton.attr('onclick', '$(this).parents(\'.items\').remove()');

                var newItem = $("<div class='items'>" + itemClone.html() + "<div/>");
                newItem.attr('data-index', key)

                newItem.appendTo(repeater);
            };

            /* find elements */
            var repeater = this;
            var items = repeater.find(".items");
            var key = 0;
            var addButton = repeater.find('.repeater-add-btn');

            items.each(function (index, item) {
                items.remove();
                if (hasOption('showFirstItemToDefault') && option('showFirstItemToDefault') == true) {
                    addItem($(item), key);
                    key++;
                } else {
                    if (items.length > 1) {
                        addItem($(item), key);
                        key++;
                    }
                }
            });

            /* handle click and add items */
            addButton.on("click", function () {
                addItem($(items[0]), key);
                key++;
            });
        }
    });

</code>```

index.php

```<code><?php
//session_start();
$servername = "localhost";
$username = "root";
$password = "bptm2012";
$dbname = "icompex";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "select panel_id,panel_kp,panel_nm from mem_panel";
$result = mysqli_query($conn, $sql);
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Add Remove Panel Group and Category</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"
            integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
            crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="repeater.js" type="text/javascript"></script>

</head>
<body>
<div class="container">
    <br/>
    <h3 align="center">Kemaskini Ahli dan Kumpulan Panel Penilai</h3>
    <br/>
    <div style="width:100%; max-width: 600px; margin:0 auto;">
        <div class="panel panel-default">
            <div class="panel-heading">Menu Kumpulan dan Ahli Panel</div>
            <div class="panel-body">
                <span id="success_result"></span>
                <div id="div1"><h2></h2></div>

                <form method="post" id="repeater_form">
                    <div class="form-group">
                        <label>Pilih Group</label><br>
                        <select class="form-control" name="cat">

                            <option value="" disabled selected>Sila Pilih Kategori</option>
                            <option value="A">A - Rekabentuk Alam Bina & Rekabentuk Dalaman</option>
                            <option value="B">B - Pembinaan dan Bahan</option>
                            <option value="C">C - Mesin, Peralatan dan Proses Pergilangan</option>
                            <option value="D">D - ICT & Multimedia</option>
                            <option value="E">E - Elektrik, Elektronik dan Telekomunikasi</option>
                            <option value="F">F - Pengangkutan, Automatif & Penerbangan</option>
                            <option value="G">G - Pertanian, Alam Sekitar dan Tenaga Boleh Diperbaharui</option>
                            <option value="H">H - Pengajaran dan Pembelajaran</option>
                            <option value="I">I - Perkhidmatan dan Pemasaran Produk</option>
                        </select>
                        <label>Sila Pilih Kumpulan Panel</label><br>
                        <select name="group" class="form-control">
                            <option value="" disabled selected>Sila Pilih Kumpulan Panel</option>
                            <option value="1">Panel 1</option>
                            <option value="2">Panel 2</option>
                            <option value="3">Panel 3</option>
                            <option value="4">Panel 4</option>
                            <option value="5">Panel 5</option>
                            <option value="6">Panel 6</option>
                            <option value="7">Panel 7</option>
                            <option value="8">Panel 8</option>
                            <option value="9">Panel 9</option>
                            <option value="10">Panel 10</option>
                            <option value="11">Panel 11</option>
                            <option value="12">Panel 12</option>
                            <option value="13">Panel 13</option>
                            <option value="14">Panel 14</option>
                            <option value="15">Panel 15</option>
                        </select>
                    </div>
                    <div id="repeater">
                        <div class="repeater-heading" align="right">
                            <button type="button" class="btn btn-primary repeater-add-btn">Tambah Ahli</button>
                        </div>
                        <div class="clearfix"></div>
                        <div class="items" data-group="programming_languages">
                            <div class="item-content">
                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-md-9">
                                            <label>Pilih Nama Ahli Panel</label>
                                            <select class="form-control" data-skip-name="true" data-name="skill[]"
                                                    required>
                                                <?php
                                                echo "<option>Sila Pilih Ahli Panel</option>";
                                                if (mysqli_num_rows($result) > 0) {
                                                    // output data of each row
                                                    while ($row = mysqli_fetch_assoc($result)) {
                                                        echo '<option value="' . $row['panel_id'] . '">' . $row['panel_nm'] . '</option>';
                                                    }
                                                } else {
                                                    echo "<option>Maaf Belum ada pendaftaran ahli panel dibuat</option>";
                                                }

                                                mysqli_close($conn);
                                                ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3" style="margin-top:24px;" align="center">
                                            <button id="remove-btn" class="btn btn-danger"
                                                    onclick="$(this).parents('.items').remove()">Remove
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="clearfix"></div>
                    <div class="form-group" align="center">
                        <br/><br/>
                        <input type="submit" name="insert" class="btn btn-success" value="insert"/>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {

        $("#repeater").createRepeater();

        $('#repeater_form').on('submit', function (event) {
            event.preventDefault();
            $.ajax({
                url: "insert.php",
                method: "POST",
                data: $(this).serialize(),
                success: function (data) {
                    $('#repeater_form')[0].reset();
                    $("#repeater").createRepeater();
                    $('#success_result').html(data);
                    /*setInterval(function(){
                        location.reload();
                    }, 3000);*/
                }
            });
        });

    });

</script>
</body>
</html>
</code>```

insert.php

```<code><?php

connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

if (isset($_POST["name"])) {
    $skill = implode(", ", $_POST["skill"]);

    $data = array(
        ':panel_cat' => $_POST["cat"],
        ':panel_group' => $_POST["group"],
        ':panel_mem' => $skill
    );

    $query = "
 INSERT INTO panel_penilai
 (panel_cat, panel_group,panel_mem)
 VALUES (:panel_cat, :panel_group, :panel_mem)
 ";

    $statement = $connect->prepare($query);
    if ($statement->execute($data)) {
        echo '
  <div class="alert alert-success">
   Data Successfully Inserted
  </div>
  ';
    }
}

//?>
</code>```

答:
first in insert.php your code will run if there is a "name" parameter that is posted, whereas in the index.php form there is no field with the name "name".

so the insert.php file doesn't display any results when you post with the current form

And as reminder you forget about $ and there is a database difference between insert.php and index.php

```<code>connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
</code>```

should be

```<code>$connect = new PDO("mysql:host=localhost;dbname=icompex", "root", "bptm2012");
</code>```

and in ajax you better add error handling so that you can see the error information in the console browser

```<code>$.ajax({
    url:"insert.php",
    method:"POST",
    data:$(this).serialize(),
    success:function(data)
    {
        $('#repeater_form')[0].reset();
        $("#repeater").createRepeater();
        $('#success_result').html(data);
        /*setInterval(function(){
                    location.reload();
        }, 3000);*/
    },
    // like this
    error : function(err){
        console.log(err);
    }
});
</code>```

Body:
I would like to create a dynamic form with add and remove field using jquery and ajax. but unfortunately,my insert button supposedly go to insert.php wont work.When I click insert button,nothing is happened. When the insert button clicked,it will be redirect to insert.php store data inside the database.Here is my coding

repeater.js

    jQuery.fn.extend({
        createRepeater: function (options = {}) {
            var hasOption = function (optionKey) {
                return options.hasOwnProperty(optionKey);
            };

            var option = function (optionKey) {
                return options[optionKey];
            };

            var generateId = function (string) {
                return string
                    .replace(/\[/g, '_')
                    .replace(/\]/g, '')
                    .toLowerCase();
            };

            var addItem = function (items, key, fresh = true) {
                var itemContent = items;
                var group = itemContent.data("group");
                var item = itemContent;
                var input = item.find('input,select');

                input.each(function (index, el) {
                    var attrName = $(el).data('name');
                    var skipName = $(el).data('skip-name');
                    if (skipName != true) {
                        $(el).attr("name", group + "[" + key + "]" + "[" + attrName + "]");
                    } else {
                        if (attrName != 'undefined') {
                            $(el).attr("name", attrName);
                        }
                    }
                    if (fresh == true) {
                        $(el).attr('value', '');
                    }

                    $(el).attr('id', generateId($(el).attr('name')));
                    $(el).parent().find('label').attr('for', generateId($(el).attr('name')));
                })

                var itemClone = items;

                /* Handling remove btn */
                var removeButton = itemClone.find('.remove-btn');

                if (key == 0) {
                    removeButton.attr('disabled', true);
                } else {
                    removeButton.attr('disabled', false);
                }

                removeButton.attr('onclick', '$(this).parents(\'.items\').remove()');

                var newItem = $("
" + itemClone.html() + "
");
                newItem.attr('data-index', key)

                newItem.appendTo(repeater);
            };

            /* find elements */
            var repeater = this;
            var items = repeater.find(".items");
            var key = 0;
            var addButton = repeater.find('.repeater-add-btn');

            items.each(function (index, item) {
                items.remove();
                if (hasOption('showFirstItemToDefault') && option('showFirstItemToDefault') == true) {
                    addItem($(item), key);
                    key++;
                } else {
                    if (items.length > 1) {
                        addItem($(item), key);
                        key++;
                    }
                }
            });

            /* handle click and add items */
            addButton.on("click", function () {
                addItem($(items[0]), key);
                key++;
            });
        }
    });

index.php

<?php
//session_start();
$servername = "localhost";
$username = "root";
$password = "bptm2012";
$dbname = "icompex";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "select panel_id,panel_kp,panel_nm from mem_panel";
$result = mysqli_query($conn, $sql);
?>
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Add Remove Panel Group and Category</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>

Kemaskini Ahli dan Kumpulan Panel Penilai

Menu Kumpulan dan Ahli Panel

                <form method="post" id="repeater_form">

                        Pilih Group

                        <select class="form-control" name="cat">

                            <option value="" disabled selected>Sila Pilih Kategori</option>
                            <option value="A">A - Rekabentuk Alam Bina & Rekabentuk Dalaman</option>
                            <option value="B">B - Pembinaan dan Bahan</option>
                            <option value="C">C - Mesin, Peralatan dan Proses Pergilangan</option>
                            <option value="D">D - ICT & Multimedia</option>
                            <option value="E">E - Elektrik, Elektronik dan Telekomunikasi</option>
                            <option value="F">F - Pengangkutan, Automatif & Penerbangan</option>
                            <option value="G">G - Pertanian, Alam Sekitar dan Tenaga Boleh Diperbaharui</option>
                            <option value="H">H - Pengajaran dan Pembelajaran</option>
                            <option value="I">I - Perkhidmatan dan Pemasaran Produk</option>
                        </select>
                        Sila Pilih Kumpulan Panel

                        <select name="group" class="form-control">
                            <option value="" disabled selected>Sila Pilih Kumpulan Panel</option>
                            <option value="1">Panel 1</option>
                            <option value="2">Panel 2</option>
                            <option value="3">Panel 3</option>
                            <option value="4">Panel 4</option>
                            <option value="5">Panel 5</option>
                            <option value="6">Panel 6</option>
                            <option value="7">Panel 7</option>
                            <option value="8">Panel 8</option>
                            <option value="9">Panel 9</option>
                            <option value="10">Panel 10</option>
                            <option value="11">Panel 11</option>
                            <option value="12">Panel 12</option>
                            <option value="13">Panel 13</option>
                            <option value="14">Panel 14</option>
                            <option value="15">Panel 15</option>
                        </select>

                            <button type="button" class="btn btn-primary repeater-add-btn">Tambah Ahli</button>

                                            Pilih Nama Ahli Panel
                                            <select class="form-control" data-skip-name="true" data-name="skill[]"
                                                    required>
                                                <?php
                                                echo "<option>Sila Pilih Ahli Panel</option>";
                                                if (mysqli_num_rows($result) > 0) {
                                                    // output data of each row
                                                    while ($row = mysqli_fetch_assoc($result)) {
                                                        echo '<option value="' . $row['panel_id'] . '">' . $row['panel_nm'] . '</option>';
                                                    }
                                                } else {
                                                    echo "<option>Maaf Belum ada pendaftaran ahli panel dibuat</option>";
                                                }

                                                mysqli_close($conn);
                                                ?>
                                            </select>

                                            <button id="remove-btn" class="btn btn-danger"
                                                    onclick="$(this).parents('.items').remove()">Remove
                                            </button>

                        <input type="submit" name="insert" class="btn btn-success" value="insert"/>

                </form>

insert.php

<?php

connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

if (isset($_POST["name"])) {
    $skill = implode(", ", $_POST["skill"]);

    $data = array(
        ':panel_cat' => $_POST["cat"],
        ':panel_group' => $_POST["group"],
        ':panel_mem' => $skill
    );

    $query = "
 INSERT INTO panel_penilai
 (panel_cat, panel_group,panel_mem)
 VALUES (:panel_cat, :panel_group, :panel_mem)
 ";

    $statement = $connect->prepare($query);
    if ($statement->execute($data)) {
        echo '

   Data Successfully Inserted

  ';
    }
}

//?>

Body:
first in insert.php your code will run if there is a "name" parameter that is posted, whereas in the index.php form there is no field with the name "name".

so the insert.php file doesn't display any results when you post with the current form

And as reminder you forget about $ and there is a database difference between insert.php and index.php

connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

should be

$connect = new PDO("mysql:host=localhost;dbname=icompex", "root", "bptm2012");

and in ajax you better add error handling so that you can see the error information in the console browser

$.ajax({
    url:"insert.php",
    method:"POST",
    data:$(this).serialize(),
    success:function(data)
    {
        $('#repeater_form')[0].reset();
        $("#repeater").createRepeater();
        $('#success_result').html(data);
        /*setInterval(function(){
                    location.reload();
        }, 3000);*/
    },
    // like this
    error : function(err){
        console.log(err);
    }
});


来源: stackexchange

问:
Get data from RowCommand
I have a grid which shows product versions and have a few link buttons like edit, delete, preview etc.
On click of the edit button I want to get the Product ID and Version ID and redirect to some xyz.aspx page where the product details can be edited.

Here is how my Grid looks:

<asp:GridView ID="grdBindVersion" runat="server" AutoGenerateColumns="false"
            onrowcommand="grdBindVersion_RowCommand" >

        <RowStyle BorderStyle="Solid" BorderWidth="1px" />
        <Columns>
            <asp:BoundField datafield="HistoryId"  HeaderText="Version ID.">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

            <asp:BoundField datafield="Title" HeaderText="Title">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

             <asp:TemplateField HeaderText = "Edit">
                   <ItemTemplate>

                       <asp:LinkButton ID="Edit" runat="server" CommandArgument='<%# Container.DataItem %>'  CommandName ="Add">Edit</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Delete">
                   <ItemTemplate>
                           <asp:LinkButton ID="Delete" runat="server">Delete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Sub Page">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddSubPage" runat="server">Add Sub Page</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Rank">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddRank" runat="server">Add Rank</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Approve/DisApprove">
                   <ItemTemplate>
                           <asp:LinkButton ID="ApproveStatus" runat="server">Approve/DisApprove</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Complete">
                   <ItemTemplate>
                            <asp:LinkButton ID="Complete" runat="server">Complete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Preview">
                   <ItemTemplate>
                            <asp:LinkButton ID="Preview" runat="server">Preview</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Comment">
                   <ItemTemplate>
                            <asp:LinkButton ID="Comment" runat="server">Comment</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

        </Columns>
        </asp:GridView>
```

I am tracking the clicking on the link button  in the RowCommand event of the GridView.
Here i want to get the VersionID and ProductID and then redirect to another page.
Please help me.
I am really new to coding.
I did a bit of Google but none of the solutions are helping me.

答: Assign VersionID and ProductID as DataKeyNames of the GridView and then Pass these two values through Query Strings.</p>

ContentLicense: CC BY-SA 3.0

Title: Get data from RowCommand

Body:
I have a grid which shows product versions and have a few link buttons like edit, delete, preview etc.
On click of the edit button I want to get the Product ID and Version ID and redirect to some xyz.aspx page where the product details can be edited.

Here is how my Grid looks:

<asp:GridView ID="grdBindVersion" runat="server" AutoGenerateColumns="false"
            onrowcommand="grdBindVersion_RowCommand" >

        <RowStyle BorderStyle="Solid" BorderWidth="1px" />
        <Columns>
            <asp:BoundField datafield="HistoryId"  HeaderText="Version ID.">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

            <asp:BoundField datafield="Title" HeaderText="Title">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

             <asp:TemplateField HeaderText = "Edit">
                   <ItemTemplate>

                       <asp:LinkButton ID="Edit" runat="server" CommandArgument='<%# Container.DataItem %>'  CommandName ="Add">Edit</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Delete">
                   <ItemTemplate>
                           <asp:LinkButton ID="Delete" runat="server">Delete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Sub Page">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddSubPage" runat="server">Add Sub Page</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Rank">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddRank" runat="server">Add Rank</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Approve/DisApprove">
                   <ItemTemplate>
                           <asp:LinkButton ID="ApproveStatus" runat="server">Approve/DisApprove</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Complete">
                   <ItemTemplate>
                            <asp:LinkButton ID="Complete" runat="server">Complete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Preview">
                   <ItemTemplate>
                            <asp:LinkButton ID="Preview" runat="server">Preview</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Comment">
                   <ItemTemplate>
                            <asp:LinkButton ID="Comment" runat="server">Comment</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

        </Columns>
        </asp:GridView>

I am tracking the clicking on the link button  in the RowCommand event of the GridView.
Here i want to get the VersionID and ProductID and then redirect to another page.
Please help me.
I am really new to coding.
I did a bit of Google but none of the solutions are helping me.


问:
Images are not showing on PDF after changing application pool setting on IIS Server
We have one application hosted on Windows 2016 server and with this there is one shared drive as well which holds some images.

Recently we have changed application pool of the site and also added that user on shared file system.

After this change, when i generate a PDF which holds images from the shared drive , it is showing image on PDF file. It shows file not found. I was working before this change.

I do have one edit page which shows this same image. When I generate PDF of it , images are not getting displayed.

PDF Image file path Format is "\\xx.xx.xx.xx\path\to\folder\filename.jpg"

Not sure what we missed here for the permission.

答:
It seems that your application pool identity has been changed. Please set your application pool identity to a domain account that have permission to access the image file.

Maybe somewhere else need read/write permission .Process monitor could help in this case. Please add a filter to trace file not found exception or access denied error.

https://learn.microsoft.com/en-us/sysinternals/downloads/procmon

ContentLicense: CC BY-SA 4.0


问:
Column-specific processing in an sklearn pipeline
I have a situation where I need to do some column-specific processing in a pipeline, but because transformers return numpy arrays rather than pandas dataframes, I don't have column names to do my feature engineering.

Here's a simple, reproducible example where I have a function called engineer_feature that I want to use to create new data. I need to use it during/after the pipeline because it depends on one column becoming imputed, and I would like it to be able to be performed during k-fold cross-validation.

```<code>import numpy as np
import pandas as pd

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler

df = pd.DataFrame({"Type": ["Beta", "Beta", "Alpha", "Charlie", "Beta", "Charlie"], "A": [1, 2, 3, np.nan, 22, 4], "B": [5, 7, 12, 21, 12, 10]})

def engineer_feature(df):
    df["C"] = df["A"] / df["B"]
    return df

categorical_transformer = Pipeline([
    ("one_hot", OneHotEncoder())
])

numeric_transformer = Pipeline([
    ("imputer", SimpleImputer()),
    ("engineer", FunctionTransformer(engineer_feature)),
    ("scaler", StandardScaler())
])

preprocessor = ColumnTransformer([
    ("categorical", categorical_transformer, ["Type"]),
    ("numeric", numeric_transformer, ["A", "B"])
])

preprocessor.fit_transform(df)
</code>```

Which yields this error:

```<code>IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
</code>```

Which makes sense because engineer_feature is trying to index columns as if though they are dataframes when they are just numpy arrays.

What's a strategy for getting around this? I don't want to hardcode column indices to access them via numpy, especially since my real dataframe has many more columns.

答:
There are ways to get around your challenge by adding few steps and simplifying the entire approach instead of trying to run everything on a single input dataframe.

For one hot encoding, you can use the get_dummies() function in pandas.

For calculating df["C"], you can write a lambda function and apply it to all rows in the dataframe using the apply function in pandas.

You should still rely on sklearn for imputing and scaling the numeric columns.

As you correctly mentioned, the output from sklearn will be a numpy array. You should convert it back to a pandas dataframe that can be used further.

In order to follow the above approach,

Split your dataframe into two, one with categorical columns and the other with numeric. Once you are done with data processing, use append in pandas to append them back.

```<code>df_numeric.append(df_catgeorical)
</code>```

You will need to save the output of each step in a new dataframe, and pass it further downstream in your data pipeline.

To release memory footprint, delete the old dataframe and call garbage collector

```<code>import gc

del df
gc.collect()
</code>```

You do not need to save the column index of a numpy array. Simply use df.columns to return the dataframe's columns as a list. For example, below is what you can do to convert the output of a sklearn transformation into a dataframe

```<code>sim = SimpleImputer()
sklearn_output_array = sim.fit_transform(df_input)

df_output = pd.DataFrame(sklearn_output_array, columns=df_input.columns)

del df_input
del sklearn_output_array
gc.collect()

df_output["C"] = df_output["A"] / df_output["B"]
</code>```

I agree that the above approach will increase the number of lines of code. However, our code will be much more readable and easier to follow.

In addition to the above, below is another stack overflow post that deals with one-hot encoding and saving column names of transformed dataframes for further use downstream. The answer has some examples with code that you might find useful.

https://stackoverflow.com/a/60107683/12855052

Hope this all helps, and let me know if you have further questions!

Body:
I have a situation where I need to do some column-specific processing in a pipeline, but because transformers return numpy arrays rather than pandas dataframes, I don't have column names to do my feature engineering.

Here's a simple, reproducible example where I have a function called engineer_feature that I want to use to create new data. I need to use it during/after the pipeline because it depends on one column becoming imputed, and I would like it to be able to be performed during k-fold cross-validation.

import numpy as np
import pandas as pd

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler

df = pd.DataFrame({"Type": ["Beta", "Beta", "Alpha", "Charlie", "Beta", "Charlie"], "A": [1, 2, 3, np.nan, 22, 4], "B": [5, 7, 12, 21, 12, 10]})

def engineer_feature(df):
    df["C"] = df["A"] / df["B"]
    return df

categorical_transformer = Pipeline([
    ("one_hot", OneHotEncoder())
])

numeric_transformer = Pipeline([
    ("imputer", SimpleImputer()),
    ("engineer", FunctionTransformer(engineer_feature)),
    ("scaler", StandardScaler())
])

preprocessor = ColumnTransformer([
    ("categorical", categorical_transformer, ["Type"]),
    ("numeric", numeric_transformer, ["A", "B"])
])

preprocessor.fit_transform(df)

Which yields this error:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Which makes sense because engineer_feature is trying to index columns as if though they are dataframes when they are just numpy arrays.

What's a strategy for getting around this? I don't want to hardcode column indices to access them via numpy, especially since my real dataframe has many more columns.

Body:
There are ways to get around your challenge by adding few steps and simplifying the entire approach instead of trying to run everything on a single input dataframe.

For one hot encoding, you can use the get_dummies() function in pandas.

For calculating df["C"], you can write a lambda function and apply it to all rows in the dataframe using the apply function in pandas.

You should still rely on sklearn for imputing and scaling the numeric columns.

As you correctly mentioned, the output from sklearn will be a numpy array. You should convert it back to a pandas dataframe that can be used further.

In order to follow the above approach,

Split your dataframe into two, one with categorical columns and the other with numeric. Once you are done with data processing, use append in pandas to append them back.

df_numeric.append(df_catgeorical)

You will need to save the output of each step in a new dataframe, and pass it further downstream in your data pipeline.

To release memory footprint, delete the old dataframe and call garbage collector

import gc

del df
gc.collect()

You do not need to save the column index of a numpy array. Simply use df.columns to return the dataframe's columns as a list. For example, below is what you can do to convert the output of a sklearn transformation into a dataframe

sim = SimpleImputer()
sklearn_output_array = sim.fit_transform(df_input)

df_output = pd.DataFrame(sklearn_output_array, columns=df_input.columns)

del df_input
del sklearn_output_array
gc.collect()

df_output["C"] = df_output["A"] / df_output["B"]

I agree that the above approach will increase the number of lines of code. However, our code will be much more readable and easier to follow.

In addition to the above, below is another stack overflow post that deals with one-hot encoding and saving column names of transformed dataframes for further use downstream. The answer has some examples with code that you might find useful.

https://stackoverflow.com/a/60107683/12855052

Hope this all helps, and let me know if you have further questions!


问:
$(document).ready called inside an external function?
I saw some jquery code on the Net somewhere, that took this form :

```<code><script>
function doSomething(message)
{
    $(document).ready(function(){
        alert(message);
        });
};
</script>
</code>```

i.e. an external function ("doSomething") which has $(document).ready inside it. I'm confused because isn't the code under $(document).ready triggered when the DOM is loaded ? Its like having an event handler inside a function (?). Does this form of code make sense to anyone ? Thanks.

答:
It makes sense. $(document).ready registers an event handler that is fired when the DOM is fully loaded. The anonymous function that is passed to it, is that handler. If you register that handler after the DOM is loaded, it is fired immediately.

Javascript can be executed before the DOM is fully loaded, so what this function does, it actually registers messages that are not to be shown before the DOM is loaded. You can use this construct if you don't want the message to be displayed before the DOM is fully loaded.

Body:
I saw some jquery code on the Net somewhere, that took this form :

i.e. an external function ("doSomething") which has $(document).ready inside it. I'm confused because isn't the code under $(document).ready triggered when the DOM is loaded ? Its like having an event handler inside a function (?). Does this form of code make sense to anyone ? Thanks.


问:
How to make while loop check if there are 16 digits in a string
How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!</p>

```<code>import java.util.Scanner;

public class LuhnAlgorithm {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
        String nums = input.nextLine();

        int i = 0;
        char chk = nums.charAt(15);

        while(!nums .equals("") ) {

            if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
                System.out.println("ERROR! Number MUST have exactly 16 digits.");
            }

            int sum = 0;
            for( i = 0; i < 15; i++) {
                char numc = nums.charAt(i);
                int num = Character.getNumericValue(numc);
                if ( i % 2 == 0 ) {
                    num = num * 2;
                    if ( num >= 10) {
                        num = num - 9;
                    }
                }
                sum = num + sum;
            }

            int sum2 = sum % 10;
            if (sum2 > 0) {
                sum2 = 10 - sum2;
            }
            int chk2 = Character.getNumericValue(chk);
            System.out.println("The check digit should be: " + sum2);
            System.out.println("The check digit is: " + chk);
            if ( sum2 == chk2) {
                System.out.println("Number is valid.");
            }
            else {
                System.out.println("Number is not valid. ");
            }

            System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
            nums = input.nextLine();
        }

        System.out.println("Goodbye!");
        input.close();
    }
}
</code>```

答:
You can bring the prompts and all your initialization except the scanner itself into the while loop. Then if they say "", break to exit the loop. If they say a number that is too short or too long, say continue to go back to the prompting.
Thus:

```<code>    import java.util.Scanner;
public class main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (true) {
            System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
            String nums = input.nextLine().trim();
            if (nums.length() == 0) {
                break; //exits while loop
            }
            if (nums.length() != 16) { //How do I get this line to reset the while loop?
                System.out.println("ERROR! Number MUST have exactly 16 digits.");
                continue; //goes back to the beginning right away
            }
            //still here, process the number
            char chk = nums.charAt(15);
            int sum = 0;
            for (int i = 0; i < 15; i++) {
                char numc = nums.charAt(i);
                int num = Character.getNumericValue(numc);
                if (i % 2 == 0) {
                    num = num * 2;
                    if (num >= 10) {
                        num = num - 9;
                    }
                }

                sum = num + sum;
            }

            int sum2 = sum % 10;
            if (sum2 > 0) {
                sum2 = 10 - sum2;
            }
            int chk2 = Character.getNumericValue(chk);
            System.out.println("The check digit should be: " + sum2);
            System.out.println("The check digit is: " + chk);
            if (sum2 == chk2) {
                System.out.println("Number is valid.");
            } else {
                System.out.println("Number is not valid. ");
            }

        }

        System.out.println("Goodbye!");

        input.close();
    }

}
</code>```

Body:
How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!

import java.util.Scanner;

public class LuhnAlgorithm {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
        String nums = input.nextLine();

        int i = 0;
        char chk = nums.charAt(15);

        while(!nums .equals("") ) {

            if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
                System.out.println("ERROR! Number MUST have exactly 16 digits.");
            }

            int sum = 0;
            for( i = 0; i < 15; i++) {
                char numc = nums.charAt(i);
                int num = Character.getNumericValue(numc);
                if ( i % 2 == 0 ) {
                    num = num * 2;
                    if ( num >= 10) {
                        num = num - 9;
                    }
                }
                sum = num + sum;
            }

            int sum2 = sum % 10;
            if (sum2 > 0) {
                sum2 = 10 - sum2;
            }
            int chk2 = Character.getNumericValue(chk);
            System.out.println("The check digit should be: " + sum2);
            System.out.println("The check digit is: " + chk);
            if ( sum2 == chk2) {
                System.out.println("Number is valid.");
            }
            else {
                System.out.println("Number is not valid. ");
            }

            System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
            nums = input.nextLine();
        }

        System.out.println("Goodbye!");
        input.close();
    }
}

Body:
You can bring the prompts and all your initialization except the scanner itself into the while loop. Then if they say "", break to exit the loop. If they say a number that is too short or too long, say continue to go back to the prompting.
Thus:

    import java.util.Scanner;
public class main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (true) {
            System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
            String nums = input.nextLine().trim();
            if (nums.length() == 0) {
                break; //exits while loop
            }
            if (nums.length() != 16) { //How do I get this line to reset the while loop?
                System.out.println("ERROR! Number MUST have exactly 16 digits.");
                continue; //goes back to the beginning right away
            }
            //still here, process the number
            char chk = nums.charAt(15);
            int sum = 0;
            for (int i = 0; i < 15; i++) {
                char numc = nums.charAt(i);
                int num = Character.getNumericValue(numc);
                if (i % 2 == 0) {
                    num = num * 2;
                    if (num >= 10) {
                        num = num - 9;
                    }
                }

                sum = num + sum;
            }

            int sum2 = sum % 10;
            if (sum2 > 0) {
                sum2 = 10 - sum2;
            }
            int chk2 = Character.getNumericValue(chk);
            System.out.println("The check digit should be: " + sum2);
            System.out.println("The check digit is: " + chk);
            if (sum2 == chk2) {
                System.out.println("Number is valid.");
            } else {
                System.out.println("Number is not valid. ");
            }

        }

        System.out.println("Goodbye!");

        input.close();
    }

}


问:
how to make bootstrap table clickable
I have a bootstrap like this in main.html page:

```<code><table class="table table-striped">
 <thead>
    <tr>
     <th scope="col">#</th>
     <th scope="col">First</th>
     <th scope="col">Last</th>
     <th scope="col">Handle</th>
   </tr>
 </thead>
 <tbody>
  <tr>
    <th scope="row">1</th>
    <td>Mark</td>
    <td>Otto</td>
    <td>@mdo</td>
 </tr>
 <tr>
   <th scope="row">2</th>
   <td>Jacob</td>
   <td>Thornton</td>
   <td>@fat</td>
</tr>
<tr>
  <th scope="row">3</th>
  <td>Larry</td>
  <td>the Bird</td>
  <td>@twitter</td>
</tr>
</tbody>
</table>
</code>```

My requirement is:

When I click on any row of the table( either on the text or even in the space between two columns) it has to redirect to another Html page.

how can I do that?

答:
It can be done using jQuery. Bind an event listener on click of TR and then redirect the user as needed.

Your HTML

```<code><table class="table table-striped">
 <thead>
    <tr>
     <th scope="col">#</th>
     <th scope="col">First</th>
     <th scope="col">Last</th>
     <th scope="col">Handle</th>
   </tr>
 </thead>
 <tbody>
  <tr>
    <th scope="row">1</th>
    <td>Mark</td>
    <td>Otto</td>
    <td>@mdo</td>
 </tr>
 <tr>
   <th scope="row">2</th>
   <td>Jacob</td>
   <td>Thornton</td>
   <td>@fat</td>
</tr>
<tr>
  <th scope="row">3</th>
  <td>Larry</td>
  <td>the Bird</td>
  <td>@twitter</td>
</tr>
</tbody>
</table>
</code>```

jQuery Code

```<code>$(function() {
  $('tr').on('click', function() {
    document.location.href = 'https://google.com';

  });
});
</code>```

Plain JavaScript

```<code>var table = document.getElementById('js-table');
for(var i = 0; i < table.rows.length; i++) {
  table.rows[i].addEventListener('click', function() {
    document.location.href = "https://google.com"
  });
}
</code>```

Title: how to make bootstrap table clickable

Body:
I have a bootstrap like this in main.html page:

     #
     First
     Last
     Handle

    1
    Mark
    Otto
    @mdo

   2
   Jacob
   Thornton
   @fat

  3
  Larry
  the Bird
  @twitter

My requirement is:

When I click on any row of the table( either on the text or even in the space between two columns) it has to redirect to another Html page.

how can I do that?

Body:
It can be done using jQuery. Bind an event listener on click of TR and then redirect the user as needed.

Your HTML

<table class="table table-striped">
 <thead>
    <tr>
     <th scope="col">#</th>
     <th scope="col">First</th>
     <th scope="col">Last</th>
     <th scope="col">Handle</th>
   </tr>
 </thead>
 <tbody>
  <tr>
    <th scope="row">1</th>
    <td>Mark</td>
    <td>Otto</td>
    <td>@mdo</td>
 </tr>
 <tr>
   <th scope="row">2</th>
   <td>Jacob</td>
   <td>Thornton</td>
   <td>@fat</td>
</tr>
<tr>
  <th scope="row">3</th>
  <td>Larry</td>
  <td>the Bird</td>
  <td>@twitter</td>
</tr>
</tbody>
</table>

jQuery Code

$(function() {
  $('tr').on('click', function() {
    document.location.href = 'https://google.com';

  });
});

Plain JavaScript

var table = document.getElementById('js-table');
for(var i = 0; i < table.rows.length; i++) {
  table.rows[i].addEventListener('click', function() {
    document.location.href = "https://google.com"
  });
}


问:
Card header cannot strech to the card edge when using Bootstrap cards grid
I use bootstrap 4 in Laravel and write blade.php template files. Below is my code.

The card grid looks good, but there are blank spaces between card titles and the car edges.

```<code><div id="unassigned-list" class="row">
            @foreach ($cardsUnAssignedToCurrentUser as $card)
            <div class="card unassigned border-secondary mt-2 mr-2 col-sm-3">
                <div class="card-header">
                    Card<a href="#" class="card-link pull-right moveBtn">Assign</a>
                </div>
                <div class="card-body unassigned">
                    <h6 class="card-subtitle mb-2 text-muted">First Name</h6>
                    <p class="card-text">@if (strlen($card->first_name) > 0) {{ $card->first_name }} @else None @endif
                    </p>
                    <h6 class="card-subtitle mb-2 text-muted">Last Name</h6>
                    <p class="card-text">@if (strlen($card->last_name) > 0) {{ $card->last_name }} @else None @endif</p>
                    <h6 class="card-subtitle mb-2 text-muted">Last Four Number</h6>
                    <p class="card-text"><strong>{{ $card->last_four_digits }}</strong></p>
                    <input type="hidden" value="{{ $card->id }}" />
                </div>
            </div>

            @endforeach
</div>
</code>```

答:
the left and right padding is added due to class col-sm-3 ... just override these to get what you want...

code snippet below:

.card.unassigned.border-secondary.col-sm-3 {
  padding-right: 0;
  padding-left: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<div class='container'>
  <div id="unassigned-list" class="row">
    <div class="card unassigned border-secondary mt-2 mr-2 col-sm-3">
      <div class="card-header">
        CardAssign
      </div>
      <div class="card-body unassigned">
        <h6 class="card-subtitle mb-2 text-muted">First Name</h6>
        <p class="card-text">@if (strlen($card->first_name) > 0) {{ $card->first_name }} @else None @endif
        </p>
        <h6 class="card-subtitle mb-2 text-muted">Last Name</h6>
        <p class="card-text">@if (strlen($card->last_name) > 0) {{ $card->last_name }} @else None @endif</p>
        <h6 class="card-subtitle mb-2 text-muted">Last Four Number</h6>
        <p class="card-text"><strong>{{ $card->last_four_digits }}</strong></p>
        <input type="hidden" value="{{ $card->id }}" />
      </div>
    </div>
    <div class="card unassigned border-secondary mt-2 mr-2 col-sm-3">
      <div class="card-header">
        CardAssign
      </div>
      <div class="card-body unassigned">
        <h6 class="card-subtitle mb-2 text-muted">First Name</h6>
        <p class="card-text">@if (strlen($card->first_name) > 0) {{ $card->first_name }} @else None @endif
        </p>
        <h6 class="card-subtitle mb-2 text-muted">Last Name</h6>
        <p class="card-text">@if (strlen($card->last_name) > 0) {{ $card->last_name }} @else None @endif</p>
        <h6 class="card-subtitle mb-2 text-muted">Last Four Number</h6>
        <p class="card-text"><strong>{{ $card->last_four_digits }}</strong></p>
        <input type="hidden" value="{{ $card->id }}" />
      </div>
    </div>
    <div class="card unassigned border-secondary mt-2 mr-2 col-sm-3">
      <div class="card-header">
        CardAssign
      </div>
      <div class="card-body unassigned">
        <h6 class="card-subtitle mb-2 text-muted">First Name</h6>
        <p class="card-text">@if (strlen($card->first_name) > 0) {{ $card->first_name }} @else None @endif
        </p>
        <h6 class="card-subtitle mb-2 text-muted">Last Name</h6>
        <p class="card-text">@if (strlen($card->last_name) > 0) {{ $card->last_name }} @else None @endif</p>
        <h6 class="card-subtitle mb-2 text-muted">Last Four Number</h6>
        <p class="card-text"><strong>{{ $card->last_four_digits }}</strong></p>
        <input type="hidden" value="{{ $card->id }}" />
      </div>
    </div>
    <div class="card unassigned border-secondary mt-2 mr-2 col-sm-3">
      <div class="card-header">
        CardAssign
      </div>
      <div class="card-body unassigned">
        <h6 class="card-subtitle mb-2 text-muted">First Name</h6>
        <p class="card-text">@if (strlen($card->first_name) > 0) {{ $card->first_name }} @else None @endif
        </p>
        <h6 class="card-subtitle mb-2 text-muted">Last Name</h6>
        <p class="card-text">@if (strlen($card->last_name) > 0) {{ $card->last_name }} @else None @endif</p>
        <h6 class="card-subtitle mb-2 text-muted">Last Four Number</h6>
        <p class="card-text"><strong>{{ $card->last_four_digits }}</strong></p>
        <input type="hidden" value="{{ $card->id }}" />
      </div>
    </div>

  </div>
</div></code>```

Body:
I use bootstrap 4 in Laravel and write blade.php template files. Below is my code.

The card grid looks good, but there are blank spaces between card titles and the car edges.

            @foreach ($cardsUnAssignedToCurrentUser as $card)

                    CardAssign

First Name

@if (strlen($card->first_name) > 0) {{ $card->first_name }} @else None @endif

Last Name

@if (strlen($card->last_name) > 0) {{ $card->last_name }} @else None @endif

Last Four Number

{{ $card->last_four_digits }}

                    <input type="hidden" value="{{ $card->id }}" />

            @endforeach

Body:
the left and right padding is added due to class col-sm-3 ... just override these to get what you want...

code snippet below:

.card.unassigned.border-secondary.col-sm-3 {
  padding-right: 0;
  padding-left: 0;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<div class='container'>
  <div id="unassigned-list" class="row">
    <div class="card unassigned border-secondary mt-2 mr-2 col-sm-3">
      <div class="card-header">
        Card<a href="#" class="card-link pull-right moveBtn">Assign</a>
      </div>
      <div class="card-body unassigned">
        <h6 class="card-subtitle mb-2 text-muted">First Name</h6>
        <p class="card-text">@if (strlen($card->first_name) > 0) {{ $card->first_name }} @else None @endif
        </p>
        <h6 class="card-subtitle mb-2 text-muted">Last Name</h6>
        <p class="card-text">@if (strlen($card->last_name) > 0) {{ $card->last_name }} @else None @endif</p>
        <h6 class="card-subtitle mb-2 text-muted">Last Four Number</h6>
        <p class="card-text"><strong>{{ $card->last_four_digits }}</strong></p>
        <input type="hidden" value="{{ $card->id }}" />
      </div>
    </div>
    <div class="card unassigned border-secondary mt-2 mr-2 col-sm-3">
      <div class="card-header">
        Card<a href="#" class="card-link pull-right moveBtn">Assign</a>
      </div>
      <div class="card-body unassigned">
        <h6 class="card-subtitle mb-2 text-muted">First Name</h6>
        <p class="card-text">@if (strlen($card->first_name) > 0) {{ $card->first_name }} @else None @endif
        </p>
        <h6 class="card-subtitle mb-2 text-muted">Last Name</h6>
        <p class="card-text">@if (strlen($card->last_name) > 0) {{ $card->last_name }} @else None @endif</p>
        <h6 class="card-subtitle mb-2 text-muted">Last Four Number</h6>
        <p class="card-text"><strong>{{ $card->last_four_digits }}</strong></p>
        <input type="hidden" value="{{ $card->id }}" />
      </div>
    </div>
    <div class="card unassigned border-secondary mt-2 mr-2 col-sm-3">
      <div class="card-header">
        Card<a href="#" class="card-link pull-right moveBtn">Assign</a>
      </div>
      <div class="card-body unassigned">
        <h6 class="card-subtitle mb-2 text-muted">First Name</h6>
        <p class="card-text">@if (strlen($card->first_name) > 0) {{ $card->first_name }} @else None @endif
        </p>
        <h6 class="card-subtitle mb-2 text-muted">Last Name</h6>
        <p class="card-text">@if (strlen($card->last_name) > 0) {{ $card->last_name }} @else None @endif</p>
        <h6 class="card-subtitle mb-2 text-muted">Last Four Number</h6>
        <p class="card-text"><strong>{{ $card->last_four_digits }}</strong></p>
        <input type="hidden" value="{{ $card->id }}" />
      </div>
    </div>
    <div class="card unassigned border-secondary mt-2 mr-2 col-sm-3">
      <div class="card-header">
        Card<a href="#" class="card-link pull-right moveBtn">Assign</a>
      </div>
      <div class="card-body unassigned">
        <h6 class="card-subtitle mb-2 text-muted">First Name</h6>
        <p class="card-text">@if (strlen($card->first_name) > 0) {{ $card->first_name }} @else None @endif
        </p>
        <h6 class="card-subtitle mb-2 text-muted">Last Name</h6>
        <p class="card-text">@if (strlen($card->last_name) > 0) {{ $card->last_name }} @else None @endif</p>
        <h6 class="card-subtitle mb-2 text-muted">Last Four Number</h6>
        <p class="card-text"><strong>{{ $card->last_four_digits }}</strong></p>
        <input type="hidden" value="{{ $card->id }}" />
      </div>
    </div>

  </div>
</div>


问:
Selection area after image rotated
I'm using the selection area plugin from here in my project. My problem is that when the image been rotated(-90), the selection direction will become weird. When I draw a selection like pic 1, it shows the result like pic 2. Does anyone have any idea on how I suppose to solve this problem?

答:
I just made an empty image with the appropriate width and height, and overlaid it over the original image. It's a hack, but it should work.

function debugQtyAreas(event, id, areas) {
  console.log(areas.length + " areas", arguments);
};

var blank = function(width, height) {
  var newImg = $("").attr("width", height)
    .attr("height", width);
  return newImg[0];
}

$("#originalImage").load(function() {
  var width = $("#originalImage")[0].width, height = $("#originalImage")[0].height;
  var img = blank(width, height);
  $("#originalImage").after(img);
  $.selectAreas(img, {
    minSize: [10, 10],
    onChanged: debugQtyAreas,
    areas: [{
      x: 10,
      y: 20,
      width: 60,
      height: 100,
    }]
  });
  $(".rotated-img > div").css("left", width / 2 - height / 2).css("top", height / 2 - width / 2);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.rotated-img {
  position: relative;
}

img#originalImage {
  transform: rotate(270deg);
}

img {
  position: absolute;
  top: 0px;
  left: 0px;
}</code>```

<link href="https://rawgit.com/360Learning/jquery-select-areas/master/resources/jquery.selectareas.css" rel="stylesheet" />

```

Title: Selection area after image rotated

Body:
I just made an empty image with the appropriate width and height, and overlaid it over the original image. It's a hack, but it should work.

function debugQtyAreas(event, id, areas) {
  console.log(areas.length + " areas", arguments);
};

var blank = function(width, height) {
  var newImg = $("<img src='data:,' alt>").attr("width", height)
    .attr("height", width);
  return newImg[0];
}

$("#originalImage").load(function() {
  var width = $("#originalImage")[0].width, height = $("#originalImage")[0].height;
  var img = blank(width, height);
  $("#originalImage").after(img);
  $.selectAreas(img, {
    minSize: [10, 10],
    onChanged: debugQtyAreas,
    areas: [{
      x: 10,
      y: 20,
      width: 60,
      height: 100,
    }]
  });
  $(".rotated-img > div").css("left", width / 2 - height / 2).css("top", height / 2 - width / 2);
});

.rotated-img {
  position: relative;
}

img#originalImage {
  transform: rotate(270deg);
}

img {
  position: absolute;
  top: 0px;
  left: 0px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link href="https://rawgit.com/360Learning/jquery-select-areas/master/resources/jquery.selectareas.css" rel="stylesheet" />
<script src="https://rawgit.com/360Learning/jquery-select-areas/master/jquery.selectareas.js"></script>

<div class="rotated-img">
<img src="https://rawgit.com/360Learning/jquery-select-areas/master/example/example.jpg" id="originalImage" />
</div>


问:
NPM security not enforceable by running "npm config set ignore-scripts false"
I have done some research that recommends npm config set ignore-scripts false to be run to avoid any possible malicious package from npm. However, after running the command,it seem to prevent npm run... commands from working in my node projects until I set it back to false. For example, I cant run node server and react client concurrently with npm run dev commands making development difficult. Is there a solution for this

答:
I think you missed something the idea is to ignore scripts installed via npm install (there may be malicious publishers out there) thus using npm config set ignore-scripts true will help to keep you safe, however there are projects where you want to use your own custom scripts.

You can use a local version of .npmrc to override said config, and manually change the value of ignore-scripts on your own, I would advice to setting to false when running npm install and setting it to true whenever you want to run your local scripts.

Remember that .npmrc will be located in the root of your project if you want to have it as local, and usually lies at ~/.npmrc for global configuration.

For more information about .npmrc please check https://docs.npmjs.com/configuring-npm/npmrc.html

I hope this help you or any future folk out there!


问:
Cannot automate signing in to Azure Active Directory using Selenium WebDriver
I'm trying to test logging in to our web application using Azure AD but the click action on the Sign In button doesn't seem to register. Here's the code:

```<code>namespace WebApp.Tests
{
    using System;
    using System.IO;
    using System.Threading;
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using OpenQA.Selenium;
    using OpenQA.Selenium.IE;
    using OpenQA.Selenium.Remote;
    using OpenQA.Selenium.Support.UI;

    [TestClass]
    public class LoginTests
    {
        [TestMethod]
        public void CanLogin()
        {
            string internetExplorerDriverServerDirectory = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
            IWebDriver driver = new InternetExplorerDriver(internetExplorerDriverServerDirectory)
            {
                Url = "https://localhost:44399"
            };

            try
            {
                driver.Manage().Cookies.DeleteAllCookies();

                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
                wait.Until(d => d.FindElement(By.Id("logonIdentifier")));

                driver.FindElement(By.Id("logonIdentifier")).SendKeys("username");
                driver.FindElement(By.Id("password")).SendKeys("password");
                driver.FindElement(By.Id("next")).Click();

                wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
                wait.Until(d => d.FindElement(By.ClassName("logo_title")));

                driver.FindElement(By.ClassName("logo_title")).Text.Should().Contain("HELLO!");
            }
            finally
            {
                driver.Close();
                driver.Quit();
                driver.Dispose();
                driver = null;
            }
        }
    }
}
</code>```

Here's the relevant bits of HTML:

```<code><div class="entry">
    <div class="entry-item">
        <label for="logonIdentifier">Email Address</label>
        <div class="error itemLevel" aria-hidden="true" style="display: none;">
            <p role="alert"></p>
        </div>
        <input type="email" id="logonIdentifier" name="Username or email address" pattern="^[a-zA-Z0-9.!#$%&’'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$" placeholder="Email Address" value="" tabindex="1" autocomplete="off">
    </div>
    <div class="entry-item">
        <div class="password-label">
            <label for="password">Password</label>
                <a id="forgotPassword" tabindex="2" href="/redacted">Forgot your password?</a>
        </div>
        <div class="error itemLevel" aria-hidden="true" style="display: none;">
            <p role="alert"></p>
        </div>
        <input type="password" id="password" name="Password" placeholder="Password" tabindex="1" autocomplete="off">
    </div>
    <div class="working"></div>
    <div class="buttons">
        <button id="next" tabindex="1">Sign in</button>
    </div>
</div>
</code>```

It all looks OK in the browser: the username and password fields are filled in, the button looks like it gets clicked (the little "working" icon appears briefly above it) but nothing happens.

I've tried a longer wait (up to 30 seconds) for the home page to
appear after clicking the Sign In button.

wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));

I've tried sending an Enter key while in the form instead of clicking
the button.

driver.FindElement(By.Id("password")).SendKeys(Keys.Enter);

I've tried executing some JavaScript to call the button click action.

IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript("document.getElementById('next').click();");

I've tried using the Chrome and Firefox drivers.

I've tried on both the local development version and the hosted test    environment.

Nothing so far has worked. There are no error/validation messages shown in the browser during the process.

I'm at a bit of a loss with this one.

Thanks,
Stuart.

答:
I have solved the same by using CSS selector as element locator.

SeleniumLibrary.Input              Text                      css:#i0118       your_password

it's working fine in every iteration.

Body:
I'm trying to test logging in to our web application using Azure AD but the click action on the Sign In button doesn't seem to register. Here's the code:

namespace WebApp.Tests
{
    using System;
    using System.IO;
    using System.Threading;
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using OpenQA.Selenium;
    using OpenQA.Selenium.IE;
    using OpenQA.Selenium.Remote;
    using OpenQA.Selenium.Support.UI;

    [TestClass]
    public class LoginTests
    {
        [TestMethod]
        public void CanLogin()
        {
            string internetExplorerDriverServerDirectory = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
            IWebDriver driver = new InternetExplorerDriver(internetExplorerDriverServerDirectory)
            {
                Url = "https://localhost:44399"
            };

            try
            {
                driver.Manage().Cookies.DeleteAllCookies();

                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
                wait.Until(d => d.FindElement(By.Id("logonIdentifier")));

                driver.FindElement(By.Id("logonIdentifier")).SendKeys("username");
                driver.FindElement(By.Id("password")).SendKeys("password");
                driver.FindElement(By.Id("next")).Click();

                wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
                wait.Until(d => d.FindElement(By.ClassName("logo_title")));

                driver.FindElement(By.ClassName("logo_title")).Text.Should().Contain("HELLO!");
            }
            finally
            {
                driver.Close();
                driver.Quit();
                driver.Dispose();
                driver = null;
            }
        }
    }
}

Here's the relevant bits of HTML:

        Email Address

        <input type="email" id="logonIdentifier" name="Username or email address" pattern="^[a-zA-Z0-9.!#$%&’'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$" placeholder="Email Address" value="" tabindex="1" autocomplete="off">

            Password
                Forgot your password?

        <input type="password" id="password" name="Password" placeholder="Password" tabindex="1" autocomplete="off">

        <button id="next" tabindex="1">Sign in</button>

It all looks OK in the browser: the username and password fields are filled in, the button looks like it gets clicked (the little "working" icon appears briefly above it) but nothing happens.

I've tried a longer wait (up to 30 seconds) for the home page to
appear after clicking the Sign In button.

wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));

I've tried sending an Enter key while in the form instead of clicking
the button.

driver.FindElement(By.Id("password")).SendKeys(Keys.Enter);

I've tried executing some JavaScript to call the button click action.

IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript("document.getElementById('next').click();");

I've tried using the Chrome and Firefox drivers.

I've tried on both the local development version and the hosted test    environment.

Nothing so far has worked. There are no error/validation messages shown in the browser during the process.

I'm at a bit of a loss with this one.

Thanks,
Stuart.


问:
ExtJS Grid Message When No Records Found
I'm using ExtJS 4.0 grid and want to display a message (or HTML, or component)  inside the grid area when there are no records found.  I've been rummaging through their code for a while and can't seem to find any evidence that this exists natively in their library.  Is there a config or method I can use for this or will I have to roll my own?

Thx

答:
ExtJS 4 do provide you with the functionality of displaying a message inside the grid area when there is no records in your grid's store. You need to use the viewConfig for doing this. Here is an example:

```<code>viewConfig: {
    emptyText: 'There are no records to display'
}
</code>```

Now, if you are using a local store (or loading data directly to the grid using data) then you will need to set deferEmptyText to false. This is clearly explained in the documentation of grid's view. Refer to the config properties emptyText and deferEmptyText.

Body:
ExtJS 4 do provide you with the functionality of displaying a message inside the grid area when there is no records in your grid's store. You need to use the viewConfig for doing this. Here is an example:

viewConfig: {
    emptyText: 'There are no records to display'
}

Now, if you are using a local store (or loading data directly to the grid using data) then you will need to set deferEmptyText to false. This is clearly explained in the documentation of grid's view. Refer to the config properties emptyText and deferEmptyText.


问:
Trying to get property of non-object when display value of json response in Laravel
i try to display the value of json response . Its work well when I dd   @php dd( $user->irel__com_access_level->ID); @endphp inside blade view but when i try to display at table it return error which is

Trying to get property of non-object

My code display in table

```<code>     @foreach($content as $user)
      <td>{{ $user->irel__com_access_level->ID }}</td>
     @endforeach
</code>```

Here is my json response ....i want to display ID which is inside irel__com_access_level

```<code>{
    "data": [
        {

        {
            "ID": "banana",
            "PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g=",
            "NICK_NAME": "BANANA NANA NA",
            "PWD_INVALID_HIT": "0",
            "PWD_CREATE_DT": "2019/09/06 16:44:40",
            "INSTITUTION_ID": "C01",
            "ACL_ID": "L03",
            "LOGIN_DT": "                   ",
            "LOGIN_STS_ID": "N",
            "STS_ID": "C03",
            "TYPE_ID": "U00",
            "UPD_ID": "asmidah",
            "UPD_DT": "2019/09/06 16:44:40",
            "EMAIL_ID": "banana@gmail.com",
            "PHONE_NO_ID": "0",
            "HP_ID": "0101234567               ",
            "CRT_DATE_DELETED": "2019/09/06 16:44:40",
            "irel__com_access_level": {
                "ID": "L03",       // i want to display this
                "DESCRIPTION": "2NDLEVEL",
                "IS_CREATE": "N",
                "IS_READ": "Y",
                "IS_UPDATE": "Y",
                "IS_DELETE": "N",
                "STS_ID": "R01",
                "UPD_ID": "shukrimb",
                "UPD_DT": "2012/09/13 13:28:25"
           }
</code>```

my controller

```<code> private $client;

    public function __construct(){

        $this->client = new Client(['base_uri' => 'http://172.19.52.6/api/configuration/getUserIndex']);

    }

    public function index()
    {

        $response =  $this->client->get('getUserIndex');
         $content = json_decode($response->getBody());

         return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data]);

</code>```

i want to display ID which is inside irel__com_access_level in json response

答:
Try this

```<code> return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data->first()]);
</code>```

or

```<code> return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data()->first()]);
</code>```

Body:
i try to display the value of json response . Its work well when I dd   @php dd( $user->irel__com_access_level->ID); @endphp inside blade view but when i try to display at table it return error which is

Trying to get property of non-object

My code display in table

     @foreach($content as $user)
      {{ $user->irel__com_access_level->ID }}
     @endforeach

Here is my json response ....i want to display ID which is inside irel__com_access_level

{
    "data": [
        {

        {
            "ID": "banana",
            "PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g=",
            "NICK_NAME": "BANANA NANA NA",
            "PWD_INVALID_HIT": "0",
            "PWD_CREATE_DT": "2019/09/06 16:44:40",
            "INSTITUTION_ID": "C01",
            "ACL_ID": "L03",
            "LOGIN_DT": "                   ",
            "LOGIN_STS_ID": "N",
            "STS_ID": "C03",
            "TYPE_ID": "U00",
            "UPD_ID": "asmidah",
            "UPD_DT": "2019/09/06 16:44:40",
            "EMAIL_ID": "banana@gmail.com",
            "PHONE_NO_ID": "0",
            "HP_ID": "0101234567               ",
            "CRT_DATE_DELETED": "2019/09/06 16:44:40",
            "irel__com_access_level": {
                "ID": "L03",       // i want to display this
                "DESCRIPTION": "2NDLEVEL",
                "IS_CREATE": "N",
                "IS_READ": "Y",
                "IS_UPDATE": "Y",
                "IS_DELETE": "N",
                "STS_ID": "R01",
                "UPD_ID": "shukrimb",
                "UPD_DT": "2012/09/13 13:28:25"
           }

my controller

 private $client;

    public function __construct(){

        $this->client = new Client(['base_uri' => 'http://172.19.52.6/api/configuration/getUserIndex']);

    }

    public function index()
    {

        $response =  $this->client->get('getUserIndex');
         $content = json_decode($response->getBody());

         return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data]);

i want to display ID which is inside irel__com_access_level in json response

Body:
Try this

 return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data->first()]);

or

 return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data()->first()]);


问:
Asp.net unhandled exception in timer callback crashes w3wp and error not logged
I am experiencing some randomly happening unhandled exception causing w3wp to crash. I want to trace the cause of that exception. I already have a global Application_Error handler override in my MvcApplication class, so the crash must be caused by some out-of-http-context exception. In order to replicate the problem I genereate one myself in a timer callback, and try to trace it. Simplified code like

```<code>public static class MonitorTimers
{
    public static Timer _taskMonitorTimer = new Timer(state: null, dueTime: 1000, period: 1000, callback: (state) =>
    {
        throw new Exception("Ouch! Me dead.");
    });
}
</code>```

In my local development environment (iisexpress launched by VS2017) and test environment (IIS 8.5), when the app starts and then crashes, the following can be seen in event viewer:

The most useful Event 1325 and 1026 sourced from ASP.NET and .NET Runtime shows the stack trace - just the thing I need.

My problem is, in my production machine (also IIS 8.5) I can't find the useful event 1325. Only a crash report, bearing no more information than I know. So I don't know what caused the error. I could surround my timer callback with try...catch block but the error could well be caused by something else (unmanaged libraries, error in static class initialization) then I still can't trace.

So suggestions on why event 1325 is missing or some tools that can show the log and analyse the stack trace is greatly appreciated. Thank you.

答:
So, in your case you generate Exception diring Loading of application domain.
When CLR load application domain it firstly init static fields. So, if your code has problem with static fields, then exception will throw until it specifies Application_Error  handler.

One more point, Is your application take a lot of memory? There are 2 cases when application can not write logs and execute code in catch block: StackOverflowException and OutOfMemoryException. Can you check is it has some memory leaks or infinite recursion?

One more point: set in visual studion setting to break when any exception throwed.

One more point: It is better to move your initialization logic from static constructors to ApplicationStart or something like this. You can do it temporary, for catch the bag and then move it to previous state.

Body:
I am experiencing some randomly happening unhandled exception causing w3wp to crash. I want to trace the cause of that exception. I already have a global Application_Error handler override in my MvcApplication class, so the crash must be caused by some out-of-http-context exception. In order to replicate the problem I genereate one myself in a timer callback, and try to trace it. Simplified code like

public static class MonitorTimers
{
    public static Timer _taskMonitorTimer = new Timer(state: null, dueTime: 1000, period: 1000, callback: (state) =>
    {
        throw new Exception("Ouch! Me dead.");
    });
}

In my local development environment (iisexpress launched by VS2017) and test environment (IIS 8.5), when the app starts and then crashes, the following can be seen in event viewer:

The most useful Event 1325 and 1026 sourced from ASP.NET and .NET Runtime shows the stack trace - just the thing I need.

My problem is, in my production machine (also IIS 8.5) I can't find the useful event 1325. Only a crash report, bearing no more information than I know. So I don't know what caused the error. I could surround my timer callback with try...catch block but the error could well be caused by something else (unmanaged libraries, error in static class initialization) then I still can't trace.

So suggestions on why event 1325 is missing or some tools that can show the log and analyse the stack trace is greatly appreciated. Thank you.


答:
try this code    </p>

```<code><!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
    <table class="table table-striped" id="tableId">
     <thead>
        <tr>
         <th scope="col">#</th>
         <th scope="col">First</th>
         <th scope="col">Last</th>
         <th scope="col">Handle</th>
       </tr>
     </thead>
     <tbody>
      <tr>
        <th scope="row">1</th>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
     </tr>
     <tr>
       <th scope="row">2</th>
       <td>Jacob</td>
       <td>Thornton</td>
       <td>@fat</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
    </tbody>
    </table>

    <script>
        function addRowHandlers() {
            var table = document.getElementById("tableId");
            var rows = table.getElementsByTagName("tr");
            for (i = 0; i < rows.length; i++) {
                var currentRow = table.rows[i];
                var createClickHandler =
                    function(row)
                    {
                        return function() {
                                                var cell = row.getElementsByTagName("td")[0];
                                                var id = cell.innerHTML;
                                                alert("id:" + id);
                                                window.location.href = "http://www.w3schools.com";
                                         };
                    };

                currentRow.onclick = createClickHandler(currentRow);
            }
        }
        window.onload = addRowHandlers();
    </script>
    </body>
    </html>
</code>```

Title: how to make bootstrap table clickable

Body:
try this code

<!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
    <table class="table table-striped" id="tableId">
     <thead>
        <tr>
         <th scope="col">#</th>
         <th scope="col">First</th>
         <th scope="col">Last</th>
         <th scope="col">Handle</th>
       </tr>
     </thead>
     <tbody>
      <tr>
        <th scope="row">1</th>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
     </tr>
     <tr>
       <th scope="row">2</th>
       <td>Jacob</td>
       <td>Thornton</td>
       <td>@fat</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
    </tbody>
    </table>

    <script>
        function addRowHandlers() {
            var table = document.getElementById("tableId");
            var rows = table.getElementsByTagName("tr");
            for (i = 0; i < rows.length; i++) {
                var currentRow = table.rows[i];
                var createClickHandler =
                    function(row)
                    {
                        return function() {
                                                var cell = row.getElementsByTagName("td")[0];
                                                var id = cell.innerHTML;
                                                alert("id:" + id);
                                                window.location.href = "http://www.w3schools.com";
                                         };
                    };

                currentRow.onclick = createClickHandler(currentRow);
            }
        }
        window.onload = addRowHandlers();
    </script>
    </body>
    </html>


答:
You can use XMLHTTP request to send the request. It is easier than your function and fully working. Check a sample request here XMLHTTP REQUEST
Let me know if you were successfull</p>

Title: PHP jQuery ajax submit button not working

Body:
I would like to create a dynamic form with add and remove field using jquery and ajax. but unfortunately,my insert button supposedly go to insert.php wont work.When I click insert button,nothing is happened. When the insert button clicked,it will be redirect to insert.php store data inside the database.Here is my coding

repeater.js

    jQuery.fn.extend({
        createRepeater: function (options = {}) {
            var hasOption = function (optionKey) {
                return options.hasOwnProperty(optionKey);
            };

            var option = function (optionKey) {
                return options[optionKey];
            };

            var generateId = function (string) {
                return string
                    .replace(/\[/g, '_')
                    .replace(/\]/g, '')
                    .toLowerCase();
            };

            var addItem = function (items, key, fresh = true) {
                var itemContent = items;
                var group = itemContent.data("group");
                var item = itemContent;
                var input = item.find('input,select');

                input.each(function (index, el) {
                    var attrName = $(el).data('name');
                    var skipName = $(el).data('skip-name');
                    if (skipName != true) {
                        $(el).attr("name", group + "[" + key + "]" + "[" + attrName + "]");
                    } else {
                        if (attrName != 'undefined') {
                            $(el).attr("name", attrName);
                        }
                    }
                    if (fresh == true) {
                        $(el).attr('value', '');
                    }

                    $(el).attr('id', generateId($(el).attr('name')));
                    $(el).parent().find('label').attr('for', generateId($(el).attr('name')));
                })

                var itemClone = items;

                /* Handling remove btn */
                var removeButton = itemClone.find('.remove-btn');

                if (key == 0) {
                    removeButton.attr('disabled', true);
                } else {
                    removeButton.attr('disabled', false);
                }

                removeButton.attr('onclick', '$(this).parents(\'.items\').remove()');

                var newItem = $("
" + itemClone.html() + "
");
                newItem.attr('data-index', key)

                newItem.appendTo(repeater);
            };

            /* find elements */
            var repeater = this;
            var items = repeater.find(".items");
            var key = 0;
            var addButton = repeater.find('.repeater-add-btn');

            items.each(function (index, item) {
                items.remove();
                if (hasOption('showFirstItemToDefault') && option('showFirstItemToDefault') == true) {
                    addItem($(item), key);
                    key++;
                } else {
                    if (items.length > 1) {
                        addItem($(item), key);
                        key++;
                    }
                }
            });

            /* handle click and add items */
            addButton.on("click", function () {
                addItem($(items[0]), key);
                key++;
            });
        }
    });

index.php

<?php
//session_start();
$servername = "localhost";
$username = "root";
$password = "bptm2012";
$dbname = "icompex";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "select panel_id,panel_kp,panel_nm from mem_panel";
$result = mysqli_query($conn, $sql);
?>
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Add Remove Panel Group and Category</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>

Kemaskini Ahli dan Kumpulan Panel Penilai

Menu Kumpulan dan Ahli Panel

                <form method="post" id="repeater_form">

                        Pilih Group

                        <select class="form-control" name="cat">

                            <option value="" disabled selected>Sila Pilih Kategori</option>
                            <option value="A">A - Rekabentuk Alam Bina & Rekabentuk Dalaman</option>
                            <option value="B">B - Pembinaan dan Bahan</option>
                            <option value="C">C - Mesin, Peralatan dan Proses Pergilangan</option>
                            <option value="D">D - ICT & Multimedia</option>
                            <option value="E">E - Elektrik, Elektronik dan Telekomunikasi</option>
                            <option value="F">F - Pengangkutan, Automatif & Penerbangan</option>
                            <option value="G">G - Pertanian, Alam Sekitar dan Tenaga Boleh Diperbaharui</option>
                            <option value="H">H - Pengajaran dan Pembelajaran</option>
                            <option value="I">I - Perkhidmatan dan Pemasaran Produk</option>
                        </select>
                        Sila Pilih Kumpulan Panel

                        <select name="group" class="form-control">
                            <option value="" disabled selected>Sila Pilih Kumpulan Panel</option>
                            <option value="1">Panel 1</option>
                            <option value="2">Panel 2</option>
                            <option value="3">Panel 3</option>
                            <option value="4">Panel 4</option>
                            <option value="5">Panel 5</option>
                            <option value="6">Panel 6</option>
                            <option value="7">Panel 7</option>
                            <option value="8">Panel 8</option>
                            <option value="9">Panel 9</option>
                            <option value="10">Panel 10</option>
                            <option value="11">Panel 11</option>
                            <option value="12">Panel 12</option>
                            <option value="13">Panel 13</option>
                            <option value="14">Panel 14</option>
                            <option value="15">Panel 15</option>
                        </select>

                            <button type="button" class="btn btn-primary repeater-add-btn">Tambah Ahli</button>

                                            Pilih Nama Ahli Panel
                                            <select class="form-control" data-skip-name="true" data-name="skill[]"
                                                    required>
                                                <?php
                                                echo "<option>Sila Pilih Ahli Panel</option>";
                                                if (mysqli_num_rows($result) > 0) {
                                                    // output data of each row
                                                    while ($row = mysqli_fetch_assoc($result)) {
                                                        echo '<option value="' . $row['panel_id'] . '">' . $row['panel_nm'] . '</option>';
                                                    }
                                                } else {
                                                    echo "<option>Maaf Belum ada pendaftaran ahli panel dibuat</option>";
                                                }

                                                mysqli_close($conn);
                                                ?>
                                            </select>

                                            <button id="remove-btn" class="btn btn-danger"
                                                    onclick="$(this).parents('.items').remove()">Remove
                                            </button>

                        <input type="submit" name="insert" class="btn btn-success" value="insert"/>

                </form>

insert.php

<?php

connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

if (isset($_POST["name"])) {
    $skill = implode(", ", $_POST["skill"]);

    $data = array(
        ':panel_cat' => $_POST["cat"],
        ':panel_group' => $_POST["group"],
        ':panel_mem' => $skill
    );

    $query = "
 INSERT INTO panel_penilai
 (panel_cat, panel_group,panel_mem)
 VALUES (:panel_cat, :panel_group, :panel_mem)
 ";

    $statement = $connect->prepare($query);
    if ($statement->execute($data)) {
        echo '

   Data Successfully Inserted

  ';
    }
}

//?>