Pass The Container text span id to a PHP Variable


I have a Video Game programmed in HTML and JavaScript from which I wish to pass the points obtained to the MySQL Database and I can not find the correct way to achieve it.

JavaScript Code:

function updateScore(){
    var score = (snakeLength - startLength) * 10;
    document.getElementById('score').innerHTML = score;

function gameScore() {
    var highScore = localStorage.getItem("high-score");
    var score = (snakeLength - startLength) * 10;
    if (score > highScore) {
        localStorage.setItem('high-score', score);
    } else {

HTML code (shows the current points of the game):

Puntos: <span id="score">0< /span>

PHP Code:

I need to perform an update of points in my Database but I do not know how to pass the <span id="score"> tag to a PHP variable. For AJAX it would be ideal but it is more difficult for me.

// Necesito El Resultado en Point 
mysql_query("UPDATE game SET point=$VARIABLE_PUNTOS ");
asked by Bryan B Weiss 15.01.2016 в 03:20

2 answers


You are trying to avoid using AJAX, however, it is not very difficult to do so. Using jQuery you do the POST with the information of score :

request = $.ajax({
    url: "/score.php",
    type: "post",
    data: {
        "score": $("#score").text()
request.done(function(response) {
}); {


$score = $_POST['score'];
mysql_query("UPDATE game SET point=$score ");

It is better to prevent, it would be better to use mysql_real_escape_string to avoid SQL injection :

$score = mysql_real_escape_string($_POST['score']);
mysql_query("UPDATE game SET point=$score ");

Since you are using HTML and JavaScript in your game, I would recommend you use a cloud Database Parse . You can save yourself a lot of headaches.


Remember that if the attribute is a class :

<span class="current-score">0</span>

You must use . instead of # , # is for when you use id :

var score = $(".current-score").text();

If you need to pass it to whole and add it you can use parseInt :

var score = parseInt($(".current-score").text()) + 50;
answered by 15.01.2016 / 03:47

Very good your answer was doing something similar and it helped me a lot.

Here I leave my code

<script language="JavaScript" type="text/JavaScript">                          
    //Metodo para cargar el formulario **************** AQUI USO ALGO DIFERENTE PARA PODER LEER EL id DEL DIV ******
    $("body").on('submit', '#formOrder', function(event) {
    if ($('#formOrder').valid()) {
        type: "POST",
        url: "imagesOrderProcesar.php",
        dataType: "json",
        data: {
        "Order": $("#output").text()
        success: function(respuesta) {
                    if (respuesta.error == 1) {
                        setTimeout(function() {
                        }, 1000);

                    if (respuesta.exito == 1) {

    function Salir() {
answered by 13.12.2016 в 23:01