0

I tried everything but it still don't work. Without $_POST value it is working, without JSON it's working, with both it's not. Function shows this error:

<b>Notice</b>:  Undefined index: someVar1 in <b>C:\xampp\htdocs\ajax3\test.php</b> on line <b>2</b><br />
Array()
{"jeden":"Po obr\u00f3bce  123  123 ","dwa":null}"

script.js

$(document).ready(function(){
    var data = {
        someVar1: '123'
    };
    data = JSON.stringify(data);
    $.ajax({
        method: "POST",
        url: "test.php",
        dataType : 'json',
        contentType: "application/json; charset=utf-8",
        data: data,
        success: function(json) {
            $.each(json, function(i, ob) {
                console.log(i, ob);
            });
        },
        error: function(error) {
            console.log(error);
        }
    });
});

and test.php

<?php
    $someVar1 = $_POST['someVar1'];

    $a = " 123 ";

    $result = array();
    $result['jeden'] = 'Po obróbce ' . $a . $a;
    $result['dwa'] = $someVar1;

    echo json_encode($result);
?>
Laba
  • 1
  • `$_POST['someVar1']` you referenced an array element that does not exist. PHP isnt cool with this. – castis Jun 26 '17 at 15:51
  • 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) – castis Jun 26 '17 at 15:52
  • I would suggest you var_dump($_POST) to see exactly what the php code is seeing in the _POST var – Stephen Adkins Jun 26 '17 at 15:53
  • if (isset($_POST["someVar1"]) && !empty($_POST["someVar1"])) { Your Code } – Murad Sofiyev Jun 26 '17 at 15:54
  • var_dump and print_r shows nothing – Laba Jun 26 '17 at 15:58

1 Answers1

0

It because you send data in JSON format. $_POST will be empty always In this case you need to use I/O stream

Try this

$postData = json_decode(file_get_content('php://input'));

look more http://php.net/manual/en/wrappers.php.php

buildok
  • 785
  • 6
  • 7