简体   繁体   English

将 JavaScript 变量存储在 php 变量中,无需页面刷新

[英]Store JavaScript variable in a php variable without page refresh

I've been been through numerous articles on here and tried dozens of variations including ajax. What I want to do is click a button and store the id of that button in a php variable without having to refresh the page.我在这里阅读了大量文章并尝试了数十种变体,包括 ajax。我想要做的是单击一个按钮并将该按钮的 ID 存储在 php 变量中,而无需刷新页面。

I've tried using isset and POST and I get some variation of Undefined key array.我试过使用 isset 和 POST,我得到了一些未定义键数组的变体。

Ajax was suggested but when I use ajax I can get the variable stored, but I'm unable to get it into a php variable.建议使用 Ajax,但当我使用 ajax 时,我可以获取存储的变量,但无法将其放入 php 变量中。

Current setup...当前设置...

I have an HTML button from which I need the id stored in a php variable so I can use it in another SQL statement.我有一个 HTML 按钮,我需要从中将 id 存储在 php 变量中,以便我可以在另一个 SQL 语句中使用它。 This button is part of an HTML table of MySQL records returned from the db.此按钮是从数据库返回的 MySQL 条记录的 HTML 表的一部分。

<input type='button' value='Edit' name='editbtn' onclick='edit(this.id)' id =  '" . $row['id'] . "'/> 

JavaScript... JavaScript...

function edit(clicked_id){
        var selid = clicked_id;
        var seleid = selid.toString();
        $.ajax({
            type: 'post',
            data: {name: seleid},
            datatype: 'text',
            success: function(data){
                console.log(name);
                alert("Success, data is: " + data);  // This correctly returns the id of the button clicked
            },
     });
} 

The PHP at the top of the page is...页面顶部的PHP是...

if(isset($_POST['name']) && !empty($_POST['name'])){
    ob_clean();
    $varid = $_POST['name'];
    echo $varid;
    exit; 
}

PHP is not receiving anything. PHP 没有收到任何东西。 Is there a way to do this?有没有办法做到这一点? I guess it's a backend/frontend issue?我想这是后端/前端问题?

Note: I have been able to store a JavaScript variable in an HTML tag but I've been unable to use it as part of a SQL statement, even after trimming the tags off of it.注意:我已经能够将 JavaScript 变量存储在 HTML 标签中,但我无法将其用作 SQL 语句的一部分,即使在删除标签后也是如此。

Please help and thank you!请帮忙,谢谢!

Try something like this in your php code:在您的 php 代码中尝试这样的事情:

$data = json_decode(file_get_contents('php://input'), true);
if(isset($data['name']) && !empty($data['name'])){
    ob_clean();
    $varid = $_POST['name'];
    echo $varid;
    exit; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM