Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send arbitrary JSON to node.js without a page reload?

My ultimate goal is to send an arbitrary JSON to node.js when a button is clicked. I currently only know how to send input from a form. Here's some code I put together to send form information:

function postForm() {
  $('form').submit(function(e) {
    e.preventDefault(); // no page reload
    $.post(
      $(this).attr('action'),
      $(this).serialize(),
      function(data) { console.log('Code for handling response here.') },
     'json'
    );
  });
}

Where the HTML looks like:

<form action='/send' method='post'>
  <input name= "foo" type="radio" value=1>
  <input type="submit" value="Submit">
</form>

And the relevant express/node.js code looks like:

app.post('/send', function(request, response) {
  fs.appendFile('test.txt', JSON.stringify(request.body) + '\n', function(e) {
    if(e) throw e;
    console.log(request.body);
  });
});

However, I don't know how to adapt this example to use data that is not from form input. To give context, I'm building a web-based user study, and I want to send various information collected about the user to node.js. I've tried variants of what was working for the form submission, but none of my attempts have been successful. My impression was that I could just swap out $(this).serialize() to any other data that the client can access, but I couldn't get this line of thought to work. I also tried altering some of the many .ajax() examples, but those always redirected the page which is undesirable, since my study will lose user-state information if the page refreshes.

I've done decent amount of client and server side programming, but I have next to no knowledge about how ajax works, which is proving rather problematic for solving this! And also rather silly since, often times, that's what glues the two together :)

like image 636
Connor Gramazio Avatar asked Dec 04 '12 20:12

Connor Gramazio


1 Answers

Since you're using jQuery, sending data is simple – call $.post(url, data) from the button's click handler:

$('#somebutton').click(function() {
    var data = { key: 'value', ... };
    $.post('/send', data, function(res) {
        // success callback
    });
});

The browser will POST to url with a URL-encoded serialization of the data argument.

POST /send HTTP/1.1
Content-Type: application/x-www-form-urlencoded
...

key=value&...

Which Express' bodyParser will have no trouble with. Alternatively, you can tell jQuery to send a JSON serialization of data:

$.post('/send', data, function(res) {}, 'json');

In your case, it really doesn't matter how jQuery transmits the data (URL encoded or JSON), since bodyParser automatically deserializes both formats.

like image 189
josh3736 Avatar answered Oct 13 '22 10:10

josh3736