我的ajax调用只工作一次,但除非我刷新页面,否则它不再工作

时间:2017-06-01 09:57:12

标签: php jquery ajax

我正在尝试使用Ajax执行表单。这是我想要输入的html部分

 <form class="col s12">
        <div class="row">
            <div class="input-field col s6">
                <i class="material-icons prefix">mode_edit</i>
                <textarea id="icon_prefix2" class="materialize-textarea" name ="discussion"></textarea>
                <input type="hidden" name="user" value="<?php echo $_SESSION['userid'];?>">
                <input type="hidden" name="id" value="<?php echo(rand(1000,99999)); ?>">
                <input type="hidden" name="date" value="<?php echo date("d.m.Y"); ?>">
                <input type="hidden" name="time" value="<?php echo date("h:i:s"); ?>">
                <label for="icon_prefix2">Start your discsussion</label>
                <input type="submit" class="btn waves-effect waves-light right" value="post">
            </div>
        </div>
    </form>

和ajax调用是

$(function () {

    $('form').on('submit', function (e) {

        e.preventDefault();

        $.ajax({
            type: 'post',
            url: 'cardiosubmit.php',
            data: $('form').serialize(),
            success: function () {
                alert('successfully posted')
            },
            error: function () {
                alert('error')
            }

        });

    });

});

这是将值存储在DB中的php代码:

<?php

session_start();


include_once('include/config.php');

$conn = config();

$uname = $_POST['user'];
$uid = $_POST['id'];
$val = $_POST['discussion'];
$date = $_POST['date'];`enter code here`
$time = $_POST['time'];

if (!$conn) {
$msg = "connection failed";
die($msg);
} else {
$query = "INSERT into cardiocase (id,uid,val,date,time) VALUES 
(?,?,?,?,?);";
$stmt = $conn->prepare($query);
$stmt->bind_param('sssss',$uid,$uname,$val,$date,$time);

if($stmt->execute()){
    echo "success";
}else{
    echo "fail";
}
$stmt->close();

}

第一次存储该值。但是在我尝试再次输入成功消息后,它只是说已成功发布,但是当我检查数据库时,值不存在。如果我刷新页面并再次尝试存储它。

5 个答案:

答案 0 :(得分:1)

问题在于这一行

<input type="hidden" name="id" value="<?php echo(rand(1000,99999)); ?>">

第一次进行ajax调用时,新行将被插入到表中,例如id&#34; 123&#34;现在,在进行下一个ajax调用时,您的ID仍然相同,并且您正在尝试向具有重复主键的表添加新行。

每次进行ajax调用之前,请尝试生成新的id(可能是通过javascript)。

$(function () {

    $('form').on('submit', function (e) {

        e.preventDefault();

        //Generate random id for very ajax request.
        $("[name='id']").val(Math.floor(Math.random() * 100));

        $.ajax({
            type: 'post',
            url: 'cardiosubmit.php',
            data: $('form').serialize(),
            success: function () {
                alert('successfully posted')
            },
            error: function () {
                alert('error')
            }

        });

    });

});

答案 1 :(得分:0)

改善你的代码:

<form class="col s12">
    <div class="row">
        <div class="input-field col s6">
            <i class="material-icons prefix">mode_edit</i>
            <textarea id="icon_prefix2" class="materialize-textarea" name ="discussion"></textarea>
            <label for="icon_prefix2">Start your discsussion</label>
            <input type="submit" class="btn waves-effect waves-light right" value="post">
        </div>
    </div>
</form>

删除隐藏字段

然后在php文件中:

 <?php
session_start();


include_once('include/config.php');

$conn = config();

$uname = $_SESSION['userid'];
$uid = echo(rand(1000,99999));;
$val = $_POST['discussion'];
$date = date("d.m.Y");
$time = date("h:i:s");

if (!$conn) {
$msg = "connection failed";
die($msg);
} else {
$query = "INSERT into cardiocase (id,uid,val,date,time) VALUES 
(?,?,?,?,?);";
$stmt = $conn->prepare($query);
$stmt->bind_param('sssss',$uid,$uname,$val,$date,$time);

if($stmt->execute()){
    echo "success";
}else{
    echo "fail";
}
$stmt->close();

}

答案 2 :(得分:0)

使用preventDefault()来避免表单提交。

$('body').on("click", '.btn', function (e) {
        e.preventDefault(); // prevent default functionality
        // run AJAX

 });

看起来JS在某处出现了错误 用来看看什么是AJAX结果

 $.ajax({
            type: 'post',
            url: 'cardiosubmit.php',
            data: $('form').serialize(),
            success: function () {
                alert('successfully posted')
            },
            complete: function (data, textStatus) {
                console.log(JSON.stringify(data));
                console.log(textStatus);
            }
        });

答案 3 :(得分:0)

使用以下代码 更改HTML <button class="btn waves-effect waves-light right trigger-submit" value="post">POST</button>

中的ur按钮

使用此

更新js代码

'$(&#34; .trigger提交&#34)关闭。(&#34;单击&#34);  $(&#34; .trigger-submit&#34;)。on(&#34; click&#34;,function(){    $就({             输入:&#39; post&#39;,             url:&#39; cardiosubmit.php&#39;,             数据:$(&#39; form&#39;)。serialize(),             成功:function(){                 提醒(&#39;已成功发布&#39;)             },             错误:function(){                 警报(&#39;错误&#39;)             }

    });

});`

答案 4 :(得分:0)

   <form action="cardiosubmit.php" class="col s12" id="myfrm" method="post" name="myfrm" >     
<div class="row">
    <div class="input-field col s6">
        <i class="material-icons prefix">mode_edit</i>
        <textarea id="icon_prefix2" class="materialize-textarea" name ="discussion"></textarea>
        <label for="icon_prefix2">Start your discsussion</label>
        <input type="submit" class="btn waves-effect waves-light right" value="post">
    </div>
</div>   
</form>
 <script type="text/javascript">   
 var frm = $('#myfrm');   

frm.submit(function (e) {

    e.preventDefault();

    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data) {
            console.log('Submission was successful.');
            console.log(data);
        },
        error: function (data) {
            console.log('An error occurred.');
            console.log(data);
        },
    });
});


    试试这个!!!