简体   繁体   English

发送到PHP时无法接收Javascript变量

[英]Trouble receiving Javascript variable when sent to PHP

Problem: Trouble receiving what is being sent to my PHP document. 问题:无法接收发送到我的PHP文档的内容。

Javascript: 使用Javascript:

$('#form_id').submit(function(event){
    event.preventDefault();
    event.stopPropagation();
    var message;
    var myRegExp = validation stuff
    var urlToValidate = document.getElementById("url").value;
    if (!myRegExp.test(urlToValidate)){
        }else{
    var code = (urlToValidate).slice(-22)
    var request = new XMLHttpRequest();

    request.addEventListener('readystatechange', function(event){
    if (this.readyState == 4){
        if (this.status ==200){
            console.log (this.status);
        }else{
            console.log('Server replied with HTTP status ' + this.status);
        }
    }
});

request.open('POST', 'php/submit.php', true);
request.setRequestHeader('Content-Type', 'text/plain');

request.send("code=" + code);
}   
});

Then I'm using this code on my php/submit.php: 然后,我在php / submit.php上使用以下代码:

if (!empty($_POST['code'])) { 
    $code = $_POST['code'];
    echo $code; 
};

I feel like I'm not using the right tag names for PHP because I'm new to all of this. 我觉得我没有为PHP使用正确的标记名,因为我是所有这些的新手。 I'll note that I'm using form id but getting the value from an input. 我会注意到我使用的是表单ID,但要从输入中获取值。

Ramblings I'm trying to send a user input that has been validated and sliced to mySQL database. 我正在尝试将经过验证的用户输入发送到mySQL数据库。

I achieved the string I wanted with javascript and passed it to a variable. 我用javascript实现了想要的字符串,并将其传递给变量。

I'm trying to send it to a separate php file in another folder with a request.send(the_javaS_variable). 我正在尝试使用request.send(the_javaS_variable)将其发送到另一个文件夹中的单独php文件。

Now in the console I can see the variable holds the correct text value and I see it sending with state 4 and 200. 现在在控制台中,我可以看到变量保存了正确的文本值,并且看到它以状态4和200发送。

But it never shows up on the submit.php page. 但是它永远不会显示在submit.php页面上。

try this and remove the console.log() 试试这个并删除console.log()

$('#form_id').submit(function(event){
    var myRegExp = validation stuff
    var urlToValidate = document.getElementById("url").value;
    if (!myRegExp.test(urlToValidate)){
        // failed
    }else{

        var code = 'code='+(urlToValidate).slice(-22);

        $.post('php/submit.php', code, function() {
            //   success stuff
        });

    }
    return false;
});

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

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