简体   繁体   中英

How to get value from Javascript to PHP on same page?

This is the current code to get data from JS to PHP:

JavaScript:

window.location.href="samepage.php?points=" + data[picked].question;

PHP GET:

<?php
    if (isset($_GET["points"])){
        //do stuff to store the points into MySQL table
        
        $value = $_GET['points'];
        echo $value;
    }
?>

The problem is that the user can now edit the url to get more points. How can I do this without using GET so the user can't manipulate the value? I have tried AJAX, but I can't get it to work.

JavaScript with AJAX:

$(document).ready(function(){
                        var url = window.location.href;
                        var params = url.split('?points=');
                        var id = data[picked].question;
                        $("#submit").click(function(){ $.ajax({
                            type:"POST",
                            url:"samepage.php",
                            data:{id:id},
                            success:function(result){
                                $("#content").html(result);
                                $("#submit").hide();
                            }
                        });
                        });
                    });

PHP POST:

if( isset($_POST["points"]) )
    {
        $random = $_POST["points"];
        echo $random;
    }

What am I doing wrong, and how can I solve this?

How can I do this without using GET so the user can't manipulate the value?

If the value is sent from the client, you can't stop the user from manipulating it.

It's not entirely clear what the end goal is, but it looks like you need to something very roughly along these lines:

  1. Generate an identifier to represent a user (eg a session)
  2. Send the choices the user makes to the server instead of the points those choices are worth
  3. Calculate the value of those choices server-side
  4. Store the result in the session

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