简体   繁体   中英

Trouble receiving Javascript variable when sent to PHP

Problem: Trouble receiving what is being sent to my PHP document.

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:

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. I'll note that I'm using form id but getting the value from an input.

Ramblings I'm trying to send a user input that has been validated and sliced to mySQL database.

I achieved the string I wanted with javascript and passed it to a variable.

I'm trying to send it to a separate php file in another folder with a request.send(the_javaS_variable).

Now in the console I can see the variable holds the correct text value and I see it sending with state 4 and 200.

But it never shows up on the submit.php page.

try this and remove the 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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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