简体   繁体   中英

How to pass a PHP value from one PHP page to another PHP page through JavaScript?

In my allcomment.php page I have this code:

$(document).ready(function() {
    var data = {
        fn: "<?php echo $thelimnid;?>",          
    };
    $.post("loadcomment/fetch_comments.php", data);       
});

I want to send the value of fn to fetch_comments.php page. In fetch_comments.php page:

<?php
    $fn  = $_POST['fn'];
    echo $fn;
?>

but it does not work.

How can do this?

Requests are requests. That means if you make a request for fetch_comments.php file you want to get something back (because this is how requests work). If you request coffee in a restaurant you're saying I want coffee and sending money. Your money are transformed into coffee. Same is here: you're requesting something and it's transformed in your fetch_comments.php file so this file can return you something back.

Avoid using shorthand ajax and go for it to debug it better:

$.ajax({
    type: "POST",
    data: {
        fn: "<?php echo $thelimnid;?>",
    },
    dataType: "json",
    url: "fetch_comments.php",
    success: function (response) {

    }
})

Btw. Your data:

var data = {
   fn: "<?php echo $thelimnid;?>",          
};

is not going to execute anything in your fetch_comments.php file.

Lets send for example something like that:

var data = {
   fn: "sayThat",          
};

Then in your fetch_comments.php file just do this:

if($_POST['fn'] === 'sayThat')
    echo $whateverYouWant;

Please also keep in mind that this echo is going back to your JavaScript. In case of ajax example I've send you above this echo will be shown in here:

success: function (response) {
    // response is your $whateverYouWant that you echoed                                
}

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