3

My problem: once I submit a JSON object with JQuery to my express app which uses JSON parser(belongs to the module body-parser) and try to respond back to it, be it res.send or res.render, it does nothing. I try to output html directly back to the client as an html response. On the other hand, on the same page of my website, I tried the regular body parser and the response works fine. Here is my JSON listener:

controller.js:

var express = require('express');
var app = express();

var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended:
false }); 

app.post('/video', jsonParser, function(req, res) {
res.send("hi"); //nothing happens

console.log(req.body.time); //works, i get the data
console.log(req.body.src); //works, i get the data
});

the form that submits to it:

index.html

...mywebsite code, uses jquery
fu();

function fu(){
    var vid = document.getElementById("vid");
    var time = vid.currentTime;
    var src = vid.currentSrc;
    $.ajax({
        type: "POST",
        url: "/video",
        data: JSON.stringify({time: time, src: src  }), //the data is parsed fine
        dataType: 'json',
        contentType: 'application/json'
    });

    //alert("current time: " + time);
};

Now, I have tried a simple form with a body parser and it works fine, on the exact same website(I put it there just to see if it will work):

controller.js

 var express = require('express');
var app = express();

var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended:
false }); 

app.post('/person', urlencodedParser, function(req, res){
    res.send('Thanks!');
    console.log(req.body.firstname);
    console.log(req.body.lastname);    
});

the person form:

      <form method="POST" action="/person">
        Firstname: <input type ="text" id="firstname"
        name="firstname"><br>
        Lastname: <input type ="text" id="lastname"
        name="lastname">
        <input type="submit" value="sumbit">
    </form>     
6
  • 3
    You don't have to stringify data you send to server. Try: data: {time: time, src: src } instead. Commented Mar 9, 2016 at 19:46
  • it doesn't work without stringify, I just tried... Commented Mar 9, 2016 at 20:48
  • I does work perfectly. At least if you arrange your server as me: gist.github.com/Nonemoticoner/366c02f7db613566d3cf Commented Mar 9, 2016 at 21:26
  • You wrote dataType: 'json' but you send plain text in response. Also, catching the response to any variable would be useful I believe. Currently your AJAX request does nothing with it. Commented Mar 9, 2016 at 21:32
  • ok, I tried your example without the stringify, it works. i can see the data on the console. though, there is still no response. the "hi" won't show up. Commented Mar 9, 2016 at 21:57

3 Answers 3

1

You need to handle the response in the client after $.ajax request. Set done function to handle success callback:

$.ajax({
        type: "POST",
        url: "/video",
        data: {time: time, src: src  },
        dataType: 'json',
        contentType: 'application/json'
    })
    .done(function( data, status, xhttp) {
         // put the data in the DOM 
         document.getElementById("hi").text(data);
    });
Sign up to request clarification or add additional context in comments.

4 Comments

so that's how ajax works, ok. is there any other way that it won't go directly into success? just for common knowledge.
sure, you can handle others options such as: error, complete. Take a look to this: api.jquery.com/jquery.ajax
no, i mean - just render the entire page that you want to send back and send it as a whole as the response, don't send it all as a string into that function that belongs to ajax and then decide what to do with it
Well AJAX is mean to do exactly that, send something without the need to render the entire page. If you want to render the entire page, just make an HTTP request to the server and respond with a view back.
0

Hm, looks pretty easy - you are not using jsonParser in the second snippet - just urlencodedParser, which is not correct here. So it should looks like here:

var express = require('express');
var app = express();

var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false }); 

app.post('/person', jsonParser, function(req, res){
    res.send('Thanks!');
    console.log(req.body.firstname);
    console.log(req.body.lastname);    
});

3 Comments

No, my problem is with the 1st example. everything after "Now, I have tried a simple form with a body..." is my 2nd example. and btw the 2nd example works fine as it is, no need to use the json parser.
Ok, so I don't understand what do you mean by that send method does nothing, did you mean a no response is given or nothing happens in browser? Because you don't have any handler code (done method in jQuery) at browser's side.
the browser doesn't display the "hi" message sent by res.send. now, in my 2nd example it does display it, my entire website html is "removed" and i see "Thanks!"
0

You may try polyfill "fetch" instead jQuery:

function getResponse (url) {
  return fetch(url, {
      method: 'post',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ time, src })
      })
      .then(response => response.json())
      .then(data => {
        console.log('request succeeded with JSON response', data)
      })
      .catch(error => {
        console.log('request failed', error)
      })
}

I think it will look much better. And it can be used on server side. Docs: https://github.com/github/fetch

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.