Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Chris Gaona
Full Stack JavaScript Techdegree Graduate 31,350 PointsUsing $.ajax post to send data to node.js server
I'm trying to figure out how to use $.ajax post method to send data to a node.js server. I have an html form on my webpage and when I click submit I want the form contents to add another object to my JSON file. I've been looking all over the internet for some help, but haven't found anything that useful. The problem is I don't really know where to start (know of any good material to read or look at?). I know how to do an $.ajax get request from a server to populate an html page, but I can't figure out how to send something back to the server.
This is my client side code:
function postItem() {
$.ajax({
type: "POST",
url: "/static/json/garbage.json",
timeout: 2000,
data: { image: "/static/images/apples.jpeg", text: "apples" },
success: function(data) {
//show content
alert('Success!')
},
error: function(jqXHR, textStatus, err) {
//show error message
alert('text status '+textStatus+', err '+err)
}
});
}//postItem()
$('#new-item').on('click', function() {
postItem();
});
I'm trying to just get test data to send to the server and add to the end of a JSON file.
This is my server side code:
router.post('/static/json/garbage.json', function(req, res) {
console.log(req);
console.log('req received');
res.redirect('/');
});
This is my JSON file where I want to place the data once I've clicked the submit button:
{
"garbageItems" : [
{
"image" : "/static/images/empty-chip-bag.jpg",
"text" : "Chip Bags"
},
{
"image" : "/static/images/bubble-wrap.jpeg",
"text" : "Bubble Wrap"
},
{
"image" : "/static/images/porcelain.jpeg",
"text" : "Porcelain"
}
]
}
Any help would be much appreciated! Here is the code I've been working with below. Thank you!
1 Answer

Donald Brunais
8,895 PointsYour URL in your post request is incomplete. You have given it the path but it doesn't know where to post it too. So if you have your server set up locally you need to put http://localhost:3000/static/json/garbage.json or what ever port you have it listening on. Good place to start is the ajax docs. http://api.jquery.com/jQuery.ajax/ Or the express docs for routing. http://expressjs.com/guide/routing.html