When I add an item to my database it just shows the id was added but the name attribute I chose for the item was not added: Meaning - The 'name' attribute I add to the 'player' is not persisted when I save it. Can someone please tell me why? I think it's an issue with string conversion but I am not sure.
*I am able to update the item's name using POSTMAN's PUT option.
Using the x-www-form-urlencoded option, I can update my item's name with a plain string.
So do I need to simply do some sort of string conversion or is something else wrong with my code? And please let me know if you need me to provide more code. Thanks!
Here's my code:
browser control - network:
Yes - (and I only add a name attribute)
When I add the name attribute it is not saved - yet an item is still created. That is the problem.
browser console - network tab:
Remote Address:127.0.0.1:3000
Request URL:http://localhost:3000/api/players
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,he;q=0.6
Connection:keep-alive
Content-Length:18
Content-Type:application/json;charset=UTF-8
Cookie:connect.sid=s%3AX2FaOplCDPU3qDaM7vVQPb5vFo_ievn1.zFM%2FKNj2QN5eDspCFOJEE2fYwXiTyUnN90sR8oTfnpI
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/add
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Request Payloadview source
{showName:Jay}
showName: "Jay"
Response Headersview source
Connection:keep-alive
Content-Length:29
Content-Type:application/json
Date:Sun, 06 Jul 2014 06:13:25 GMT
X-Powered-By:Express
Here's code of the route: server side. maybe there's an error here:
.post(function(req, res) {
var player = new Player(); // create a new instance of the Player model
player.name = req.body.name; // set the player name (comes from the request)
player.sport = req.body.sport;
player.league = req.body.league;
player.team = req.body.team;
player.age = req.body.age;
player.description = req.body.description;
// save the player and check for errors
player.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Player created!' });
});
})
.get(function(req, res) {
Player.find(function(err, players) {
if (err)
res.send(err);
res.json(players);
});
});
controller: add.js
angular.module('MyApp')
.controller('AddCtrl', ['$scope', '$alert', 'Player', function($scope, $alert, Player) {
$scope.addShow = function() {
Player.save({ showName: $scope.showName },
function() {
$scope.showName = '';
$scope.addForm.$setPristine();
$alert({
content: 'Player has been added.',
placement: 'top-right',
type: 'success',
duration: 3
});
},
function(response) {
$scope.showName = '';
$scope.addForm.$setPristine();
$alert({
content: response.data.message,
placement: 'top-right',
type: 'danger',
duration: 3
});
});
};
}]);
template: add.html
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Add Sports Player</div>
<div class="panel-body">
<form class="form" method="post" ng-submit="addShow()" name="addForm">
<div class="form-group" ng-class="{ 'has-success' : addForm.showName.$valid && addForm.showName.$dirty, 'has-error' : addForm.showName.$invalid && addForm.showName.$dirty }">
<input class="form-control" type="text" name="showName" ng-model="showName" placeholder="Enter TV show name" required autofocus>
<div class="help-block text-danger" ng-if="addForm.showName.$dirty" ng-messages="addForm.showName.$error">
<div ng-message="required">Sports Player's name is required.</div>
</div>
</div>
<button class="btn btn-primary" type="submit" ng-disabled="addForm.$invalid">Add</button>
</form>
</div>
</div>
service: player.js
angular.module('MyApp')
.factory('Player', ['$resource', function($resource) {
return $resource('/api/players/:_id');
}]);
From what I can tell, you are making a POST HTTP request to /api/players:
Request URL:http://localhost:3000/api/players
Request Method:POST
However, you're only sending showName:
Request Payloadview source
{showName:Jay}
showName: "Jay"
But on the server side, you are not looking for showName, and instead looking name, sport, league, etc:
var player = new Player(); // create a new instance of the Player model
player.name = req.body.name; // set the player name (comes from the request)
player.sport = req.body.sport;
player.league = req.body.league;
player.team = req.body.team;
player.age = req.body.age;
player.description = req.body.description;
If you want to store name, then you'll need to send over name instead of showName. If you want to store showName, then you'll need to pull it from the request body (req.body.showName). So either send over all those attributes from the client side to the server side, or change the server side to accept only showName for a Player.
Hopefully that makes sense? There's just a disconnect from what you're sending on the client side to what you're looking for on the server side. It's also a bit confusing that it looks like on the client side you're dealing with a TV show, and on the server side its some player for a sport team?
Related
Using Nodejs, Express, EJS
I see a lot of 'Send Data from Server to Client' but not from Client to Server AND sending the data from a tag not from a form input.
I would like to send the content of a tag from my ejs page/client to my nodejs/server.
What I'm trying...
page.ejs
<div>
<form action="/brewery" method="GET">
<div class="form-group">
<input type="text" class="form-control"
placeholder="search brewery name"
name="search">
</div>
<input class="button" type="submit" value="Submit">
</form>
</div>
<div>
<ul>
<% searchBreweryList.forEach(function(searchBrewery){ %>
<div>
<li>
Brewery Name: <span><%= searchBrewery.brewery.brewery_name %></span>
Brewery ID: <span name="brewID" id="shareBreweryID"><%= searchBrewery.brewery.brewery_id %></span>
</li>
</div>
<% }) %>
</ul>
</div>
Then on my server side...
server.js
app.get('/brewery', async (req, res) => {
var searchBreweryFound = req.query.search;
var isIndie = req.params.brewID
//console.log(isIndie)
//console.log(searchBreweryFound)
try {
request("https://api.com/v4/search/brewery?access_token=abc123&limit=1&q=" + searchBreweryFound, function (error, response, body)
{
if (error) throw new Error(error);
const searchBrewery = JSON.parse(body);
const searchBreweryList = searchBrewery.response.brewery.items.map(item => item );
res.render('brewery.ejs', {searchBreweryList});
//console.log(searchBreweryList);
});
} catch(e) {
console.log("Something went wrong", e)
}
});
So the above Get call is just an example where I'm trying to take the result in the client side span that looks like <span name="brewID">. Then I'm trying to give that ID number to the server in the var seen as var isIndie = req.params.brewID.
But this does not seem to be a method that allows me to pass content from a span in client to server.
What approach should I be taking? Thanks!
It's not clear what you mean by "sending data from client to server". Standard method of sending data from client to server is using XMLHttpRequest (XHR) inside *.js file(s), but based on your code you want to redirect browser window to URL with some parameters. When browser hit your endpoint, for example /brewery, server will render *.ejs file and respond to browser with HTML code.
Redirecting browser with EJS
Below code is based on code you posted.
<div>
<ul>
<% searchBreweryList.forEach(function(searchBrewery){ %>
<div>
<li>
Brewery Name: <span>
<%= searchBrewery.brewery.brewery_name %>
</span>
Brewery ID: <span name="brewID" id="shareBreweryID">
<%= searchBrewery.brewery.brewery_id %>
</span>
<!-- Here we create link using parameter of brewery (version with param) -->
Go to brewery
<!-- Version with query param -->
Go to brewery
</li>
</div>
<% }) %>
</ul>
</div>
After clicking Go to brewery browser will hit /brewery endpoint with param brewery_id. I also noticed that in posted example var isIndie = req.params.brewID may not work.
Bonus: req.query vs req.params
Both req.query and req.params are used to get some informations from endpoint URL. However req.query and req.params are not the same.
Using req.query
For endpoint: /brewery?id=5&q=test
const id = req.query.id // 5
const q = req.query.q // 'test'
Using req.params
To use req params you must place param name somewhere in url of express endpoint.
app.get('/brewery/:id', async (req, res) => {
var id = req.params.id
})
So to make your example with req.params working:
app.get('/brewery/:brewID', async (req, res) => {
var searchBreweryFound = req.query.search;
var isIndie = req.params.brewID
// Rest of your code
})
I am having some trouble trying to connect/link two Azure logic apps together.
Here is my scenario and how I am trying to use the Logic apps.
I have created a 1st Logic app : that allows a user to upload a .mp4 media file into a folder on OneDrive, and the logic app checks to see if there is new file on that OneDrive folder. If there is new file, it will trigger the logic app and Index the video onto https://www.videoindexer.ai/.
2nd - Logic App : After the video is indexed to https://www.videoindexer.ai/ , I want the user to pick language(s) from the custom web page that I have created, for caption translation(here is the custom web page). Once the user choose the language(s) they click on "submit" and this will send the data(languages) to my 2nd logic app URL end-point, and trigger my second logic app and get the captions based on the user's selection of languages. Finally, it will then output those caption files on to a OneDrive folder.
Here is how I have created both the Logic apps:
1st Logic APP:
2nd Logic APP:
HTML:
<form id="language-form">
<h3>Please select the languages(s) for translating captions: </h3>
<ul>
<li><label><input type="checkbox" name="language" value="en-US"> English</label></li>
<li><label><input type="checkbox" name="language" value="es-ES"> Spanish</label></li>
<li><label><input type="checkbox" name="language" value="ko-KR"> Korean</label></li>
<li><label><input type="checkbox" name="language" value="th-TH"> Thai</label></li>
<li><label><input type="checkbox" name="language" value="ja-JP"> Japanese</label></li>
</ul>
<button type="submit">Submit</button>
</form>
JavaScript:
function fetchForLanguages(languages) {
console.info('starting fetch for', languages)
return fetch("https://prod-00.westus2.logic.azure.com:443/workflows/xxxxxxxxxxxxxxxxx", { // this is my azure provided endpoint
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
languages: languages
})
}).then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.status} ${response.statusText}`);
}
return response.json()
})
}
function handleSubmit(event) {
event.preventDefault()
const data = new FormData(event.currentTarget)
const languages = data.getAll('language')
console.info('languages selected:', languages)
fetchForLanguages(languages)
.then((result) => console.log('got result:', result))
}
let form = document.getElementById('language-form')
form.addEventListener('submit', handleSubmit)
Here is workflow quite similar to yours with explanation:
[https://azure.microsoft.com/en-us/blog/logic-apps-flow-connectors-will-make-automating-video-indexer-simpler-than-ever/][1]
Here is python function to check for the file is ready before you send an email:
import requests
loc = '' # location
acc_id = '' # account id
vi_subscription_key = '' # primary key
def get_access_token(loc, acc_id):
headers = {'Ocp-Apim-Subscription-Key': vi_subscription_key}
params = {'allowEdit': 'true'}
access_token_req = requests.get(
f'https://api.videoindexer.ai/auth/{loc}/Accounts/{acc_id}/AccessToken',
params=params,
headers=headers)
access_token = access_token_req.text[1:-1]
return access_token
def is_video_proccessed(loc, acc_id, access_token, video_id, video_language='English'):
params = {'accessToken': access_token,
'language': video_language }
get_video_info_req = requests.get(
f'https://api.videoindexer.ai/{loc}/Accounts/{acc_id}/Videos/{video_id}/Index',
params=params)
response = get_video_info_req.json()
if (response['state'] != "Uploaded") and (response['state'] != 'Processing'):
print(f'Video {video_id} finished processing')
return True
Hope this help.
I am building a node.js,express.js and passport.js app. Once logged into the profile I ask the user to click a button “Get Location” to get the users location.
Profile.ejs
<form action="/testform" method="post" >
<div class="form-group">
<input type="text" class="form-control" id="latVal" placeholder="latitude">
<input type="text" class="form-control" id="longVal" placeholder="longitude">
</div>
<button type = "submit" class="btn btn-warning btn-sm">Save</button>
</form>
<button type = "submit" class="btn btn-warning btn-sm" onclick="getLocation()">Get Location</button>
onclick the getLocation() function is called which is located in mapCall.js
function getLocation()
…
//call to showLocation()
}
function showLocation(position) {
…
document.getElementById("latVal").value = latitude;
document.getElementById("longVal").value = longitude;
}
showLocation() sets the values in the form to the latitude (id="latVal") and longitude (id="longVal") returned from the API call. The values appear in the form field. From here I want to save these values to the users profile data in MongoDB which I try to achieve in routes.js by click of the “Save” button which triggers the function below
app.post('/testform', isLoggedIn, function(req, res) {
user.findById(req.user.id, function(err,user) {
if(!user) {
req.flash('error', 'No accound found');
return res.redirect('/profile');
}
user.location.latitude = req.body.latVal;
user.location.longitude = req.body.longVal;
user.save(function(err){
res.redirect('/profile');
});
});
});
When I console.log req.body.latVal and req.body.longVal the value for these variables is undefined. Nothing is saved in the db.
In server.js I have
var bodyParser = require('body-parser');
app.use(bodyParser());
Upon looking into proposed solutions to req.body returning undefined I tried
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
I didn’t think adding the two lines above would work because the value returned by the API is not in JSON format. This did not work. I checked the typeof for latitude and longitude and it is a number. I am not sure why req.body is not picking up the value.
My initial guess was that app.post tries to read the value before the API can return a value in which case req.body.latVal would read an empty field. I added the save button to test that theory which also proved wrong.
The closest thing I found to my issue is this which was never resolved.
Any guidance is highly appreciated or perhaps even a better way to accomplish this will be great. The reason I have the form fields populate is because I couldn't think of another way to send the values from the frontend to the backend for saving.
Add the name attribute to your inputs.
<input type="text" class="form-control" id="latVal" placeholder="latitude" name="latVal">
<input type="text" class="form-control" id="longVal" placeholder="longitude" name="longVal">
EDIT: (from the comment)
You can do an AJAX call to your server after the getLocation() call.
function getLocation() {
///you get the lat and long
showLocation(position)
saveLocation(latitude, longitude)
.then(function(resp){
//do something with resp
})
}
function saveLocation(latitude, longitude) {
//we have native fetch in newer browsers, so
return fetch("/testform", {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8", //if this doesn't work use the below one
// "Content-Type": "application/x-www-form-urlencoded",
},
body: JSON.stringify({latitude,longitude}), // body data type must match "Content-Type" header
})
.then(response => response.json());
}
This is just an outline of what you can do. Extend this code to your needs.
You are correct in most parts ,You just have to replace ID with name.that is the only way nodejs will be able to locate to your input field
Is it possible to create a form visual webpart with fields like name, email, address and submit button. After user submit data should be submitted to sharepoint custom list here custom list will have same fields like name, email, address. I created one custom list.
I search on internet but i didn't find any solutions for that. Also am new to sharepoint. If any one can provide some links it will be helpful.
Thanks
Yes, this is very possible using jQuery and AJAX.
So, lets say that, just to be brief, this is your input:
<input type='text' id='name' />
<input type='submit' id='submitdata' value='submit />
Using jquery, you would do this:
$(function(){
$('#submitdata').click(function(){
//this gets the value from your name input
var name = $('#name').val();
var list = "PutYourListNameHere";
addListItem(name, list);
});
});
function addListItem(name, listname) {
var listType = "PutTheTypeOfListHere";
// Prepping our update & building the data object.
// Template: "nameOfField" : "dataToPutInField"
var item = {
"__metadata": { "type": listType},
"name": name
}
// Executing our add
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log("Success!");
console.log(data); // Returns the newly created list item information
},
error: function (data) {
console.log("Error!");
console.log(data);
}
});
}
This SHOULD work. I am not at work where my SharePoint station is, so if you are still having issues with this, let me know.
You may use SPServices also, It will work
<script type="text/javascript" src="~/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="~/jquery.SPServices-0.7.2.min.js"></script>
HTML
<input type='text' id='name' />
<input type='text' id='email' />
<input type='text' id='mobile' />
<input type='submit' id='submit' value='Submit' />
SPServices
<script type="text/javascript">
$("#submit").click(function(){
var Fname=$("#name").val();
var Email =$("#email").val();
var Mobile =$("#mobile").val();
$().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "New",
listName: "YourCustomListName",
valuepairs: [["Fname", Fname], ["Email", Email], ["Mobile", Mobile]], //"Fname","EMail" and "Mobile" are Fields Name of your custom list
completefunc: function(xData, status) {
if (status == "success") {
alert ("Thank you for your inquiry!" );
}
else {
alert ("Unable to submit your request at this time.");
}
}
});
});
</script>
I have a form like this:
<form method='post' action='next' onsubmit="return validateMyForm();" >
<input type="text" id="data" />
<input type="submit" />
<p id="result"></p>
and this code for interact with node.js:
socket = io.connect();
function vlidateMyForm(){
var data = $('data').val();
socket.emit('login',{data: data}); // check dataBase in server
return false;
}
socket.on('responseLogin',function(result){
if(result){ // if data is valid
// submit form
}
else{ // data invalid
$('#result').html('field is not valid')
}
});
I want to submit my form, when the result is true. What should I do to solve this problem?
Change socket.on('responseLogin',function(result){... to socket.on('login',function(result){... should fix your problem
You can use Jquery submit to submit the form :
$("form#formID").submit();
Your form must have action attribute like action='url_to_post_to' for this.
Or if you like to use AJAX so that you can process the data, you can do :
$.ajax({
type: "POST",
url: 'url_to_post_to',
data: $("#formID").serialize(),
success: function(data)
{
alert(data);
}
});