简体   繁体   中英

Pass variable to PHP with JS

I have an HTML form which i populate from a database. On submit we load a page called "viewgame.php". Now what i want is here to run some scripts to populate some tables with data but how exactly can i pass the variable which i got from the form ex. $_POST['gameNo'] to the other php file though JavaScript?

Below is some of my code JS function

function refreshGameinfo() {
    var load = $.get('gameinfo_sc.php');
    $(".gameinfo").html('Refreshing');
    load.error(function() {
        console.log("Mlkia kaneis");
        $(".gameinfo").html('failed to load');
        // do something here if request failed
    });
    load.success(function(res) {
        console.log("Success");
        $(".gameinfo").html(res);
    });
    load.done(function() {
        console.log("Completed");
    });
}

How can i pass the $POST_['gameNo'] to the gameinfo_sc.php file so that i can get the correct results?

Try this

var load = $.get('gameinfo_sc.php',{gameNo:"1212"});

In your php file you can access it using

$_GET['gameNo']

For post method use

var load = $.post('gameinfo_sc.php',{gameNo:"1212"});

In your php file you can access it using

$_POST['gameNo']

You are trying to post $POST_['gameNo'] to gameinfo_sc.php but $.get isn't the right method for post, its actually for http get . you can also do this by using $.post http://api.jquery.com/jquery.post/

function refreshGameinfo() {
        $.ajax({
            type: "POST",
            url: "gameinfo_sc.php",
            data: {gameNo: data},
            cache: false,
            success: function(html){
                console.log( "Success" );
                $(".gameinfo").html(res);
            },
            error:function(html){
                console.log("Mlkia kaneis");
                $(".gameinfo").html('failed to load');
            }
        });
    }

try this

You can do it like this:

(in html layout):

<input type="hidden" id="gameNo" value="<?=$_POST['gameNo']?>" />

(in js file):

var gameNo = $('#gameNo').val();
var load = $.get('gameinfo_sc.php', {gameNo: gameNo});
....

UPDATE:

If your server doesn't support short open tags , you can write:

<input type="hidden" id="gameNo" value="<?php echo $_POST['gameNo'] ?>" />

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