2

Firstly I would like to describe what's wrong.

This is my Jquery code and it's good.

 $.ajax({ url: 'ajaxHandler.php',
     data: {'list' : 'list'},
     type: 'post',
     dataType:'json',
     success: function(output) {
                  alert(output);
              },
      error: function(request, status, error){
        alert("Error: Could not delete");
      }
  });

But problem is it i have just wanted to create the same in vanilla js.

var request = new XMLHttpRequest();
    request.open("POST", url, true);
    //Send the proper header information along with the request
    request.setRequestHeader("Content-type", 'application/json; charset=UTF-8');
    request.onreadystatechange = function() {

      if (request.readyState == 4 && request.status == 200) {
          alert(request.responseText);
      };
    }
    var dataParam = {
        'list': 'list'
    };

    var $json = JSON.stringify(dataParam);
    request.send($json);

Is Anybody who could tell me where is my mistake.

    <?php
    require_once 'tasksController.php';
    $dataFunction =  (string)($_POST['list']);
    echo $dataFunction;

    ?>

This is my alert : Notice: Undefined index: list in C:\xampp..........\ajaxHandler.php on line 3

Maciej.O
  • 63
  • 1
  • 7
  • What is the output of `JSON.stringify(dataParam)`? Try `console.log()`'ing it. – Daniel Jun 22 '17 at 02:12
  • 4
    Possible duplicate of [Send POST data using XMLHttpRequest](https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest) – Roamer-1888 Jun 22 '17 at 02:14
  • If you don't need IE11, there's always fetch. http://caniuse.com/#search=fetch and there are polyfills for ie11. – mkaatman Jun 22 '17 at 02:15

1 Answers1

3

The problem is that jQuery isn't sending JSON, it's sending the object as www-urlencoded data, and expecting to get JSON back.

var request = new XMLHttpRequest();
var data    = new FormData();

data.append('list','list');

request.onreadystatechange = function() {
  if (request.readyState === 4 && request.status === 200) {
    var result = JSON.parse(request.responseText);
    console.log(result);
  }
}

request.open("POST", 'ajaxHandler.php', true);
request.send(data);
adeneo
  • 293,187
  • 26
  • 361
  • 361