Pass Variables from JavaScript to Php

0

Well I want to pass a variable of js to another php document they told me that the most practical thing is using ajax, but I think something is not right: / I want to pass the variable from a document .js to one .php. when passing the variable does not detect it in the php, and I do not know if I am making good use of ajax.

function showScore()
{
   $("#scoreboard").css("display", "block");
   setBigScore(true);
  
   if(score > highscore)
   {
     
      highscore = score;
    
      setCookie("highscore", highscore, 999);
   }
//AQUI COMIENZO A PASAR LA "VARIABLE"
    var elscorebest = score;
      $.ajax({
                data:  {score:elscorebest},
                url:   'ACTIONSCORE.php',
                type:  'post',
                success:  function (response) {
                        if (response === 'SI') window.location = "../Juegos/GamLocker/index.php";
                }
        });
and this is what my php does

<?php
session_start();
if($_SESSION['id']) {
$idder = $_SESSION['id'];
$varscore = $_POST['score'];
require("connect_db.php");
$veri=mysql_query("SELECT id FROM users WHERE id='".$idder."' ", $link);

  if($veri==true){
      $sql = "UPDATE users SET criptcoins='$varscore' WHERE id='$idder'";
     $result = mysql_query($sql); 
     die($varscore);
      header("location: ../index.php");
  }else{
    echo '<script>alert("MAL NO DETECTA SESSION")</script>';
echo "<script>location.href='../index.php#error de pasar db'</script>";  
  }

     
   }else{
 echo '<script>alert("Ingresa Sesion")</script>';
echo "<script>location.href='../index.php#error de sesion'</script>";
}

?>
    
asked by Pablo Cripting Step 04.03.2017 в 05:00
source

1 answer

1

possible solutions:

1) check the value of the variable var elscorebest that is not empty

2) try with method : 'POST', and you also have to specify the data type dataType : 'json'

var request = $.ajax({
                    method : 'POST',
                    url    : 'ACTIONSCORE.php',
                    data:  {score:elscorebest},
                    dataType    : 'json' 
                });

a good practice is to capture the errors, I'll give you an example, insert it below the ajax call

request.done(function(response) { 
                    if(response.status) {
                        alert('Success: ' + response.result + "\n Message: " + response.message);

                    }
                    else {
                        alert('Error: ' + response.message);
                        window.location.href = window.location.href;
                    }
                });

                request.fail(function(jqXHR, textStatus) {
                    alert("Server request failed: " + textStatus);
                    window.location.href = '';
                });
    
answered by 04.03.2017 в 05:32