Test
Test

Reputation: 3

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?

Upvotes: 0

Views: 62

Answers (1)

Quentin
Quentin

Reputation: 944559

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 (e.g. 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

Upvotes: 2

Related Questions