send callback from nodejs backend to frontend - html

I have got a fileUpload (made with NodeJS) and i want to show the success of the upload in the html in the {{upload.message}}. I implemented it with AngularJS but it didn't work. What am I doing wrong?
HTML
<form enctype="multipart/form-data" action="/upload"
method="POST">
<div class="form-group">
<input type="file" name="file" />
<p></p>
<input type="file" name="file" />
<p></p>
<input type="file" name="file" />
<br> <br>
<input type="submit" value="Upload File" name="submit"
class="btn btn-primary">
</form>
<span>{{upload.message}}</span>
</div>
NodeJS
router.post('/upload', function(req,res){
upload(req,res,function(err) {
var fileNames = [];
req.files.forEach(function(element){
fileNames.push(element.filename);
})
console.log('Selected Files: ', fileNames);
if(err){
res.end("Error: '" , err , "'");
}else{
res.sendStatus(204);
}
});
});
AngularJS
var self = this;
this.message = "";
this.upload= function(){
$http.post('/uploads')
.then(function success(result){
self.message = "Upload worked";
},
function error(response){
self.message = "Error upload failed";
});
};

edit: You should read this book: http://www.allitebooks.com/read/index.php?id=7630
You normally make a request from browser to the server and not the other way around. I suggest using Ajax with polling. If you insist on sending a request from the server to the browser you could use Comet (but I do not recommend that solution).
With jQuery (altough not mentioned in your question), you would write something like this to poll every x seconds:
function doPoll() {
$.ajax({
url: "/uploads",
type: "POST",
data: {
//Set an empty response to see the error
xml: "<response></response>"
},
dataType: "text xml",
success: function(xml, textStatus, xhr) {
if (xhr.status == "200") {
//do the thing you wanted to do on succes
}
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
setTimeout(doPoll,5000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
P.S. Totally forgot about sockets I also like that solution, but beware sockets are not REST like HTTP.
You should think of it like this: a browser is meant to make stateless
requests, not to keep open a connection, however with commet or
websockets it's possible. With polling which I would recommend you ask
the server a lot of times for the info until you get the desired
response.
From the wiki about Comet:
None of the above streaming transports work across all modern browsers
without negative side-effects. This forces Comet developers to
implement several complex streaming transports, switching between them
depending on the browser. Consequently, many Comet applications use
long polling, which is easier to implement on the browser side, and
works, at minimum, in every browser that supports XHR. As the name
suggests, long polling requires the client to poll the server for an
event (or set of events). The browser makes an Ajax-style request to
the server, which is kept open until the server has new data to send
to the browser, which is sent to the browser in a complete response.
The browser initiates a new long polling request in order to obtain
subsequent events. Specific technologies for accomplishing
long-polling include the following:

Related

form tag in html not posting/hitting website

so im trying to create a link shortener for me and my friend
to use on our small service center
but im having a small problem.
i set up an express server to get this done, whilst creating a fileuploader
which i used postman to test.
both work fine, but this is where im getting the problem.
whenever i use the snippet below to try and send data to the 'api'
it doesnt even post/touch the website yes i debugged to see if it touched
its only when i use form post/get method that the code doesnt work
HTML code snippet
<form method="POST" action="/shorten" enctype="application/x-www-form-urlencoded">
<label for="fUrl" class="sronly">URL</label>
<input class="input"
required
placeholder="URL"
type="url"
name="fUrl"
id="fUrl"
/>
<button type="submit">Shrink This!</button>
</form>
ive tried many things, i dont know if its because im rendering it with EJS or what
i tested it on its own with an HTML file but to no avail
if theres anything in this post i missed to go over let me know!
It looks like there is some issue with mapping between client and server. Try changing action value to the your API endpoint.
<form method="POST" action="http://myserver.com/shorten" enctype="application/x-www-form-urlencoded">
<label for="fUrl" class="sronly">URL</label>
<input class="input"
required
placeholder="URL"
type="url"
name="fUrl"
id="fUrl"
/>
<button type="submit">Shrink This!</button>
</form>
It was a problem of browsers being a tad too fast/slow
fix is here
// thanks to Vikasdeep Singh for this oddly specific url regex test
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
return (res !== null)
};
var el = document.getElementById("yourButtonID");
el.addEventListener("click", avoidNSErrorWithFirefox, false); //Firefox
function avoidNSErrorWithFirefox() {
ElementInterval = setInterval(function() {
var url = document.getElementById("inputURL").value; // input tag
if (isValidURL(url)) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://your-url.com/shorten", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"url": url
}));
}
clearInterval(ElementInterval);
}, 0);
};
works like a charm on all browsers ive tested
edge chrome opera firefox
Hopefully me and my friends fix saves you some trouble with form / express problems!

HTML button to submit form with popup

I have this code that submits a form and sends a mail, and it opens a different page saying successful:
<input type="submit" value="submit">
Then I also have this code which is a sexy button that pops up a message that the mail has been sent (even though it hasn't):
Submit
How do I combine the code so that the mail sends with the sexy button and I get the popup, instead of landing on a new page?
I'd suggest using ajax to confirm the email sending, after which pop-up your so called sexy button.
<form method="POST" action="/your/path/to/php/file">
<input type="submit" value="submit" onclick="someFunction();">
</form>
<a id="href_id" href="submit-message.html" class="nicdark_marginbottom20_iphoneland nicdark_marginbottom20_iphonepotr nicdark_mpopup_ajax nicdark_outline white nicdark_btn nicdark_bg_bluedark medium title">Submit</a>
<script type="application/javascript">
function someFunction() {
$.ajax({
type: 'POST',
url: 'route/to/php/file',
data: {
// data goes here
},
cache: false,
headers: {
// headers(if any) fo here
},
success: function(){
$('#href_id').show();
}
});
}
</script>
The php file may look something like this:
if(mail ($to, $subject, $message, $additional_headers = null, $additional_parameters = null)) {
return true;
}
Now, clearly this is not a complete code and should not be taken as such, this is mearly a pointing in the right direction of sorts.
I'm using jQuery here simply because I'm more familiar with it, but all this can be done in pure javascript, there's no real need to use jQuery if you don't want to.
Read more about ajax, PHP and Ajax.
As a final note, the logic is as such:
Do an ajax call in the front-end
Send email in backend using PHP(or your language of choice)
Return a response that confirms or not that the email has been sent
Based on that response display the pop-up

How to pass back values from Node JS to Html using EJS

I am trying to POST some values using my HTML form to a node JS method. Thereafter, I need to send the return result back from NODE JS and display it in the HTML page.
I am also using EJS to send back the values to the form. However, the result doesn't get displayed.
Basically, After the user clicks on the submit button on the HTML form, values should be passed to Node Js processed and send back a result Success or failed to the HTML doc where it'll display.
My code is as follows:
HTML CODE:
<form id="form-register" action="http://localhost:8089/ttt"" method="post" enctype="multipart/form-data">
<input type="logintext" value="" name="nam" class="nameC" id="mc" >
<input type="submit" name="subscribe" id="mc-submit-number">
<label >REEEEE <%= titles %></label>
</form>
NODE JS CODE:
app.post('/ttt', function (req,res){
loginProvider.signUp(params, function(err, data) {
if (err) {
res.render('index',{title: 'HOME',titles:err.stack
});
res.send('WHATTT');
}
else {
console.log('Result ' + data); // successful response
res.render('index',{title: 'HOME',titles:'SUCCESS'
});
res.end('xzxzxzxzxzx');
}
});
}
You could (or rather have to) use AJAX.
Then you can manually send your form parameters via post request to your Node server and return a response object with either an error or a success message.
The reason your code isn't working is because you have already loaded the DOM of the HTML page and when you are making that request the only way for EJS to work is if you reload the page since EJS just goes through your file and string replaces
My best solution is to have a normal AJAX call to your '/ttt' and have the Node.js do a 'res.send("SUCCESS");' and in your html you can set that label or any part of your document page to "SUCCESS"
With JQuery
$.post("/ttt", function(data, status){
$("#yourLabel").text(data);
});

How I use the data from Angular on Node JS? And how can I make a page load the information about a certain "data"?

I'm working on a project that I need from login, to compare the information at the form with the database. And later, after doing the validation, I need to load the information of a login in another page (I have no idea how).
(I tried to find some tutorials, but all of them use Express, that I'm not allowed to)
Now my code:
HTML (I think this part is OK, cause I could save the information in $scope.u)
<form ng-controller = "login" ng-submit="submit(user)">
<label>Login:</label>
<input type="text" ng-model="user.login" required>
<label>Senha:</label>
<input type="password" ng-model="user.pwd" required>
<label><input type="checkbox"> Lembre-me</label>
<button type="submit" class="btn btn-default">Login</button>
<p>{{user.login}}</p>
<p>{{user.pwd}}</p>
<p>LOGIN:{{user.login}}</p>
<p>SENHA:{{user.pwd}}</p>
</form>
Angular (I'm not sure if I understood the idea of $http.post, so I don't know if I can send the info of $scope.u to Nodejs)
app.controller('login',function($scope,$http){
$scope.u = {};
$scope.submit = function(user) {
$scope.u = angular.copy(user);
console.log($scope.u);
};
$http.post('/servico/login', $scope.u).success(function(data, status) {
console.log('Data posted successfully');
});
});
Node (If I could use the information of $scope.u, my problem would be finished there, but I don't know how I can load the information in another page)
The button Login should compare the values from the form and them, maybe, use to send to the other page.
function login(request,response){
var queryString = 'SELECT uLogin,uSenha FROM usuarios';
connection.query(queryString,function(err,rows){
});
}
I hope I've been clear with my doubt.
Thanks for your help.

How to send form field value to a REST service using JSON or AJAX

I have a form field (email signup) on the site, and the email provider wants me to submit it to their REST web service and get a response. I've never used JSON or AJAX before so floundering!
The HTML:
<form>
<input type="hidden" name="gid" value="12345678">
<input type="hidden" name="user.CustomAttribute.NewsletterPopUp" value="Global">
<input type="hidden" name="user.CustomAttribute.NewsletterOptIn" value="True">" value="True">
<input type="text" name="uemail" class="email_input_field" value="please enter your email" size="30" maxlength="64" onFocus="clearText(this)">
<input type="submit" name="signup" value="signup" class="email_submit_button">
</form>
Currently, using Javascript and using window.location to visit the URL (which creates the action instead of posting it) they want it converted to a form post action with XML response. What happens now:
$(".email_submit_button").click(function(){
var uemail = $('.email_input_field').val();
window.location = "http://example.com/automated/action.jsp?action=register&errorPage=/automated/action.jsp&gid=12345678&uemail="+uemail+"&user.CustomAttribute.NewsletterPopUp=Global&user.CustomAttribute.NewsletterOptIn=True";
return false;
}
});
I see you'r using jQuery so you can use the $.post to post to the server like this:
var url = "http://example.com/automated/action.jsp"
var data ={
"gid": form.gid,
"action": register,
"uemail": form.uemail,
"errorPage": "/automated/action.jsp",
"user.CustomAttribute.NewsletterOptIn": user.CustomAttribute.NewsletterOptIn,
"user.CustomAttribute.NewsletterPopUp": user.CustomAttribute.NewsletterPopUp
};
var success_func = function(data){
//do what you want with the returned data
};
$.post(url, data, success_func);
Documentation for $.post.
Or you can use the pure longer Ajax version it's mentioned in the documentation of the $.post.
EDIT:
I forget you can't do xhttpresuext to a different domain you need to use JSONP, here's a link to another SO post explaining everything by detail
Hope this help.
$(".email_submit_button").submit(function(e) {
// stop form from submitting
e.preventDefault();
// Grab all values
var uemail = $('.email_input_field').val();
// make a POST ajax call
$.ajax({
type: "POST",
url: "YOUR URL", // set your URL here
data: {
uemail: uemail // send along this data (can add more data separated by comma)
},
beforeSend: function ( xhr ) {
// maybe tell the user that the request is being processed
$("#status").show().html("<img src='images/preloader.gif' width='32' height='32' alt='processing...'>");
}
}).done(function( response ) {
// do something with the received data/response
//$("#status").html(response);
});
});
Not sure if ".email_submit_button" is the class given to the submit button or the form.. you need to use the id or class given to the form and not the submit button.. hope this helps