Variable within a object reference - javascript

I'm getting the username from the input field and sending it as the parameter to the searchUser function. What it returns the username with a value of more objects.
so if I send 'daveeeeeed' in the input field and submit then it sends back
{"daveeeeeed":{"id":30155374,"name":"daveeeeeed","profileIconId":577,"summonerLevel":30,"revisionDate":1443840218000}}
so in my html document I'm trying to access res.'daveeeeeed'.name to print out the name from the request. But obviously {{ res.username.name }} isn't working. and in the javascript I cant use $scope.res = data.username.name.
My question is; how do I use a variable from a object? ex.
my goal
res.username.name //replace username with whatever was send in form
<form>
<input type="text" ng-model="username" placeholder="username" name="username" />
<button ng-click="searchUser(username)" class="btn btn-primary">Submit</button>
</form>
{{ res }}
here's the javascipt
$scope.searchUser = function(username){
$http.get('https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' + username + '?api_key=<key>').
success(function(data) {
$scope.res = data;
}).error(function(err) {
$scope.res = "User not found";
});
}

Adding Answer from comment:
You can add username to $scope before making http call. Then you can access it in your DOM template like this {{ res[username] }}.
So Your code should look like this:
$scope.searchUser = function(username){
$scope.username = username; // Notice this change
$http.get('https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' + username + '?api_key=<key>').
success(function(data) {
$scope.res = data;
}).error(function(err) {
$scope.res = "User not found";
}
);
}
Template should look like this:
{{ res[username] }}

you can do it in two ways -
Method 1 :
When returning the result, make the property of the object a static value (e.g. instead of sending daveeeeeed, send user).
{"user":{"id":30155374,"name":"daveeeeeed","profileIconId":577,"summonerLevel":30,"revisionDate":1443840218000}}
this way, you can display the name as :
<div> {{res.user.name}} </div>
Method 2
If you follow your own way,
<div> {{res[username].name}} </div>

Related

Node js giving ajax request undefined value error when trying to get value from mongoose document user

I have written a node js script where I am using ajax request to get data. I have two documents in mongoose one is user and another is post in a collection. Now when I create a post by signed in user and ajax loads the data in dom I am getting user name as undefined.I am not able to figure out a solution for this. Here is my code
let createPost = function(){
let newPostForm = $('#new-post-form');
newPostForm.submit(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/posts/create-post',
data: newPostForm.serialize(),
success: function (data) {
console.log(data);
let postData = createNewPostDom(data.data.post);
$('#posts-list-container>ul').prepend(postData);
deletePost($('.delete-post-button',postData))
},
error:function(error){
console.log(error.responseText);
}
})
});
}
Now coming to another function which will show the user name
let createNewPostDom = function(post){
return $(`<li id="post-${ post._id}">
<small><a class="delete-post-button" href="posts/delete/${post._id}">Delete</a></small>
<h2>${post.content }</h2>
<small> ${ post.user.name } </small>
<div class="post-comments">
Enter comment
<form action="/comments/create" id="new-comment-form" method="post">
<input
type="text"
name="content"
placeholder="enter comment"
required
/>
<input type="hidden" name="post" value="${ post._id }" required />
<input type="submit" name="Post comment" />
</form>
<div class="post-comment-list">
</div>
</div>
</li>`);
The code ${ post.user.name } is giving me undefined value. Need help for this.

How to change Flask WTForm field value in HTML using javascript?

I have this simple hidden field in an HTML form:
<input type="hidden" id="response" name="response">{{ form.response}}</div>
and I want to change the it's value so that I can use it using flask and WTForms later on.
I tried this:
function(token){
document.getElementById('response').value = token
}
and the function is being called with a valid token, but no success.
Any suggestions?
The input field for a form is created as follows, where additional arguments like a label or validators are possible.
class ExampleForm(FlaskForm):
response = HiddenField()
submit = SubmitField()
The following code is required to request the value on the server side.
#app.route('/', methods=['GET', 'POST'])
def index():
form = ExampleForm(request.form)
if form.validate_on_submit():
print(form.response.data)
return render_template('index.html', **locals())
If you now render within the template, the attributes name and id are set automatically. The value corresponds to the identifier of the variable to which the input field was assigned. To query and set the value, you can either use a selector with the name attribute or the id of the input field.
<form method="post">
{{ form.csrf_token }}
{{ form.response }}
{{ form.submit }}
</form>
<script type="text/javascript">
(() => {
const token = 'your token here';
let responseField;
// Selecting the input field based on the id attribute,
responseField = document.getElementById('response');
responseField.value = token;
// or select based on the name attribute.
responseField = document.querySelector('input[name="response"]');
responseField.value = token;
})();
</script>

Why am I getting a JSON error and how do I fix it

I am trying got take the value that is inserted into the first and last name fields and then take that and insert it into a MySQL database backend that I have running using restAPI. I got some help to fix the form but I am trying to find the error when I try to take the input form the form and enter it in the database
The table code is this
<div class="superhero">
<h1>Lets add our first name </h1>
<form action="/add_user" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<form action="/add_user" method="post">
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
Then this is taken into the nodeJS server with this command
app.post('/add_people', function(req, res){
axios.get('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
Then at the end it is going to be taken to the RestAPI with that is using this route
#app.route('/api/adduser', methods = ['POST']) # This is a post method because the user needs to be able to add info
def adding_stuff():
request_data = request.get_json() # Gets the info from the table and converts to JSON format
new_fname = request_data['firstname']
new_lname = request_data['lastname']
conn = create_connection("", "", "", "")
sql = "INSERT INTO restaurantusers (firstname, lastname) VALUES ('%s', '%s');" % (new_fname, new_lname) # This sql statement will then be uploaded to the databse to add a new record
execute_query(conn, sql) # This will execute the query
return 'Post worked'
Sorry if what I am asking sounds really complicated. Professor goes too fast in class and I've been trying to find out how to do this for sometime with no luck.
UDATE: I later changed the two items as suggested. The route is
app.post('/add_people', function(req, res){
axios.post('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
and the form is now
<form action="/add_people" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
I get the error that
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
and also this error on the restAPI window
TypeError: 'NoneType' object is not subscriptable
First, you'll need to update your form and inputs to accept user input properly by using the value attribute on the <input> so instead of
<input type = "text" firstname = "firstname">
<input type = "text" lastname = "lastname">
Do this
<input type="text" value="firstname">
<input type="text" value="lastname">
this will send the values firstname and lastname to your API.
If you need to dynamically accept user input you'll need to watch input changes using javascript and handle the form submit with it too. Check
input value attribute and Javascript form.
To send the data from your node server to your python server you'll need to update
axios.post('http://127.0.0.1:5000/api/adduser')
To
axios.post('http://127.0.0.1:5000/api/adduser', { first_name: req.body.firstname, last_name: req.body.last_name })
Because that way you're passing the form data inside req.body to your python server

Odoo AJAX attachment or images creation into client-side (frontend)

What i know
In a modal creation object i know how add an attachment or image because all <input> are inside a form and when user click the submit button the form action trigger the controller that manage inputs data.
For Example:
<form id="formId" t-attf-action="/my/object/#{slug(object)}/create" method="post" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
<input type="hidden" name="object" t-att-value="object"/>
<input type="text" name="text" class="o_website_form_input form-control"/>
<input type="file" name="image" class="o_website_form_input form-control" accept="image/*"/>
<input type="submit" class="btn btn-success" value="Create/"/>
</form>
Will trigger the following controller:
#route(['/my/object/<model("object.model"):object>/create'],
type='http', auth="user", methods=['POST'], website=True)
def object_create(self, object, **post):
if not object:
return request.render("website.404")
attachment = post.get('image')
text = post.get('text')
values = {
'text': text,
}
# If present get image data from input file
if attachment:
data_image = base64.b64encode(attachment.read())
values['image'] = data_image
request.env['object.model'].create(values)
# Redirect to the details page with new value
string_url = '/my/object/view/' + slug(object)
return werkzeug.utils.redirect(string_url)
So, now we have a sync POST that create object with text and image with a redirect to the create object.
Now, the question is:
How manage records with images or attachments update?
For simple record update i use this methods:
1) a modify button that show hidden <input> or <textarea> that will
take new values
2) an on.('change', '.class-to-monitorate') that populate an object like
point 3)
3) dataToSend = {}
It become something like:
dataToSend = {object_id: {values from input}} --> This is Good for write() inside controller
4)An ajax.jsonRpc("/my/path/for/update/value", "call", dataToSend)
The problem is that with controller type JSON and <input type="file"> i don't know how pass files.
It's possible to use a controller type="http" and send data like a <form>?
So i can receive all the changed <input type="file"/> and store them without refreshing the entire page every time.
EDIT
Here the JS that populate dataToSend object
// onChange bind that manage confirmity line values save
$(document).on("change", ".conformity-line-value", function () {
let value = $(this).val();
let name = $(this).attr('name');
let type = $(this).attr('type');
let non_conformity_line_id = Number($(this)
.closest('div.non-conformities-line')
.find("input[name='non_conformity_line_id']").val());
//If the dict for this line does not exist create it
if (!dataToSaveConformities[non_conformity_line_id]) {
dataToSaveConformities[non_conformity_line_id] = {}
}
//Add changed elements into dic to corresponding line
switch (name) {
case 'name':
dataToSaveConformities[non_conformity_line_id]['name'] = value;
if (value === '') {
$(this).addClass('error_input');
} else {
$(this).removeClass('error_input');
}
break;
case 'non_conformity_note':
dataToSaveConformities[non_conformity_line_id]['non_conformity_note'] = value;
break;
default:
break;
}
});
The class .conformity-line-value is set to all input,textarea,select,checkbox that i need to monitorate if the user change them.
Here the JS function that call controller that save data:
function save_changed_values() {
if (!isEmpty(dataToSaveConformities)) {
ajax.jsonRpc("/my/sale_worksheet_line/non_conformity/update/value", "call", dataToSaveConformities)
.then(function (data) {
//Clear data to send
for (var member in dataToSaveConformities) delete dataToSaveConformities[member];
if (data.error) {
//FIXME: check that case or manage it
$('.non-conformities-div').load(window.location + " .non-conformities-div>*", function () {
$('select.js-conformities-read-multiple').select2();
});
} else {
$('.non-conformities-div').load(window.location + " .non-conformities-div>*", function () {
$('select.js-conformities-read-multiple').select2();
});
}
});
}
}
I try to take the base64 of image from <input type="file"> and put it inside sended object (parsed as JSON)
But in the controller i receive an empty value inside **post

Display Firebase data previously/currently submitted

So I'm simply trying to make a page where I have an input for a user's name and age, then they submit that, and it sends that to the Firebase database, and that is working perfectly. The other thing I'm trying to do is display the data submitted in a "view" section. So just display the user's name and age below. I'm struggling to understand/get why my code is not working -- I have an h3 in place that should be replaced by the data that is stored in my database.
Here is my code for the retrieval section
'Age' is what one category of children is called (the other is 'Name')
<h2> View</h2>
<h3 id="showData"> Hello</h3>
<script>
showData = document.getElementByID('showData');
var firebaseDataRef = firebase.database().ref().child('Age');
firebaseDataRef.on('value', function(snapshot){
showData.innerText = snapshot.value;
});
the rest of my code:
<input type=text" id="userName">
<input type="number" id="userAge">
<button id="btUpdateMessage" margin-bottom="20px" onclick="addFB()"> Update</button>
<script>
var lblCurrentMessage = document.getElementById('lblCurrentMessage'),
userName = document.getElementById('userName'),
btUpdateMessage = document.getElementById('btUpdateMessage'),
userAge = document.getElementById('userAge'),
rootRef = new Firebase('https://addview-c21e6.firebaseio.com'),
currentMessageRef = rootRef.child('Name'),
currentNameRef = rootRef.child('Age');
function addFB()
{
currentMessageRef.push(userName.value);
currentNameRef.push(userAge.value);
userName.value = '';
userAge.value = '';
}
.value is not a property of DataSnapshot. You need to call the .val() method on it.
firebaseDataRef.on('value', function(snapshot){
showData.innerText = snapshot.val();
});
docs: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#val

Categories

Resources