-1

My issue that I encountered here is when I send a request with parameters to my PHP back-end it would act as a form was submitted and would send a false submission. I use AJAX to communicate with the front and back-end and the code I use is:

$(document).ready(function () {
    $("#submitmsg").click(function () {
        var usrmsg = $("#Text").val();
        var username = localStorage.getItem("user")
        $.post("send.php", { text: usrmsg,user: username,},
            function(result){ });
        $("#Text").val("");
        return false;
   });
});

in my backend where it gets the request is

$username = $_POST['user']; 
$text = $_POST['text'];
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149

1 Answers1

0

This will prevent Cross-Site Scripting

When your page loads, save a token in a session / cookie / database.

$_SESSION['token'] = md5(uniqid(mt_rand(), true));

In your AJAX call pass that same token to send.php:

{ text: usrmsg,user: username, token: token_generated }

In send.php just check the tokens match

if ($_POST['token'] != $_SESSION['token']) exit();

Or if your only concert are fake submits try a captcha.

Also you can validate the fields using Javascript BEFORE they're send via AJAX.

kissumisha
  • 484
  • 4
  • 12