0

I want to Update my database with a variable from javascript.

This is my javascript code i want the testusersGeld variable to transfare over to php.

var testusersGeld = 111;

var sendUsersGeld = new XMLHttpRequest();

sendUsersGeld.open("POST", "usersGeldSenden.inc.php");
sendUsersGeld.setRequestHeader("Content-Type", "application/json");
sendUsersGeld.send(testusersGeld);

and this is my php code:

<?php

session_start();

$requestPayload = file_get_contents("php://input");

$object = json_decode($requestPayload);

var_dump($object);

if(isset($_POST['update']))
{

    require_once 'includes\dbh.inc.php';

    $query = "UPDATE users SET usersGeld='".$object."' WHERE usersName LIKE '{$_SESSION["usersName"]}'";
    
    $result = mysqli_query($conn, $query );

    if($result)
    {   
        echo 'Data Updated';
    }else{
        echo 'Data Not Updated';
    }
    mysqli_close($conn);
}

When i var_dump than i can see the 111 but when i try to echo it out it wont work. The part of Update works when i use another variable.

TheJoniii
  • 21
  • 2
  • Why is `$requestPayload` coming from a file? Surely it should come from the POST body? Maybe I'm just misunderstanding – evolutionxbox Jan 07 '22 at 13:55
  • $requestPayload shoud contain the testusersGeld variable witch is in the javascript file. Is that wrong? I am a beginner. – TheJoniii Jan 07 '22 at 14:38
  • Does this answer your question? [How do I pass JavaScript variables to PHP?](https://stackoverflow.com/questions/1917576/how-do-i-pass-javascript-variables-to-php) – evolutionxbox Jan 07 '22 at 14:47
  • no i dont want to pass an inpud field – TheJoniii Jan 07 '22 at 15:40
  • that's just a small detail. the rest of the answer is relevant to your issue – evolutionxbox Jan 07 '22 at 15:46
  • When you call `sendUsersGeld.send(testusersGeld)`, you are just passing `111` into there, there's no JSON. The fact that you previously set a JSON header doesn't cause anything special to happen. On the server side `$requestPayload` should hold `111` as a string, calling `json_decode` on it is unnecessary. Make sure that [MySQL](https://stackoverflow.com/a/22662582/231316) and [PHP](https://stackoverflow.com/a/21429652/231316) error reporting are both turned on. Run `var_dump($query)` to see the literal query generated, and try running it through a SQL tool to make sure it does what you want. – Chris Haas Jan 07 '22 at 17:48
  • @ChrisHaas `111` is valid JSON, so `json_decode` likely makes sense. What doesn't is why the OP is loading a file and not using POST data. – evolutionxbox Jan 07 '22 at 19:38

0 Answers0