简体   繁体   中英

How can i use an JavaScript(AJAX) variable in PHP

I want to use my var 'resp' in php, so i can add the JSON request info in my database. this is the code i ame using now:

 $.ajax({ 
            url: 'https://prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=' <?php echo rawurlencode($key); ?>,
            type: 'GET',
            dataType: 'JSON',
            async: false,
            error: function(){},
            success: function(resp){
            <?php
                mysql_query("INSERT INTO Game VALUES('', '1', 'Blue', '1', 'WIN')");
                mysql_query("INSERT INTO Game VALUES('1', '2', 'Red', '1', 'Lose')");
                mysql_query("INSERT INTO Game VALUES('1', '3', 'Green', '1', 'Draw')");
            ?>
            }
        });

so instead of:

mysql_query("INSERT INTO Game VALUES('1', '2', 'Red', '1', 'Lose')");

i want this:

mysql_query("INSERT INTO Game VALUES(resp.id, resp.value, resp.team, resp.unit, resp.status)");

i know that doesnt work, and i tried searching online for answer but couldnt find anything. TY in advance

Essentially what you'll have to do is, on success, make another AJAX call to a PHP script that just runs the mysql_query's. And you could really just use something like $.get() to do that instead of the full $.ajax method. Or maybe have a PHP script do the whole thing… grabbing that URL of JSON content etc.

You can't directly do that, since JavaScript runs on the client-side and PHP gets executed on the server-side.

You would need to execute the JavaScript first and then send the result to the server via a FORM or AJAX call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM