1

I am using Ajax call to post data from client side to node server and trying to receive data at server end, manipulate it(do some db query) and then return the response.

client side code :

$.ajax({
    type: "post",
    url: "http://localhost:8888/ajaxRequest", 
    dataType: "json",
    data:  {name: "Manish", address: {city: "BBSR", country: "IN"}}
}).done(function ( data ) {
    console.log("ajax callback response:" + data);
});

server side :

var port = 8888;
var server = http.createServer();
server.on('request', request);
server.listen(port);

function request(request, response) {
    var store = '';
    response.writeHead(200, {"Content-Type": "text/json"});
    request.on('data', function(data) {
        store += data;
    });
    request.on('end', function() {
        console.log(store);
        response.end(store);
    });
}

Problem : when I am consoling "store" variable in request end function I am getting something like this:

name=Manish&address%5Bcity%5D=BBSR&address%5Bcountry%5D=IN

I just want the same data at the server side what I sent in the Ajax 'data' parameter. I also tried, queryString.parse, JSON.parse() but no help. I just want my output as :

{name: "Manish", address: {city: "BBSR", country: "IN"}}

2 Answers 2

2

You need to tell jQuery that this is an JSON request:

$.ajax({
    type: "post",
    url: "http://localhost:8888/ajaxRequest", 
    dataType: "json",
    contentType: "application/json; charset=UTF-8",
    data:  JSON.stringify({name: "Manish", address: {city: "BBSR", country: "IN"}})
}).done(function ( data ) {
    console.log("ajax callback response:" + data);
});

This way, your request body will reach the server with the stringified JSON, so you'll be able to do the following:

request.on('end', function() {
    store = JSON.parse(store);
    console.log(store); // ta-daaa, Object!
    response.end(store);
});
Sign up to request clarification or add additional context in comments.

2 Comments

just gave it a try, not working, still getting the url same string int he request.on('end', function).... (name=Manish&address%5Bcity%5D=BBSR&address%5Bcountry%5D=IN])
see updated answer, just added JSON.stringify() around data. This haves to work, it's how backbone does...
1

Have you tried something like:

...
response.end(JSON.stringify(store));

1 Comment

nothing happens, just returns the same string ("name=Manish&address%5Bcity%5D=BBSR&address%5Bcountry%5D=IN") with quotes around it. Anyways I do not need the resulting object at client side, I just want to manipulate the string at server side.

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.