0

I have an XMLHttpRequest sending data to a PHP backend.

var req = new XMLHttpRequest();
req.open('GET', url);

req.onload = function() {
  // This is called even on 404 etc
  // so check the status
  if (req.status == 200) {
    // Resolve the promise with the response text
    resolve(req.response);
  }
  else {
    // Otherwise reject with the status text
    // which will hopefully be a meaningful error
    reject(Error(req.statusText));
  }
};

// Handle network errors
req.onerror = function() {
  reject(Error("Network Error"));
};

// Make the request
req.send('query=messages'); // <-- i want to access this in php

i tried print_r($_GET) and print_r($_REQUEST) but neither works.

anyone knows how to access this data?

4
  • Have you watched the request / response in the browser's console? Commented Jan 15, 2016 at 13:44
  • yes @JayBlanchard it doesn't seem to deliver query=message at all: GET /rest/api.php HTTP/1.1 Host: localhost Connection: keep-alive Origin: localhost:8000 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36 Accept: / Referer: localhost:8000/index.html Accept-Encoding: gzip, deflate, sdch Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 Commented Jan 15, 2016 at 13:58
  • See my answer below why that is... Commented Jan 15, 2016 at 13:59
  • @MagnusEriksson Yes thanks a lot! i answered the comment before i read your answer Commented Jan 15, 2016 at 14:04

1 Answer 1

2

You can only send data through the XMLHttpRequest.send()-method for POST-requests, not GET.

For GET-requests, you need to append the data to the url as query string.

url += "?query=message";

Then you can retrieve the data with PHP using:

$message = $_GET['query'];

More info: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

Sign up to request clarification or add additional context in comments.

2 Comments

aaah okay, i didn't know. using XMLHttpRequest to call a PHP REST API seems a bit unconvenient then since i have to use URL for GET and send() for POST. is there a better aproach to this in vanilla js?
Not really. I would make a small wrapper for it and use it like: ajax.get(url, data, callback); and ajax.post(url, data, callback) and handle the request in those methods.

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.