How can I access data sent via AJAX on Node JS server? - ajax

I would like to make a simple contact form for my website. I know how to use ajax to send data, but I don't know how to access it on the Node JS server.
If I were to send my data using this code:
var request=new XMLHttpRequest();
request.open("POST","url");
request.send("{value:'10'}");
How can I access my value in the JSON object I pass to the server?

There are a lot of ways to do this.
For example you could create an endpoint on your server e.g. with express http://expressjs.com/. It might look like this
router.post('/your/url', function(req, res, data) {
var value = req.body.value;
// do cool things with value
res.send('cool');
});
You define a post endpoint which will handle your request. Using the request object you can access the JSON object from the request

I used request_.on("data", function(data_){}); to get my data.
If in my client JS I use request.send("my data");
I can access my data by adding a listener to the request_ object in my Node JS server function.
request_.on("data", function(data_){
console.log(data_);// my data
}
I can then slice up my data any way I want to and use it how I see fit. No need for Express.
Here's my client function that is called when the submit button on my contact form is pressed:
function clickSubmit(event_) {
var xmlhttprequest = new XMLHttpRequest();
xmlhttprequest.open("POST", "contact");
xmlhttprequest.send("email=" + html.email.value + "&name=" + html.name.value + "&message=" + html.message.value);
}
And here's my Node JS server function:
function handleRequest(request_, response_) {
switch(request_.url) {
case "/contact":
request_.on("data", function(data_) {
console.log("data: " + data_);// Outputs the string sent by AJAX.
});
break;
}
}

Related

How to add data to IndexedDb in service worker which are coming as http response from api

I have a application in codeigniter and angular framework. All its data are coming from api's that are we have created in codeigniter . Now i am trying make this application a pwa . so far,caching of static file and manifes.json are working ,but when it comes to storing those data in IndexedDb and retriving them i am confused how to that.Till now i have find only examples with static json being inserted into IndexedDb ,but i want to know how to store those http response in indexedDb, so that when it goes in offline mode it automatically provide data.Also in every page have more than one http response is coming so it should also provide right data to variables..
If you any part of question than just let me know ,I will try better to explain.
And thank you all in advance.
If the response from api is JSON or some similar sort of data file then you can store in indexDB as string or manipulate as you need.Here's an example of storing JSON as string.
//JSONfile is the response from your api.
var JSONstring = JSON.stringify(JSONfile)
// Storing JSON as string in indexDB
var dbPromise = idb.open('JSON-db', 1, function (upgradeDB) {
var keyValStore = upgradeDB.createObjectStore('JSONs')
keyValStore.put(JSONstring, 'samples')
})
//provide better key name so that you can retrieve it easily from indexDB
Other case if response is some sort of multimedia then you can convert it into blob and then store the blob in indexDB.
return fetch(new Request(prefetchThisUrl, { mode: 'no-cors' }))
.then((resp) => {
resp.blob()
.then((blob) => {
return db.set(prefetchThisUrl, blob);
});
});
You can then get the information from indexDB when required.For a good understanding of storing and retrieving blob from indexDB you can visit this site:https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/
And for providing right data on your page it's not an issue,you just need to make your logic to respond to request from indexDB.Here's how you can do it.
dbPromise.then(function (db) {
var tx = db.transaction('JSONs')
var keyValStore = tx.objectStore('JSONs')
return keyValStore.get('samples')
}).then(function (val) {
var JSONobject = JSON.parse(val)}

How to export/link user e-mails?

So we're using Parse.com's signup, and e-mails of user signups go into the User Class. We're also using MailChimp at the moment for our campaign software. How can we export or link the two so that any e-mails from signups go to our MailChimp lists?
I know that Parse has some Cloud Module integrations with Mandrill and SendGrid, but nothing with MailChimp directly.
Maybe these articles can help you:
https://www.parse.com/questions/mailchimp
Github project: Mailchimp API + Mandrill API optimized for Parse.com Cloud Code
https://github.com/icangowithout/parse-mailchimp/commit/0d75b8be9775347efd939c8715d5d2b13076353c
var api_key = "YOUR_MAILCHIMP_API_KEY";
// use https and last verison
var options = {secure: true, version: "1.3"};
// Set the path to the mailchimp module
// If you cloned the mailchimp lib somewhere else, it's time to set this
// value properly
var module_path = "cloud/libs/mailchimp/";
var MailChimpAPI = require(module_path+"MailChimpAPI.js");
var myChimp = new MailChimpAPI(api_key, options, module_path);
myChimp.ping({}, function(error, data){
// data is a string or JSON parsed object
if(error){
// Oops… there was a problem...
}else{
// Do something with the data
}
// Handle what to do with the ping
});
//or
// Parse callback style
myChimp.ping({}, {
success: function(data){
// data is a string or JSON parsed object
// Howdy! The ping worked!
},
error: function(error){
// Something went wrong...
}
});

Get Picture from Client - save on MongoDB, expressJS, nodeJS

I'm trying to Implement a simple Picture upload from the client to my mongoDB.
I've read many explanations but I can't find a way from start to finish.
My clientside -
function profilePic(input) {
if (input.files && input.files[0]) {
var file = input.files[0];
localStorage.setItem('picture', JSON.stringify(file));
}
}
Later on I take the this JSON from the LocalStorage and send it to my server side like this:
var request = false;
var result = null;
request = new XMLHttpRequest();
if (request) {
request.open("POST", "usersEditProf/");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
.....//More code to send to Server
request.setRequestHeader('content-type', 'application/json');
request.send(JSON.stringify(localStorage.getItem('picture)));
}
}
On my serverside:
app.post('/usersEditProf/',users.editProfile);
/** Edits the Profile - sends the new one **/
exports.editProfile = function(req, res) {
var toEdit = req.body;
var newPic = toEdit.picture;
And thats where I get lost. is newPic actually holding the picture? I doubt it...
Do I need to change the path? What is the new path I need to give the picture?
How do I put it in my DB? Do I need GridFS?
When trying to simply put that in my collection, it looks like this (example with a image called bar.jpg:
picture: "{\"webkitRelativePath\":\"\",\"lastModifiedDate\":\"2012-10-08T23:34:50.000Z\",\"name\":\"bar.jpg\",\"type\":\"image/jpeg\",\"size\":88929}",
If you want to upload a blob through XMLHTTPRequest(), you need to use an HTML 5 FormData object:
https://developer.mozilla.org/en-US/docs/Web/API/FormData
It alows you to specify a filename to push, then you handle the incoming file as you would with a mime form post. Note the limitations on browser support when you use the FormData object. Your alternative is a form POST to a hidden frame, which works OK but is not nearly as clean looking in code as FormData.

How to load image list from REST API using angularJS

I have searched in this forum for quiet a bit and here's my problem -
I have a ng-repeat in my html which takes in a list of messages(Json object).
Each message JSON has a sender email address - e.g. abc#gmail.com
Now, I have to get the email address from the message and form another REST API request to fetch their images for e.g. - http://<>:8080/getImage/abc#gmail.com (email address dynamic)
So in my code, I'll have a ng-repeat and a ng-src pointing to the image REST URL
If there's no image in server, it returns a 404 and displays a broken image on the UI. How do I handle it? On the other hand, if I make a http request to determine if there's a success message and on failure return a default image, then the whole thing goes through an endless loop. I'll try to create a fiddle and include it for better explanation.
Use the error block to handle such behavior:
function($http) {
var restUrl = 'getImage/abc';
return {
fetchImage: function(imageId) {
var self = this;
return $http.get(restUrl + '/' + imageId).
success(function(data) {
return self.imageUrl = data;
}).
error(function(data) {
return self.imageUrl = "pathToDefaultImage";
});
},
...

Can I send multiple responses via Node.js to the client?

I'm using Node.js and I want to send back multiple responses to the client. So the client will send an AJAX POST request and get back some data. But the server has to continue to do some processing and when that's done, I want it to send more data back.
I know this is a good candidate for Socket.io, but I haven't really seen an example of how to use socket.io in the context of an MVC framework. Does it go in the controller?
You could use Server Sent Events.
Here's an example:
https://github.com/chovy/nodejs-stream (full source code example)
UI
var source = new EventSource('stream');
source.addEventListener('a_server_sent_event', function(e) {
var data = JSON.parse(e.data);
//do something with data
});
Node
if ( uri == '/stream' ) {
//setup http server response handling and get some data from another service
http.get(options, function(resp){
resp.on('data', function(chunk){
res.write("event: a_server_sent_event\n");
res.write("data: "+chunk.toString()+"\n\n");
});
});
}

Resources