简体   繁体   中英

AJAX POST request with response

As the title states, I'm looking to make a POST request using JavaScript and also get a response. Here's my current code:

var request = new XMLHttpRequest();
request.open('POST', 'test.php', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success
    console.log(request.responseText)
  } else {
    // Server-side Error
    console.log("Server-side Error")
  }
};

request.onerror = function() {
    // Connection Error
    console.log("Connection Error")
};

request.send({
    'color':'red', 
    'food': 'carrot',
    'animal': 'crow'
});

With test.php being:

<?php 
    echo $_POST['color'];
?>

This should return 'red' but instead returns nothing.

This seems like a simple problem but I could only find solutions for people using jQuery. I'd like a solution that does not rely on and libraries.

The send method takes a string rather than an object, perhaps more like:

var request = new XMLHttpRequest();
request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    console.log(request.response)
  } else {
    console.log("Server-side Error")
  }
};

request.onerror = function() {
    console.log("Connection Error")
};

request.open('POST', 'test.php', true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.send('color=red&food=carrot&animal=crow');

The JavaScript problem

You are trying to send a generic Object, so it gets converted to a String ( "[Object object]" ), and the data is lost.

Convert the data to a FormData object instead.

var data = {
    'color':'red', 
    'food': 'carrot',
    'animal': 'crow'
};

var formData = new FormData();

Object.keys(data).forEach(function (key) { 
  formData.append(key, data[key]);
})

request.send(formData);

The PHP problem

All of the current solutions simply log the source code of "test.php" to the console as opposed to logging 'red' to the console

This is an issue unrelated to your code. It is also a FAQ. See: PHP code is not being executed, instead code shows on the page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM