简体   繁体   中英

POST data using Ajax, jquery, Node.js and Express

I need some help. I'm trying to get this done following different things I've found over the internet but I can't understand the process. I have a carousel where my users is redirect to right after the signup. I'm tying to get informations about their profile by asking simple questions as inputs. This is the Pug code

body
div(class='container fill')
  div(id='myCarousel', class='carousel slide', data-ride='carousel', data-interval="false", data-wrap="false")
    div(class='carousel-inner')
      div(class='item active')
        div(class='carousel-caption')
          div(class='form-group', method='post')
            h1(id='welcome') WELCOME 
            h1
            | Tell us more about yourself
          h2
            | Pick any interest you like
          label(for='shopping', class="radio-inline")
            | Shopping
          input(type='checkbox', id='round', name='interest_filter', value='2', checked=interest=='shopping')

          div
          label(for='travelling', class="radio-inline")
            | Travelling
          input(type='checkbox', id='round', name='interest_filter', value='3', checked=interest=='travelling')

          div
          label(for='musique', class="radio-inline")
            | Musique
          input(type='checkbox', id='round', name='interest_filter', value='4', checked=interest=='musique')

          div
          label(for='cooking', class="radio-inline")
            | Cooking
          input(type='checkbox', id='round', name='interest_filter', value='5', checked=interest=='cooking')

          div
          label(for='nature', class="radio-inline")
            | Nature
          input(type='checkbox', id='round', name='interest_filter', value='6', checked=interest=='nature')

          div
          label(for='arts', class="radio-inline")
            | Arts
          input(type='checkbox', id='round', name='interest_filter', value='7', checked=interest=='arts')

And this is where I have no idea how to give the data

$('#matchme').click(function(){
var data = {};

$.ajax({
       url: '/carousel',
       type: 'POST',
       cache: false,
       data: JSON.stringify(data),
       success: function(data){
          alert('post success')
          console.log(JSON.stringify(data));
        }
      });
 });

This is in my app.js (I will use a waterfall to get thought the data and store it in my db)

app.post('/carousel', function (req, res) {
var data = {
interests: req.body.interest_filter,
orientation: req.body.orientation_filter,
age: req.body.age
 },
});

I'm using inputs because you can't put a form in a carousel. So far I understand the concept, but I've been using Javascript for a month now and I'm stuck, any help please ? Thanks in advance !

First you have to collect all the informations from user and pass that object in Ajax call. And I don't see any data you are passing during request except blank object. After that on server side you can get all the informations in req.body as you have already written..

     $('#matchme').click(function(){
         var data = {name:'hola', info: 'info'};

      $.ajax({
        url: '/carousel',
        type: 'POST',
        cache: false,
       data: JSON.stringify(data),
        success: function(data){
           alert('post success')
           console.log(JSON.stringify(data));
        }
       });
   });

First of all, I would recommend using the class attribute instead of id to apply the style of "round" to each of the elements, if im understanding the question correctly.

If you change that, you are able to use the vanilla JavaScript: document.getElementById('someId').value syntax to extract the different values?

If you are using JQuery library, it is even easier: $( "#someId" ).val(); http://api.jquery.com/val/

Thanks you for your help I get the concept now. It as been working so far with this :

$(document).ready(function() {
console.log("document is ready");
$("#matchme").click(function(){
event.preventDefault();
var data = {};
data.sex = $('[name=sex]:checked').val();
data.orientation_filter = $('[name=orientation_filter]:checked').val();
data.age = $('[name=age]:checked').val();

console.log(data.sex);
console.log(data.orientation);
console.log(data.age);
$.ajax({
         url: '/carousel',
         type: 'POST',
         cache: false,
         data: JSON.stringify(data),
         success: function(data){
            alert("post success")
            console.log(JSON.stringify(data));
          }
        });
   });

});

So I can get the value of data.sex when I log it but the two others data.orientation and data.age are still undefined.

Here is my app.js file for this post :

app.post('/carousel', function (req, res) {
username = session.uniqueID;
var data = {
sex: req.body.sex,
orientation: req.body.orientation_filter,
age: req.body.age
};
console.log(data.sex);
console.log(data.age);
function UserStart(data, callback) {
async.waterfall([
  function(cb) {
    pool.getConnection(function (err, connection) {
      if (err) {
        console.log(err);
      }
      connection.query('INSERT INTO usersinfo SET ?', data , function (err, rows, fields) {
        if (err) {
          console.log(err, "error")
        } else {
          callback(null, "all good")
        }
      });
    });
  }
],
function (err, data) {
  if (err) {
    callback(err);
  } else {
    callback(null, data);
  }
})
}
UserStart(data, function (err, callback) {
 if (err) {
   res.redirect('/login');
   console.log("login again");
 } else {
   res.redirect('/home');
   console.log("user is now activated, ready !");
 }
})
});

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