Maky-chan
Maky-chan

Reputation: 39

Ajax - Notice: Undefined index: id

I'm learning all this php and script things, but I'm having problems with sending the information to the php. I hope you can help me. Thank you. This is the problem:

Notice: Undefined index: id in ** on line 103

Php:

<?php 
echo $_POST['id']; //<< This is line 103
$sql = "SELECT id as ids,position FROM workerPosition WHERE '".$_POST['id']."'=id";
$rs = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($rs);
echo "Codigo:  <input type='text' name='ids' value='".$row['ids']."' disabled></br>";
echo "Nombre:  <input type='text' required='required' name='position'  placeholder='Max 50 caracteres' maxlength='50' value='".$row['position']."'>"; ?>

Script:

$(document).ready(function() {
    $(".edit-position").click(function () {
        var id = $(this).attr('id') 


        $.ajax({
        type: "POST",
        data: {id:id},
        url: "editPosition.php",
        }).done(function( data ) {
            location.href = "editPosition.php"
        });
    });
}); 

HTML:

while($row = mysql_fetch_array($result))
{
echo "<tr id='". $row['id'] ."'>";
echo "<td>" . $row['position'] . "</td>";
echo "<td class='buto' id='". $row['id'] ."'> <input type='submit' class='edit-position' id='". $row['id'] ."' value='Edit' /></td>";
echo "</tr>";
 }

Upvotes: 1

Views: 1164

Answers (1)

nickell
nickell

Reputation: 389

It looks like your ajax call is going to have the correct id in the POST variable, but when you do the location.href back to that editPosition.php file again, there's no POST variable, so that's when you're seeing that problem.

I'd use a success callback in your ajax call.

$.ajax({
    type: "POST",
    data: {id:id},
    url: "editPosition.php",
    success: function(returnData) {
       console.log(returnData);
    }
});

Edit: I just saw your comment, if you want to programmatically go to the editPosition.php page with post data, you'll need to construct a hidden form that has editPosition.php as the action like so:

$('.edit-position').click(function() {
    var id = $(this).attr('id');
    var form = '<form method="post" action="editPosition.php"><input type="text" name="id" value="' + id + '" /></form>';
    $(form).submit();
});

Upvotes: 2

Related Questions