0

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}');
Dave Newton
  • 152,765
  • 23
  • 240
  • 286
8this
  • 295
  • 1
  • 2
  • 8
  • 1
    [This question should help you a bit](http://stackoverflow.com/questions/9713058/sending-post-data-with-a-xmlhttprequest). You need to send the data in the format expected by the POST request. So you could create a variable called `data`, and set it to something like this. `var data = "name=" + encodeURIComponent(name)` – Brandon Anzaldi Nov 04 '15 at 21:09
  • *"Doing the following doesn't work though:"* How are you testing that? (other than the fact that `{"Tom"}` is invalid json) – Kevin B Nov 04 '15 at 21:12
  • How is this related to jQuery? – Dave Newton Nov 04 '15 at 21:15
  • 2
    You're also sending the request then *immediately* parsing the response, which won't work: it's *async*. I think you might want to take a step back, and possibly consider using jQuery until you understand the basics. – Dave Newton Nov 04 '15 at 21:18

1 Answers1

2

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" />