无法通过Ajax添加到数据库

时间:2012-05-21 18:28:34

标签: php ajax database

单击提交按钮时,应返回所选奖牌的ID并通过Ajax插入数据库。但这似乎不起作用。有人知道发生了什么或者我做错了什么吗? 这是形式:

<form action="" method="post">
<?php

            while($medal = $allMedals->fetch_assoc())
                {
                    echo "<img src='" . $medal['imagepath'] . "' />";
                    echo "<input type='radio' name='radio' class='selectmedal' value='" . $medal['medalid'] . "' />";
                }

?>
            <input type='submit' value='Nominate' id='submitknop' onclick='geklikt()'/>
</form>

这是函数geklikt:

function geklikt(){
        alert($("#selectmedal").val());
        var medalid = $(".selectmedal").val();
        var data = { selectmedal:medalid };

        $.ajax({
            type: "POST",
            url: "ajax/medal_save.php",
            data: data
        }).done(function( msg ) {
            $(".feedback").text(msg.message);
        });

        return false;

警报正在显示,但与所选的每枚奖牌显示相同的ID(ID 3)。这是medal_save.php中的代码:

<?php
    include('../classes/Nomination.class.php');

    if(!empty($_POST['selectmedal']))
    {
        $nomination = new Nomination();
        $nomination->Medal = $_POST['selectmedal'];
        try
        {
            $nominate->Save();
            $feedback ['message'] = "Nomination succes!";
            $feedback ['status'] = "success";
        }
        catch(Exception $e)
        {
            $feedback ['message'] = $e->getMessage();
            $feedback ['status'] = "error"; 
        }   
    }
    else
    {
        $feedback ['message'] = "Please select a medal";
        $feedback ['status'] = "error";     
    }
    header('Content-type: application/json');
    echo json_encode($feedback);
?>

提前致谢!

1 个答案:

答案 0 :(得分:0)

看起来你需要获得选中 radiobutton

 $('input[name=radioinputname]:checked', '#yourformid').val();

如果你实际上并没有说你想要属性id(?) 如果是这样的话

 $('input[name=radioinputname]:checked', '#yourformid').attr("id");

所以

<form action="" method="post" id="myradioform">
   <?php

        while($medal = $allMedals->fetch_assoc())
            {
                echo "<img src='" . $medal['imagepath'] . "' />";
                echo "<input type='radio' name='radioinputname' 
                      class='selectmedal' value='" . $medal['medalid'] . "' />";
            }

      ?>
        <input type='submit' 
         value='Nominate' id='submitknop' onclick='geklikt()'/>
  </form>

<script type="text/javascript">
   function geklikt(){
    alert($("#selectmedal").val());

    /* here */
    var medalid = $('input[name=radioinputname]:checked', '#myradioform').val();

   /* or if you actually meant to you want the attribute id */
   /*
  var medalid =  $('input[name=radioinputname]:checked', '#myradioform').attr("id");
 */

    var data = { selectmedal:medalid };

    $.ajax({
        type: "POST",
        url: "ajax/medal_save.php",
        data: data
    }).done(function( msg ) {
        $(".feedback").text(msg.message);
    });

    return false;
  }
  </script>