使用ajax发布按钮值

huangapple go评论78阅读模式
英文:

Posting button values using ajax

问题

我正在尝试使用Ajax的POST方法将一个值发送到PHP脚本,但是我得到了以下错误消息:

>注意:未定义索引:gamekey

以下是我的JavaScript代码:

function adminchat(row) {
    var to_user_id = $('#start_chat_' + row).data('key_' + row);
    var dataString = 'gamekey=' + to_user_id;

    fetch_chat();

    setInterval(function () {
        fetch_chat();
    }, 5000);

    setInterval(function () {
        autoRefresh_div();
    }, 1000);

    function fetch_chat() {
        $.ajax({
            url: 'admin_dispute_handler.php',
            data: dataString,
            type: 'post',
            success: function () {
                window.location = 'admin_dispute_handler.php';
            },
            error: function (request, status, error) {
                alert(error);
                alert(status);
                alert(request);
            }
        });
    }

    function autoRefresh_div() {
        $("#result").load("load.php").show(); // 在x秒后从其他文件加载数据的函数
    }
};

以下是HTML代码:

<button type="button" class="btn btn-info btn-xs start_chat" id="start_chat_1" onclick="adminchat(1)" data-key_1="34354661" data-toggle="modal" data-target="#exampleModal">开始聊天</button>

引发问题的PHP代码段如下:

<?php
if ($_SESSION['logged_in'] == FALSE) {
    header("Location:http://localhost/the_site/login/login.html");
} else {
    require_once 'connection.php';

    $conn = new mysqli(host, user, password, db);
    session_start();
    $Game_key   = $_POST['gamekey'];
    $_SESSION['gamekey'] = $_POST['gamekey'];
    $username   = $_SESSION['username'];
    $query = "SELECT gamername, score From ongoing_game_list Where Game_Key = $Game_key";

    $result = $conn->query($query);

    /* 数值数组 */
    $row = $result->fetch_array(MYSQLI_ASSOC);

    $gamername  = $row["gamername"];
    $score      = $row["score"];
}
?>
英文:

I am trying to post a value to a php script using post method in ajax, however I am getting
>Notice: Undefined index: gamekey

The following is my JavaScript code

function adminchat(row) {
    var to_user_id = $(&#39;#start_chat_&#39; + row).data(&#39;key_&#39; + row);
    var dataString = &#39;gamekey=&#39; + to_user_id;

    fetch_chat()

    setInterval(function () {
        fetch_chat();
    }, 5000)

    setInterval(function () {
        autoRefresh_div();
    }, 1000);

    function fetch_chat() {
        $.ajax({
            url: &#39;admin_dispute_handler.php&#39;,
            data: dataString,
            type: &#39;post&#39;,,
            success: function () {
                window.location = &#39;admin_dispute_handler.php&#39;;
            },
            error: function (request, status, error) {
                alert(error);
                alert(status);
                alert(request);
            }
        });
    }

    function autoRefresh_div() {
        $(&quot;#result&quot;).load(&quot;load.php&quot;).show(); // a function which will load data from other file after x seconds
    }

};

Below is the html:

&lt;button type=&quot;button&quot; class=&quot;btn btn-info btn-xs start_chat&quot; id=&quot;start_chat_1&quot; onclick=&quot;adminchat(1)&quot; data-key_1=&quot;34354661&quot; data-toggle=&quot;modal&quot; data-target=&quot;#exampleModal&quot;&gt;Start Chat&lt;/button&gt;

The section of the php code giving me issue:

&lt;?php
    if ($_SESSION[&#39;logged_in&#39;]==FALSE) {
        header(&quot;Location:http://localhost/the_site/login/login.html&quot;);
    } else {
        require_once &#39;connection.php&#39;;
    
        $conn = new mysqli(host,user,password,db);
        session_start();
        $Game_key   = $_POST[&#39;gamekey&#39;];
        $_SESSION[&#39;gamekey&#39;] = $_POST[&#39;gamekey&#39;];
        $username   = $_SESSION[&#39;username&#39;];
        $query = &quot;SELECT gamername,score From ongoing_game_list Where Game_Key = $Game_key&quot;;
        
        $result = $conn-&gt;query($query);
        
        /* numeric array */
        $row = $result-&gt;fetch_array(MYSQLI_ASSOC);
    
        $gamername  = $row[&quot;gamername&quot;];
            $score      = $row[&quot;score&quot;];
    }
?&gt;

答案1

得分: 1

首先,你的代码中有一个语法错误,type: 'post',,应该改为type: 'post',,浏览器应该在开发者控制台中显示错误消息。并且在.ajax()中使用对象作为参数:

$.ajax({
    url: 'admin_dispute_handler.php',
    data: {
        gamekey: to_user_id
    },
    // 原始代码是:type: 'post',,
    type: 'post',
    success: function () {
        window.location = 'admin_dispute_handler.php';
    },
    error: function (request, status, error) {
        alert(error);
        alert(status);
        alert(request);
    }
});

你可以在官方文档示例部分了解更多关于jQuery AJAX的用法。

英文:

First, you have a syntax error on type: &#39;post&#39;,,, browser should raise an error message on developer console. And use object as param in .ajax():

$.ajax({
    url: &#39;admin_dispute_handler.php&#39;,
    data: {
        gamekey: to_user_id
    },
    // Original is: type: &#39;post&#39;,,
    type: &#39;post&#39;,
    success: function () {
        window.location = &#39;admin_dispute_handler.php&#39;;
    },
    error: function (request, status, error) {
        alert(error);
        alert(status);
        alert(request);
    }
});

You can learn more about jQuery AJAX usage at official docs example section.

答案2

得分: 0

如果在重定向后遇到问题,请尝试以下解决方案:

$headers = apache_request_headers();
$is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');

在这里,如果使用 AJAX 发送请求,则$is_ajax 为真,否则返回假(null)。

希望这对您有所帮助。

英文:

If you facing issue after redirecting then try below solution

$headers = apache_request_headers();
$is_ajax = (isset($headers[&#39;X-Requested-With&#39;]) &amp;&amp; $headers[&#39;X-Requested-With&#39;] == &#39;XMLHttpRequest&#39;);

here you got $is_ajax true if send request using AJAX other wise return false(null).

Hope this help to you.

huangapple
  • 本文由 发表于 2020年1月6日 17:08:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609299.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定