LefterisL
LefterisL

Reputation: 1153

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?

Upvotes: 1

Views: 116

Answers (3)

Oleg
Oleg

Reputation: 23327

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'] ?>" />

Upvotes: 0

sas
sas

Reputation: 2597

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

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115272

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']

Upvotes: 3

Related Questions