Chitoge Kirisaki
Chitoge Kirisaki

Reputation: 45

How to get variable from javascript to php?

I want to get a variable from the code value:

/* Link Skor */
Memory.prototype.cekSkor = function(){
    window.location = "./skor/index.php?value=" + this.numMoves;
}

Memory.prototype._winGame = function() {
    var self = this;
    if (this.options.onGameEnd() === false) {
        this._clearGame();
        this.gameMessages.innerHTML = 
            '<h2 class="mg__onend--heading">Keren!</h2>\
            <p class="mg__onend--message">Kamu memenangkan game ini dalam ' + this.numMoves + ' gerakan.</p>\
            <button id="mg__onend--restart" class="mg__button">Ingin Bermain Lagi?</button>\
            <button id="mg__onend--skor" class="mg__button">Cek Skor?</button>';
        this.game.appendChild(this.gameMessages);
        document.getElementById("mg__onend--restart").addEventListener( "click", function(e) {
            self.resetGame();
        });
        document.getElementById("mg__onend--skor").addEventListener( "click", function(e) {
            self.skor();
        });
    } else {
        // run callback
        this.options.onGameEnd();
    }
}

I want get the ( this.numMoves ) to another file is index.php

<?php
        $skornya = $_GET['value'];
        echo $skornya;
?>

when i run the web. i get error The value= not read

enter image description here

What need i do to solve this problem ?

Upvotes: 3

Views: 97

Answers (3)

Chromonav
Chromonav

Reputation: 773

Javascript runs on the client side while php runs on server side and the response of processed php server is sent to the client. So if you want to send a variable from javascript to php it is same as sending data from client to the server. So, you can do the following:

In Javascript:

var toSend = "hello" //variable to send.
$.ajax({
 type: "POST",
 url: url,
 data: toSend,
 success: success,
 dataType: dataType
});

In PHP use $_POST method for reading the data.

Upvotes: 0

Krispy19
Krispy19

Reputation: 1

The browser then interprets the text as HTML and JavaScript. If you want to get data from JavaScript to PHP then you need to make a new HTTP request and run a new (or the same) PHP script. You can make an HTTP request from JavaScript by using a form or Ajax.

Upvotes: 0

xuan hung Nguyen
xuan hung Nguyen

Reputation: 398

no way. =). In PHP just can receive $_GET, $_POST, $_REQUEST, or $data = json_decode( file_get_contents('php://input') );

If you want variable in javascript can be use in PHP. you must post it to server using with XMLHttpRequest in Javascript, ajax in jQuery. hope this help you

Upvotes: 1

Related Questions