0

I am trying to update a mysql database using an Ajax POST request to a php file, but I receive the following error:

Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2

Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2
{"d":true}{"d":true}

Here is my Ajax code:

$('#addbut').click(function()
    {
        console.log($("#firstteam").val());
        console.log($("#score1").val());
        console.log($("#score2").val());
        console.log($("#secondteam").val());

        var data = {
        firstteam:$("#firstteam").val(),
        secondteam:$("#secondteam").val(),
        score1:$("#score1").val(),
        score2:$("#score2").val()}

        $("#firstteam").val('');
        $("#secondteam").val('');
        $("#score1").val('');
        $("#score2").val('');

        $.ajax({
            type: "POST",
            url: "php/post.php",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType:'json',

            //if received a response from the server
            success: function(response) 
            {
                 var res = response.d;
                 if (res == true)
                 {
                     $("#error").html("<div><b>Success!</b></div>"+response);
                     updateTable();
                 }
                 //display error message
                 else {
                     $("#error").html("<div><b>Information is Invalid!</b></div>"+response);
                 }
            },

            //If there was no resonse from the server
            error: function(jqXHR, textStatus, errorThrown)
            {
                 console.log("Something really bad happened " + textStatus);
                 $("#error").html(jqXHR.responseText);
            }
        });  

    });

Here us my PHP code:

<?php
    $data = $_POST['data'] or $_REQUEST['data'];
    $js = json_decode($data,true);
    $t1 = $js['firstteam'];
    $t2 = $js['secondteam'];
    $s1 = $js['score1'];
    $s2 = $js['score2'];

    updateFunction($t1,$s1,$s2);
    updateFunction($t2,$s2,$s1);



    function updateFunction($name, $s1, $s2) 
    {
        $conn = new mysqli("localhost:3306","root","","leagues"); 
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        if ($s1 > $s2)
            $sql = "UPDATE league SET playedgames=playedgames + 1,wongames = wongames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 3 WHERE teams='".$name."'";
        else
            if ($s1 == $s2)
                $sql = "UPDATE league SET playedgames=playedgames + 1,tiegames = tiegames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 1 WHERE teams='".$name."'";
            else
                if ($s1 < $s2)
                    $sql = "UPDATE league SET playedgames=playedgames + 1,lostgames = lostgames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."' WHERE teams='".$name."'";

        if ($conn->query($sql) === TRUE) 
        {
            $response = json_encode(array('d' => true)); 
            echo $response;
        }
        $conn->close();
    }
?>

I tried some suggestions, but I don't know why my PHP code doesn't parse the data correctly. The Console.log from my Ajax function prints exactly what I want.

Here is what my debugger shows: enter image description here

Artyomska
  • 1,309
  • 5
  • 26
  • 53
  • 1
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – aynber Jun 05 '17 at 16:20
  • `var_dump($_POST);` what do you have? – aynber Jun 05 '17 at 16:20
  • array(0) { } This is what I receive – Artyomska Jun 05 '17 at 16:22

1 Answers1

2

It doesn't work, because by putting

$.ajax({
    ...
    data: '{"key":"value"}',
    ...});

you just put that string ({"key":"value"}) in raw form into request body. Therefore there is no form parameter named data.

To retrieve this raw data from body use:

$data = file_get_contents('php://input');

OR

$data = stream_get_contents(STDIN);

instead of

$data = $_POST['data'] or $_REQUEST['data'];
Dominik Szymański
  • 763
  • 10
  • 22