Passing a JavaScript object from my form to my Node app - javascript

I have this jQuery code that gets data from my form. I used a console statement to see the value. However I want to pass the data to my Node application so that I can insert into a database.
$(function() {
$('#kiosk_signin').submit(function() {
var data = $('#kiosk_signin :input').serializeArray();
console.log(data[0]);
});
});
Please let me know what I need to do.

Assuming you are using express, posting this to your route.., and inserting into the DB..
You would do something like this in your routes..
router.post('/whereever', function(req,res,next(){
///assuming kiosk_signin is the name of an input field
///and the action is ='/whereever' method='post'
var data = req.body.kiosk_signin
console.log('if you want to log it', data)
db.insert({propert: data}).then(function(){
res.redirect('/home')
})
})
I don't use JQuery for submitting forms if I have a full-stack app, just because I intend on sending it directly to the server. Hopefully that helps..

Related

Sending a var with file, accessing it in script & Displaying a hidden div

Currently there is a form in home.html page which allows us to submit data. After data is saved, displaying the same .html page but different div (message like - Congrts, your poll is created ....).
For this I am sending a boolean var dataSaved while sending file so that i can retrieve the boolean var & display the div.
I am submitting form like this -
<form class="" action="/home/newPoll" method="post">
<form>
My server.js looks like this -
app.post('/home/newPoll', function (req, res) {
const newPoll = new PollModel({
............//something here
});
PollModel(newPoll).save(function(error, data){
if (error) {
throw error;
console.error("User Data is not saved."+error);
} else {
console.log("User data saved successfully");// working fine
res.sendFile(__dirname+'/views/home.html', {dataSaved: true}); // this page is displayed also
}
});
});
if this var dataSaved is true, I want to display the div.
$(document).ready(function(){
............// some more code here, are working fine.
const dataSaved = <%= dataSaved %>;
console.log(dataSaved); // not getting this
if (dataSaved ) {
$("#newPollDiv").hide();
$("#myPollDiv").hide();
$("#pollCreated").show();
}
}
I am not using any view template.
kindly suggest, also if any other way to do this.
You need to send the form data in an AJAX request. Right now it looks like the client isn't receiving your response at all, because you are refreshing the page after POSTing the form data.
Since you're using jQuery, I suggest you read: https://api.jquery.com/jquery.post/
Basically, you use the function $.post with the URL to send the form data to and a callback to display the divs as inputs.
Example:
$.post("/your/api/endpoint", function(response) {
$("#newPollDiv").hide();
//...
});

How to access data submitted by a form in Angularjs?

Here is an example from Ng-Book - the Complete Book on Angularjs
Book by Ari Lerner http://jsbin.com/voxirajoru/edit?html,output where ng-form has been used to create nested form elements and perform validation. As the each input field has same value for name attribute so how can on the server side I can access value of all three variables by using some server side language? Let's say it's PHP and method is post. Usually in PHP I would do this:
`$_POST['dynamic_input']`
but how is it possible to access three field values coming from input field using $_POST array?
Using the example from the link you provided, you can access form data by updating the code there with the following.
// Add the fields object as a parameter to submitForm()
<form name="signup_form" ng-controller="FormController" ng-submit="submitForm(fields)" novalidate>
// In the $scope.submitForm() function...
$scope.submitForm = function(data) {
alert(data[0].name); // Alerts name
alert(data[1].name); // Alerts password
alert(data[2].name); // Alerts email
};
If you log out the data received by submitForm(), you get the following:
[{"placeholder":"Username","isRequired":true,"$$hashKey":"004","name":"random name"},{"placeholder":"Password","isRequired":true,"$$hashKey":"005","name":"password"},{"placeholder":"Email (optional)","isRequired":false,"$$hashKey":"006","name":"email#host.com"}]
For passing to your server, package all this up as is or format it to your preference and send it to your server via the built in $http.post() or $resource() inside of the $scope.submitForm function.
An example of the formatted data could be:
$scope.submitForm = function(data) {
var postData = {};
postData.name = data[0].name;
postData.password = data[1].name;
postData.email = data[2].name;
... send postData to server via AJAX ...
// Creates the object: {"name":"random name","password":"password","email":"email#host.com"}
//alert(JSON.stringify(postData));
};

Call model function from JavaScript in Laravel

I'm actually running into little problems with my current project. Following case:
I've got a model called "Posting" with relations:
public function subscribers(){
return $this->belongsToMany('User');
}
In my view-file there is a table containing all Postings and also a checkbox for subscribing/unsubscribing with the matching value to the posting-id:
<input class="click" type="checkbox" name="mobileos" value="{{{$posting->id}}}"
#if($posting->subscribers->find(Auth::User()->id))
checked="checked"
#endif
>
Now the thing I want to archive:
A JavaScript is going to watch if the checkbox is checked or not. According to that, the current user subscribes/unsubscribes to the posting. Something like:
$('.click').on('click',function() {
// $posting->find(---$(this).prop('checked')---)->subscribers()->attach(---Auth::user()->id---);
// $posting->find(---$(this).prop('checked')---)->subscribers()->detach(---Auth::user()->id---);
});
Is there any possibility to archieve that or any other ways? I couldn't get my head around this so far.
Cheers,
Chris
If you want to use Ajax to achieve this, you will need a REST endpoint in Laravel for the subscriptions, e.g.:
http://localhost/subscribe/{{userid}}
When this Endpoint is called, the database can be updated. The function could also return a JSON showing, if the saving database in the database successful.
Use this endpoint to make an Ajax Call on click:
var user = {
id: 0 // retrieve the correct ID from wherever it is stored
}
$('.click').on('click',function() {
$.GET('http://localhost/subscribe/' + user.id,
function () { // this is the success callback, that is called, if the Ajax GET did not return any errors
alert('You are subsribed')
});
});
Ideally you won't be using the GET method, but instead use POST and send the user ID as data. Also you would need to retrieve the user ID from session or wherever it is stored.
Take care that as you are using Ajax it can easily be manipulated from the client side. So on the server you should check, if the user ID that was sent is the same as in the Session. Maybe you don't need to send the user id at all, but that depends on how your backend is built.

Manipulate form data before it's sent with jQuery

I want to encrypt some data in a form using jQuery before it's sent to the server, it can be a MD5 hash. It is a small project, so I don't really need to use SSL.
I have the following JavaScript code where I use $.md5 in the password confirmation info:
$(document).ready(function() {
var dataToSend = {};
dataToSend['action'] = 'signup';
dataToSend['name'] = name.val();
dataToSend['email'] = email.val();
dataToSend['confsenha'] = $.md5(pass2.val());
var options = {
target: '#error',
url: 'insert.php',
beforeSubmit: validate,
data: dataToSend,
success: function(resposta) {
$('#message').html(resposta);
}
};
$('#customForm').ajaxForm(options);
});
The problem is that the data is being duplicated. I tought that overwriting the data being sent by using the var dataToSend would make ajaxForm send only data in that map. But besides sending data from dataToSend, it also sends data from the form, so what I wanted to encrypt using MD5 appears both encrypted and clean. This is an example of what goes in the request:
usuario=user&email=user%40email.com&senha=12345&confsenha=12345&send=&action=signup&name=user&email=user%40email.com&confsenha=d41d8cd98f00b204e9800998ecf8427e
I know I have to define the a function beforeSerialize, but I don't know how to manipulate form data. Can anyone tell me how to do that?
As per the documentation on the plugin site:
data
An object containing extra data that should be submitted
along with the form.
The word along is the crux.
So when you pass data as a part of the options object that data is serialized and is sent along with any data/input elements values that are part of a form.
A better approach would be to hash the password value and assign it to the same field or another hidden field in the beforeSubmit handler(in your case the validate function) and remove the dataToSend object totally.
Something like:
Without any hidden element:
function validate(){
//Other Code
pass2.val($.md5(pass2.val()));
}
With a hidden element in the form:
function validate(){
//Other Code
$("#hdnPass").val($.md5(pass2.val()));
pass2.val("");
}

How to catch the post data of the submitted form

So that I can send those data using perl/php or any other programmatically.
Say I've a website with a combo box containing 100 cities submitting each city would get me the list of service centers in the city.
So I want to use a perl code where I'd loop all the cities and capture all the results, format them suitably in html for use in my website.
Doing all these using jquery etc will be manual. Also using jquery I'll not be able to catch response in easy way and save it on the hard disk as html file.
im not sure who is sending it where from your description. But i guess that you have an HTML form which sends those data to some PHP script . you specify the PHP in and you catch them on server side using $_POST["variable"]
if you want to send them somewhere else from your php script, use curl http://cz.php.net/manual/en/book.curl.php
This did the trick, I had to learn jquery finally:
var chk = [];
$("#splocator2 #stateid option").each(function() {
chk.push($(this).val());
});
alert(chk.length);
for (i = 0; i < chk.length; ++i){
$("#splocator2").attr("target", "_blank");
$("#stateid option:eq(0)").attr("selected", "selected");
$("#stateid option:eq(0)").attr("value", chk[i]);
$("#splocator2").submit();
}
JavaScript running on a page can not access variables POST'd to it AFAIK.
You may be thinking of sending an XHR to your server side code.
You may use the serialize() method:
$(function() {
$("#myForm").submit(function() {
alert($(this).serialize());
// No thanks I'm gonna use my own post request
// code here!
return false;
});
});
Example.

Categories