How to send arbitrary JSON to node.js without reloading the page?

My ultimate goal is to send arbitrary JSON to node.js when a button is clicked. I currently know how to submit input from a form. Here is the code I compiled to submit the 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 HTML looks like:

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

And the corresponding express / node.js code looks like this:

 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 do not know how to adapt this example to the use of data that is not related to the input form. To give context, I am creating a user web survey and I want to send various information collected about the user to node.js. I tried options for what worked to submit the form, but none of my attempts were successful. My impression was that I could just swap $(this).serialize() for any other data that the client could access, but I could not get this line of thought to work. I also tried to modify some of the many .ajax() examples, but they always redirected an unwanted page, since my research would lose user state information if the page refreshes.

I made a decent amount of client and server programs, but I don’t know how ajax works, which is quite problematic to solve this! And also pretty stupid, because, often times, that something that sticks the two together :)

+7
source share
1 answer

Since you are using jQuery, sending data is simple - call $.post(url, data) using the click button:

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

The browser will POST indicate the URL-encoded serialization of the data argument.

 POST /send HTTP/1.1 Content-Type: application/x-www-form-urlencoded ... key=value&... 

bodyParser Express' bodyParser no problems. Alternatively, you can tell jQuery to pass serialization of JSON data:

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

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

+6
source

All Articles