8this
8this

Reputation: 495

sending variables via AJAX POST

I am trying to send a variable that contains a name to a server using the POST method. This is suppose to be Asynchronous. I have the following code written but I am getting an error, SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data and honestly it isn't too helpful.

I downloaded firebug and firebug gets me a little closer as it says the error is on line 84 column 17 (I wasn't sure what to make of column so I counted 17 characters in). If this is the case, then it says my problem is starting with the word parse.

I am new to AJAX so I am not sure what you guys do and don't need to see, but I will start by showing this bit of code where I think the problem resides.

        function sendByPost()
        {
            var name = getName();
            var req = new XMLHttpRequest();
            req.open("POST", "http://httpbin.org/post", true);
            req.setRequestHeader('Content-Type', 'application/json');
            req.send('{"Tom"}');
            console.log(JSON.parse(req.responseText));
        }
        function getName()
        {
            return document.getElementById("myName").value;
        }

I also do not want it to say Tom on the 7th line down and my intention is for it to say whatever the user types in. So I setup a name variable that would get the value inside the text box.

Doing the following doesn't work though:

            req.send('{name}');

Upvotes: 0

Views: 62

Answers (1)

Basically, you need to send an object in the request.

enter image description here

I've made a simple demo:

function sendByPost() {
  var name = getName(); // Get the value from the input field.
  var req = new XMLHttpRequest();

  var data = {}; // Declare an object.
  data.name = name; // The data object has the name attribute with the value.

  req.open("POST", "http://httpbin.org/post", true);
  req.setRequestHeader('Content-Type', 'application/json');
  req.send(JSON.stringify(data)); // Send the data object as json string.
  req.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) { // Check for the status of the response
      console.log(JSON.parse(req.responseText)); // Prints the results.
    }
  };
}

function getName() {
  return document.getElementById("name").value;
}
sendByPost();
<input type="text" id="name" value="Test" />

Upvotes: 2

Related Questions