为什么我的SQL插入重复

时间:2016-06-15 13:22:20

标签: mysql ajax laravel-5 laravel-blade

所以我在到达服务器并执行的客户端页面上有一个AJAX调用。但是,对于每次提交,我都会收到2个插入语句。我无法弄清楚这第二个插入物的来源。也许一组新的眼睛可以为它提供一些启示。

表格(在.blade.php中):

{!! Form::open(array('action'=>'PhishingController@createNewProject')) !!}
{!! Form::label('projectNameText','Project Name: ') !!}
{!! Form::text('projectNameText',null,array('name'=>'projectNameText')) !!}
{!! Form::label('projectAssigneeText','Project Assignee') !!}
{!! Form::text('projectAssigneeText',null,array('name'=>'projectAssigneeText')) !!}
{!! Form::submit('Submit',array('id'=>'submitButton')) !!}
{!! Form::close() !!}

PHP控制器:

$projectName = $request->input('projectNameText');
$projectAssignee = $request->input('projectAssigneeText');
$date = date("Y-m-d");
$db = $this->openDatabaseDefault();
$sql = "INSERT INTO database.table(PRJ_ProjectId,PRJ_ProjectName,PRJ_ProjectAssignee,PRJ_ProjectStart,
            PRJ_ProjectLastActive,PRJ_ProjectStatus,PRJ_ProjectTotalUsers,PRJ_EmailViews,PRJ_WebsiteViews,
            PRJ_ProjectTotalReports) VALUES (null,'$projectName','$projectAssignee','$date','$date','Inactive',0,0,0,0);";
if(!$projects = $db->query($sql)) {
        echo "Sorry, the website is experiencing technical difficulties.";
        echo "Error: Our query failed to execute and here is why: \n";
        echo "Query: " . $sql . "\n";
        echo "Errno: " . $db->errno . "\n";
        echo "Error: " . $db->error . "\n";
        exit;
}
$db->close();
return redirect()->to('http://localhost:8888/generateEmails');

AJAX:

$('document').ready(function() {
    $('#submitButton').click(function(e) {
        $.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
        });
        console.log("clicked");
        var projectName = $('#projectNameText').val();
        var projectAssignee = $('#projectAssigneeText').val();
        $.ajax({
            method: "POST",
            //url: "http://localhost:8888/projects/create",
            data: {projectNameText: projectName, projectAssigneeText: projectAssignee}
        })
    });
});

此时感谢任何事情。

1 个答案:

答案 0 :(得分:0)

感谢Alex对概念性ajax的改变。事实证明PHP重定向导致我的方法在重定向之前再次触发。不知道为什么,但通过将重定向推送到AJAX成功函数,它修复了我的重复插入。

修订AJAX:

$.ajax({
    method: "POST",
    data: {projectNameText: projectName, projectAssigneeText: projectAssignee},
    success: function() {
        window.location.replace("http://localhost:8888/generateEmails");
    },
    error: function(xhr,status,error) {
        alert('Unable to create new project.');
        console.log("xhr: " + xhr);
        console.log('status: ' + status);
        console.log('error: ' + error);
    }
});