简体   繁体   中英

What is the new proper way to pass a variable between Ajax code and a PHP file?

I am writing a login page for a web application. I am using ajax to pass a user name and pwd to a php file. In the php file I started with the following code.

if(isset($_POST))
{
    $uname = $_POST['uname'];
    $pwd = $_POST['pwd'];
}

IntelliJ IDEA Ultimate with the php plugin is highlighting the "$_POST" superglobal indicating that " Deprecated global variable usage ".

What is the proper way to pass variables between Ajax code and PHP code?

( Or is this a false-positive on the part of the PHP plugin in IntelliJ IDEA? )

The Jquery/Ajax code:

    <script>
    $(Document).ready(function (){
        $('#but_submit').click(function(){
            let uname = $('#txt_uname').val().trim();
            let pwd = $('#txt_pwd').val().trim();
            // alert("Your values are: "+ org + ", " + uname + ", " + pwd);

            // Now validate the input values.
            $.ajax({
                type: 'post',
                url: './Conf/Login.php',
                data: {uname: uname, pwd: pwd},
                success: function (res){
                    // Do somethings here;
                }
            });
        });
    });
    </script>

Well $_POST will always be set, but might be empty. A better check would be

if ([] !== $_POST) { ... 

Another trick you might consider uses the Null coalescing operator . The following to would result in better error checking. Please refer to the manual.

$uname = $_POST['uname'] ?? false;
$pwd = $_POST['pwd'] ??= false;

You will use $_POST in you day to day, and if you get error just from using it consider it a false positive. Moving you cursor to the underlined text in IntelliJ and pressing option + enter will pull up a menu with possible fixes. Sometimes even auto fix the issues for you.. Note that even the auto fixes can be wrong. Use with caution.

As far as passing variables to JS I try to stay out of injection territory. Such being when you add js code from a php runtime and directly pass $variables into that code. This is dirty, but will get you by while just learning. Taking principles from react programming, using asynchronous calls with Ajax and JSON encoding/decoding is typically the way to go. You want all the information needed on the initial request to be present in the initial payload. Thus, the Ajax-all-the-time method is no good. For that initial data payload just set a js const equal to a php json_encoded string.

While it's not relevant, it's worth noting in PHP using arrays will be much faster than objects for manipulating data. This seems to be uncommon knowledge.

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