serdar aksoy
serdar aksoy

Reputation: 23

How can put my values to mysql from my php table with jquery ajax method

<div id="kutu">
<?php
    echo "<table ' border='1' width='200px'>";
    echo "<tr>";
    echo "<th>#</th>";
    echo "<th>Oyuncu Adi</th>";
    echo "</tr>";
    for ($x = 1; $x <= $playernum; $x++) {
        echo "<tr>";
        echo "<td>$x </td>";
        echo "<td><input id='serdar' type='text' name='player$x'  > </td>";
        echo "</tr>";
    }
    echo "</table>";

?>
<p> <input type="submit" value="Kayit Et!"></p>

</div>

Im taking $playernum from other page. In this table I will take players name and I wanna put this names to my mysql db with javascript ajax method. But I couldnt find the way.

My table looks like:

enter image description here

Upvotes: 0

Views: 36

Answers (1)

dragonslayer
dragonslayer

Reputation: 26

I suggest you change your input-text to the same name like this, instead of player$x:

<form method="POST">
    <input type="text" name="player" /><br />
    <input type="text" name="player" /><br />
    <input type="text" name="player" /><br />
    <input type="text" name="player" />
    <p id="result"></p>
    <button id="btn">Get Player Names</button>
</form>

For the javascript:

<script>
    $("form").submit(function(e) {
        e.preventDefault();

        players = document.getElementsByName("player");
        var result = [];

        for (var i = 0; i < players.length; i++) {
            result[i] = players[i].value;
        }

        $.post(
            'index.php', {
                data: result
            },
            function(msg) {
                document.getElementById("result").innerHTML = msg;
            }
        );
    });
</script>

I just created an empty array and stored the values of each input into it. Then sent that array over to the PHP file.

For the index.php file:

$data = $_POST["data"];
echo "From PHP<br/>";

foreach ($data as $d){
    echo $d . "<br/>";
}

So you can use the variable $d to access individual player names.

Result image

Upvotes: 1

Related Questions