0

I decided to stop using jQuery so I'm converting everything to pure JavaScript.

I have this ajax call and I want to send the last part of the url to the php server, but JSON.stringify() sends anempty object in the server.

Why is this happening?

AJAX call:

var ajax = new XMLHttpRequest();

ajax.open('get', 'ajax/autocomplete.php');
ajax.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
ajax.send(JSON.stringify({q: document.location.href.split('/').slice(-1)[0]}));

PHP:

<?php
    require_once '../../private/core/init.php';
    header('Content-Type: application/json');

    print_r($_GET);//empty

    $data = new AUTOCOMPLETE($_GET['q']);
    echo json_encode($data->data());
?>

and I get this error: Undefined index: q

10
  • 3
    I don't think you should send a request entity with a GET request. Do a POST or use a query parameter (?q=......). Commented Feb 12, 2016 at 2:19
  • But I will get data. not write or update. @Thilo Commented Feb 12, 2016 at 2:20
  • 1
    The parameter data can only be sent with POST requests. data will not be placed inside the request body if any other request method is used. documentation Commented Feb 12, 2016 at 2:20
  • Thanks it works @Thilo Commented Feb 12, 2016 at 2:24
  • 1
    Why on earth would you stop using jQuery? Commented Feb 12, 2016 at 2:28

1 Answer 1

1

You might want to suppress PHP errors with error_reporting(0); or validate the input data first with isset/empty or some other function that will suppress the PHP warnings. The warning output will make your JSON response data invalid to your javascript (jQuery or pure javascript).

<?php
error_reporting(0);
require_once '../../private/core/init.php';
header('Content-Type: application/json');

if (isset($_GET['q'])) {
    $data = new AUTOCOMPLETE($_GET['q']);
    echo json_encode($data->data());
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

yeah but the same problems occurs even when I do POST request. whats the problem? I still get an empty object even with POST

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.