-3

I am using javascript to retrieve a bunch of values from the Riot API, however I want to store them in my own database using php. For example, I'm trying to store the gameID and this is what I'm trying right now.

      <?php
        $insrt = "INSERT INTO game (gameId)
        VALUES (".<script>b.gameId</script>.")";
        mysqli_query($dbc, $insrt);
        ?>

I'm pretty sure that I'm not even close to correct but I'm not sure how to do this.

ghadams
  • 41
  • 6
  • 1
    You can't embed JavaScript variables in PHP. The two languages run at different times in different places. You need an AJAX call. –  May 30 '15 at 15:16
  • Your JavaScript stuff happens on a client pc somewhere while PHP will be running on your website. Somehow you will need to make the JavaScript code "talk" to the server. In the old days this was done by submitting a
    . Nowadays you would probably be using some form of Ajax (asynchronous HTTP).
    – Carsten Massmann May 30 '15 at 15:17

1 Answers1

2

You need to take a different approach. You can make an ajax call to a php script to do this for you. But the initiator will be javascript from the client side. Using jQuery(let me know if you can't), you can do

$.ajax({url: "insert_game_id.php", data: {gameId :b.gameId} });

and your php script

<?php
        $gameId = $_POST['gameId'];
        $insrt = "INSERT INTO game (gameId)
        VALUES ($gameId)";
        mysqli_query($dbc, $insrt);
?>

See jQuery Ajax POST example with PHP

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • And remember to extract `$gameId` out of the super global `$_POST` in your PHP script ... – Carsten Massmann May 30 '15 at 15:22
  • So if I wanted to make a generalized version of this code so that I could pass it other things like player names, could I pass the name of the variable in my database as well as the value of the variable through ajax? Something like this: data: {gameId :b.gameId, dbname:gameid} – ghadams May 30 '15 at 15:42
  • @ghadams, Im not sure if I understand your question. But yes, you can pass multiple variables from javascript to php. you can even pass arrays or obect structures. Let me know if I need to explain more or if I misunderstood your question – AmmarCSE May 30 '15 at 15:45
  • @ghadams, in this example, they pass multiple parameters http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php – AmmarCSE May 30 '15 at 15:49
  • @AmmarCSE ok thanks! Any idea why I am getting this error? ReferenceError: $ is not defined $.ajax({url: "insert_data.php", data: {gameId :b.gameId, dbname:gameId}}); – ghadams May 30 '15 at 15:59
  • @ghadams, you get that error if jquery itself is not loaded. Try and load it in your with – AmmarCSE May 30 '15 at 16:01
  • @AmmarCSE Ok I downloaded jQuery and put it in the folder with my other files and did and its all working now! Thanks a lot. – ghadams May 30 '15 at 16:10