Set input values dynamically - javascript

I'm new to javascript, I'm working on a project that will using and enjoying the API of Last.fm.
But my question is the following:
I will make 2 fields:
First: Band name
Second: For fans of
When entering the name of the band I'll be sending a request to the last.fm API, but even there I am doing well.
The problem is that when I receive the request I want it automatically puts in the "For fans of" field.
I tried using the events onkeypress, onkeydown .. but have not had much success.
Anyone have any suggestions?
The request is made ​​through these files:
github.com/fxb/javascript-last.fm-api
My code is as follows:
Javascript:
/* Create a cache object */
var cache = new LastFMCache();
/* Create a LastFM object */
var lastfm = new LastFM(
{
apiKey : 'XXXXX',
apiSecret : 'XXXXXX',
cache : cache
});
function getName()
{
var bandname = $('#bandname').val();
var forfansof = $('#forfans').val();
forfansof = bandname;
/* Load some artist info. */
lastfm.artist.getSimilar(
{
artist: bandname
},
{
success: function(data)
{
/* Pega os 3 nomes das bandas similares */
for(var i = 0 ; i < 3 ; i++)
{
var artist = data.similarartists.artist[i].name;
$('#forfans').val($('#forfans').val() + artist + ", ");
}
},
error: function(code, message)
{
$('#forfans').val("Nenhum artista encontrado.");
}
});
}
HTML:
<form action="" method="post">
<input name="bandname" id="bandname" value="" onkeypress="javascript:getName();">
<input name="forfansof" id="forfans" style="width:300px;" value="">
</form>

I've have put the code that you have from GitHub into a fiddle, but I don't know anything about the API to say what needs to happen next.
Changes I made to fix immediate error that was shown in console.log
HTML
<form action="" method="post">
<input name="bandname" id="bandname" value="">
<input name="forfansof" id="forfans" style="width:300px;" value="">
</form>
JavaScript
document.getElementById("bandname").addEventListener("keypess", getName, false);
On jsfiddle

Related

req.body.Dates is not defined

I have 2 drop down menus that are dynamically being populated using SQL Server. Based on the selected items, I am loading a different ejs template. I have done this using the help of AJAX. However, I want to be able to load the data according to the selected criteria. For instance, if DD1 is selected as Andrew and DD2 as Date the table should load 7 columns based on those conditions.
AKA
SELECT * FROM exTable x WHERE x.Name = 'Andrew' and x.Date = '4/22/2019'
What I have already tried is to pass the selected item from the dropdown to the router, like so:
router.js
router.post('/selection', async (req, res) =>{
try {
var nameFromDB = await conn.query("SELECT DISTINCT pr.Name FROM WFS.Table1 pr WHERE pr.Group = 'Test'");
var dateFromDB = await conn.query('SELECT r.Date FROM WFS.Table2 r');
var tables = ("SELECT * FROM WFS.view v WHERE v.Date= '" + req.body.Dates + "' AND v.Name = '" + req.body.Names + "'");
console.log("SELECT * FROM WFS.view v WHERE v.Date= '" + req.body.Dates + "' AND v.Name = '" + req.body.Names + "'");
res.render('selection', {tables: tables, nameFromDB : nameFromDB , dateFromDB: datesFromDB});
}
catch (err) {
res.status(500)
res.send(err.message)
}
});
This is the output of the console.log :
SELECT top 100 * FROM WFS.view_workRequests_Extended v WHERE v.Revenue_Release_Id = '04/16/2019' AND v.Development_Manager = 'Andrew'
app.js
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/', router);
index.ejs
<script>
$(document).ready(function() {
$('#DDD').on('change', function(event) {
var selectedDate = $('#selections option:selected').val();
});
$('#DDN').on('change', function(event) {
var selectedName = $('#selection option:selected').val();
});
$('#submitData').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/selection",
data: {selectedDate : selectedDate, selectedName : selectedName },
success: function() {
alert('success');
}
});
});
});
</script>
<form action="/selection" method="POST">
<select class="DateDD" id="DDD" name="Dates">
<% for(var n=0; n < dateFromDB.recordset.length; n++) { %>
<option><%= dateFromDB.recordset[n].Date%></option>
<% } %>
</select>
<select class="NameDD" id="DDN" name="Names">
<% for(var n=0; n < nameFromDB.recordset.length; n++) { %>
<option><%= nameFromDB.recordset[n].Name%></option>
<% } %>
</select>
<input type="submit" name="Submit" id="submitData" class="btn btn-primary" value="View Report" />
</form>
selection.ejs
CONTAINS THE SAME THING AS INDEX.EJS (besides the script tag) AND ...
<table class="table table-bordered table-condensed table-striped">
<% for(var n=0; n < tables.recordset.length; n++) { %>
<tr>
<td><%=tables.recordset[n].Name%></td>
<td><%=tables.recordset[n].Date%></td>
....
....
</tr>
<% } %>
</table>
After form submit on index.ejs this error gets thrown:
Dates is not defined
I don't know whats causing this error, because I am able to see the name and date in the console being printed. Any help would be appreciated, thank you!
You've intercepted onsubmit event and modified the names of the data sent through ajax
$.ajax({
type: "POST",
url: "/selection",
data: {selectedDate : selectedDate, selectedName : selectedName }, // <-- here
success: function() {
alert('success');
}
});
So you're reading the wrong property in your req.body. You should instead read like:
// for date
req.body.selectedDate
// for name
req.body.selectedName
Also you claim
I am able to see the name and date in the console
The output of console you've put doesn't match the query in the code in question.
This is basic debugging question.
I can advice you to do couple of things like:
Check the browser devTools (network tab) to see if the body payload is being passed to the server.
On the server (express), are you using body parser middleware ? see more here (req.body section).
Try to run nodejs with inspect mode and attach your IDE (VSCode is a good one) and add some breakpoints. Alternatively, you can do some console.logs in order to check what are you getting from the client.
You can simulate a browser request using postman to check the server side and make sure it is working fine.
This is a simple error, so no big deal, frustrating as I know it can be.
I see you using dates, date, Date & Dates. I would look for a line number reference to give me a clue. I would use chrome and developer tools or console.log to see how far I get.
Or, I would use a different name convention like date1, date2, date3, date4 or something that is even more descriptive, so I knew for sure which date was what, then on narrowing down the error, it will be much easier to fix.

How can I add Automatic intellisense to a Textbox using Jquery

I want to add automatic Intellisense (Auto Complete--Filtering Search Result) to a textbox, corresponding to the words that I'm typing in that textbox and the Intellisense is fetched from a database table. How can I achieve this? Can anyone help?
Here is my jQuery code:
$(document).ready(function() {
$('#city').autocomplete({
source:'send.php'
});
});
send.php file given below:
$link=mysqli_connect("localhost","hari","123","hari");
$searchTerm = $_GET['query']; //get search term
$query = $db->query("SELECT fname FROM user WHERE fname LIKE
'%".$searchTerm."%' ORDER BY fname ASC"); //get matched data from user table
while ($row = $query->fetch_assoc()) {
$data[] = $row['fname'];
}
echo json_encode($data);//return json data
Corresponding HTML Code is given below:
<div class="content col-sm-12">
<form>
<h1>Hello!!!</h1>
<input type="text" id="city" name="city" size="20" class="city"
placeholder="Please Enter City or ZIP code"><br><br>
</form>
</div>
You have to include the following scripts in your html page
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
And add the following css in head of your html
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
The mistake you made is the parameter passing with the name term and trying to read with the name query in your php file. In your send.php file change the line
$searchTerm = $_GET['query'];
into
$searchTerm = $_GET['term'];
Try this:
$(document).ready(function() {
$('#city').autocomplete({
source: function( request, response ) {
$.ajax( {
url: "send.php",
dataType: "jsonp",
data: {
query: request.term
},
success: function( data ) {
response( data );
}
} );
},
});
});
I have a recommendation for you, use angular 1 for this, you can simply write that code without additional UI libraries and with much much better performance and issue-free solution.
Add the following parent div to your input element:
Change your input to this:
<input type="text" id="city" name="city" size="20" class="city" ng-model="query" ng-change="fetch()" placeholder="Please Enter City or ZIP code">
Add the following code right under your <input>:
<ul>
<li ng-repeat="text in suggestions">{{ text }}</li>
</ul>
As a basic set up, you need this in your <head> section:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
Finally you will create a new file like in assets directory like "suggestions.js" in your assets directory or somewhere and add this file right before you your </body> tag like this in your template:
<script src="assets/suggestions.js"></script>
The file will have the following lines:
var app = angular.module('myApp', []);
app.controller('suggestionsCtrl', function($scope, $http) {
$scope.suggestions = [];
$scope.query = '';
$scope.fetch = function() {
$http({method: 'POST', url: 'send.php', params: { query: $scope.query } }).
then(function(response) {
$scope.status = response.status;
$scope.suggestions = response.data;
}, function(response) {
/* SOMETHING WENT WRONG WTIH THE CALL DO SOMETHING HERE */
});
};
});
There is very simple set-up/tutorial for Angular 1 here:
https://www.w3schools.com/angular/default.asp
This is not a direct answer but believe me a more efficient answer. Angular 1 and the newer versions save a lot of time and brings performance.
And btw, autocomplete() is not a native jQuery function. Also I do not mention that you need jQuery also for Angular, but I assume it's already added in your template.

Accessing Jquery Key/Values in Python

I have a simple form and I need to access the key/value and properties of the jquery code for the form. Also when I try to create a customer in my view with request.form['stripeToken'] it gives error mentioned at end of question. I need to access following fields in Jquery script with key/value attributes:
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
Following is the code:
Jquery Code:
<form id="myForm" action="/yearly" method="POST">
<input type="hidden" id="stripeToken" name="stripeToken" />
<input type="hidden" id="stripeEmail" name="stripeEmail" />
<button id="customButton">Purchase</button>
</form>
<script type="text/javascript">
var handler = StripeCheckout.configure({
key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function (token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#myForm").submit();
}
});
$('#customButton12').on('click', function (e) {
handler.open({
name: 'Yearly',
description: 'Yearly Charge',
amount: 9500
});
e.preventDefault();
});
$(window).on('popstate', function () {
handler.close();
});
</script>
Following is the view:
#app.route('/yearly', methods=['GET', 'POST'])
def yearly_charge():
key = stripe_keys['publishable_key']
data = get_profile_data(session['auth_token'])
profile_data = data['Student']
student_id = profile_data.id
student = get_profile_data(session['auth_token'])['StudentProfile']
pkg = Package.query.filter_by(student_id=profile_data.id).first()
# customer
stripe_token = request.form['stripeToken']
email = request.form['stripeEmail']
if not pkg:
try:
customer = stripe.Customer.create(
email=email,
source=request.form['stripeToken']
)
print request.form
subscription = stripe.Subscription.create(
customer=customer.id,
plan="yearly",
)
student_id = profile_data.id
student.stripe_customer_id = customer.id
student.stripe_subscription_id = subscription.id
package = Package(
student_id=student_id,
stripe_id = customer.id,
student_email=request.form['stripeEmail'],
is_active=True,
package_type='yearly',
subscription_id=subscription.id
)
dbase.session.add(package)
dbase.session.commit()
except stripe.error.CardError as e:
# The card has been declined
body = e.json_body
err = body['error']
flash("You've successfylly subscribed for annual package.")
return redirect(url_for('new_template', key=key))
Error:
stripe.error.InvalidRequestError
InvalidRequestError: Request req_AMbjoYEtQR1d6Y: Invalid source object: must be a dictionary or a non-empty string. See API docs at https://stripe.com/docs'
It seems you are trying to implement custom button for stripe. There is an easy way instead of going to write all the code if you don't know how to communicate between python and js.
<form action='/yoururl' method='post'>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ key }}"
data-description="Your Description"
data-amount="500"
data-locale="auto"></script>
<input type="submit" value='Subscribe' class='btn' style='height:33px;width:50%;color:white;'>
</form>
<script>
document.getElementsByClassName("stripe-button-el")[0].style.display = 'none';
</script>
What actually happened in the code is it hides the default stripe button. So then any input button will work for you inside tag. You can use multiple buttons such as if you have another button you can use different price or other variables and just change the script like below:
<script>
document.getElementsByClassName("stripe-button-el")[1].style.display = 'none';
</script>
If there is a third button you can do it like:
<script>
document.getElementsByClassName("stripe-button-el")[2].style.display = 'none';
</script>

Save django forms on button click

I am currently trying to learn django. I decided to create a small app. currently I am making a form to create VoteType and Voting candidates on one page. I created a page where u can add as many candidate fields as you want, but when I click the button nothing happenes and even if I don't click the button some data is saved. I was watching this django guide on youtube. This guy is making one simple form. He added method = POST and action = '' to ... and in views he used (request.POST or None). I tried to do the similar, but as my form is a bit more complicated I got really confused.
so this is my views.py code:
def create(request):
voteTypeForm = VoteTypeForm(request.POST or None)
voteForm = VoteForm(request.POST or None)
instance = voteTypeForm.save(commit=False)
instance.pub_date = timezone.now()
instance.save()
instance2 = voteForm.save(commit=False)
instance2.save()
#print instance.pub_date
context = RequestContext(request,{
'voteTypeForm': voteTypeForm,
'voteForm': voteForm,
})
return render(request, 'Vote/create.html', context)
and this is my create.html django template:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'Vote/style.css' %}" />
<fieldset id="fieldset">
<form method = 'POST' action = ''>{%csrf_token %}
<p>{{ voteTypeForm }}</p>
</form>
<div id="placeholder">
</div>
<p>
<button type="button" name="Submit" onclick="Add();">+</button>
</p>
<input type = 'submit' value="create"/>
</fieldset>
<script type='text/javascript'>
{# document.write(code);#}
var _counter = 0;
var template = document.createTextNode('')
function appendStringAsNodes(element, html) {
var frag = document.createDocumentFragment(),
tmp = document.createElement('body'), child;
tmp.innerHTML = html;
// Append elements in a loop to a DocumentFragment, so that the browser does
// not re-render the document for each node
while (child = tmp.firstChild) {
frag.appendChild(child);
}
element.appendChild(frag); // Now, append all elements at once
frag = tmp = null;
}
function Add() {
var code = '<div id="template">' +
'<p>' +
'<fieldset id="fieldsets">' +
'<legend id="legends">Candidate No ['+ String(_counter+1) +']</legend>' +
' <form method = "POST" action = "">'+
'<input type="hidden" name="csrfmiddlewaretoken" value="{{csrf_token }}" />' +
'<p><label for="id_name">Name:</label> <input id="id_name" maxlength="50" name="name" type="text" /></p>'+
'<p><label for="id_image">Image:</label> <input id="id_image" name="image" type="file" /></p>'+
'</form>' +
' </fieldset>' +
'</p>' +
'</div>';
_counter++;
appendStringAsNodes(document.getElementById("placeholder"),code);
document.getElementById("someInput").value = _counter;
}
</script>
how do I fix this code so that my program only saves instances when I push the create button?
You still need to check that the action is a POST, and that the forms are valid, and you must redirect after a successful submission.
def create(request):
voteTypeForm = VoteTypeForm(request.POST or None)
voteForm = VoteForm(request.POST or None)
if request.method == 'POST':
# check validity separately to avoid short-cutting
vote_type_valid = voteTypeForm.is_valid()
vote_form_valid = voteForm.is_valid()
if vote_type_valid and vote_form_valid:
instance = voteTypeForm.save(commit=False)
instance.pub_date = timezone.now()
instance.save()
instance2 = voteForm.save(commit=False)
instance2.save()
return redirect('<view-you-redirect-to-on-success'>
context = RequestContext(request,{
'voteTypeForm': voteTypeForm,
'voteForm': voteForm,
})
return render(request, 'Vote/create.html', context)
The easiest way to do it is by making ajax request when you push the submit button.
Considering you have a form 'voteForm', try loading this form using django's inbuilt template as: {{voteForm.as_p}}
This will create your form for, which you have already done.
Now when you press submit button, make an ajax request with your form data in it.
The ajax request will take your data to the form and reverts back with a response which you can use to further do the processing.
A quick example for ajax request would be:
function youfunctionname()
$.ajax({
type: "POST",
url: url,
data: $("#yourformname").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
}

httr/RCurl: Login to sitecore [r]

Trying to login into a sitecore site with R to fetch html tables.
Part one, login did succeed after adding the following to the code.
EVENTVALIDATION <- as.character(sub('.*id="__EVENTVALIDATION" value="([0-9a-zA-Z+/=]*).*', '\\1', html))
Using the code example from: How to login and then download a file from aspx web pages with R
Did try other possibilities but this looks most promising)
Is it just me having problems 'deciphering' the tags structure, or are there more grave errors in this approach
library(RCurl)
Set some handy curl options:
username = 'YourUser'
password = "YourPass"
url="http://formular.sinusenergi.dk/sitecore/login"
url2="http://formular.sinusenergi.dk/viewforms.aspx"
curl = getCurlHandle()
curlSetOpt(cookiejar = 'cookies.txt', followlocation = TRUE, autoreferer = TRUE, curl = curl)
##Load the page for the first time to capture VIEWSTATE:
html <- getURL(url, curl = curl)
## Extract VIEWSTATE with a regular expression or any other tool:
viewstate <- as.character(sub('.*id="__VIEWSTATE" value="([0-9a-zA-Z+/=]*).*', '\\1', html))
EVENTVALIDATION <- as.character(sub('.*id="__EVENTVALIDATION" value="([0-9a-zA-Z+/=]*).*', '\\1', html))
Set the parameters as your username, password, VIEWSTATE, EVENTVALIDATION :
params <- list(
'Login$UserName' = username,
'Login$Password' = password,
'Login$Login' = 'Login',
'__VIEWSTATE' = viewstate,
**"__EVENTVALIDATION" = EVENTVALIDATION**
)
Log in at last:
html = postForm(url, .params = params, curl = curl)
So now I do get logged in, but grepl('Logout', html) still returns false.
So now I can get to URL2 but haven't figure out how to 'trigger. the product selector, see code below.
This dos not work:
params2 <- list(
'ddlProducts' = '83d16692-63e0-4e9c-9720-0108cfd4fd05',
'__VIEWSTATE' = viewstate,
"__EVENTVALIDATION" = EVENTVALIDATION
)
##Verify if you are logged in:
html = postForm(url2, .params = params2, curl = curl)
Returns the 'product selector code, but does not trigger, the same.
Thanks
Excerpt from site code:
<!-- language: lang-html -->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title>
</title></head>
<body>
<form method="post" action="/viewforms.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTQxMzE0MzQyMw8WAh4TVmFsaWRhdGVSZXF1ZXN0TW9kZQIBFgICAxBkZBYEAgEPZBYEAgEPEA8WBh4ORGF0YVZhbHVlRmllbGQFA0tleR4NRGF0YVRleHRGaWVsZAUFVmFsdWUeC18hRGF0YUJvdW5kZ2QQFQgMVmFsZyBwcm9kdWt0ClNQQVIgc3Ryb20WRXJodmVydiBWQVJJQUJFTCBzdHJvbQpTUE9UIHN0cm9tEkVyaHZlcnYgU1BPVCBzdHJvbQ5WQVJJQUJFTCBzdHJvbQpGQVNUIHN0cm9tEkVyaHZlcnYgRkFTVCBzdHJvbRUIAi0xJDgzZDE2NjkyLTYzZTAtNGU5Yy05NzIwLTAxMDhjZmQ0ZmQwNSRkYTdhZmNhOS1iZWVmLTQ3NDgtODhhNC0wNWQ1MTQ4NDBmZGMkYjg0ZjFiNjMtMDVkZi00MjFjLWFlNGQtMTdjYWZkY2ZmZjc0JGNhNmYxYmQwLTBlYjEtNDExOC1hYmY4LTdlZmFmYTRmNTI2YyQ2NTY2YzgyZS1mNjcyLTQwZGYtOGJkYS1hYjAzOTI3YzdiOGQkN2E3YTVmY2ItMDFkNi00Mzg1LTgwZDUtZjY4MTY5ZmI2NGJmJGY5N2FmNWI1LTAxZDYtNGU4NC1iZjUwLWZhZDU1ZTJmZDU4NxQrAwhnZ2dnZ2dnZxYBZmQCAw88KwARAQwUKwAAZAIDDw8WAh4HVmlzaWJsZWhkZBgBBQ5ndlByb2R1Y3RzRm9ybQ9nZApFHGp6DkfeGiiy/DYgq3lHp9Aq7IMgedEE3Ce3QI0m" />
</div>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAl0n//hvd...A==" />
</div>
<div>
<div id="pForm">
<select name="ddlProducts" id="ddlProducts">
<option selected="selected" value="-1">Valg produkt</option>
<option value="83d16692-63e0-4e9c-9720-0108cfd4fd05">SPAR strom</option>
<option value="da7afca9-beef-4748-88a4-05d514840fdc">Erhverv VARIABEL strom</option>
<option value="b84f1b63-05df-421c-ae4d-17cafdcfff74">SPOT strom</option>
<option value="ca6f1bd0-0eb1-4118-abf8-7efafa4f526c">Erhverv SPOT strom</option>
<option value="6566c82e-f672-40df-8bda-ab03927c7b8d">VARIABEL strom</option>
<option value="7a7a5fcb-01d6-4385-80d5-f68169fb64bf">FAST strom</option>
<option value="f97af5b5-01d6-4e84-bf50-fad55e2fd587">Erhverv FAST strom</option>
</select>
<div>
</div>
<span id="lbResult"></span>
</div>
</div>
</form>
</body>
</html>
Solved the last part:
Needed to include: __EVENTTARGET' and the choice for the eventarget variable.
Så the final 'params' list have the following structure.
'__VIEWSTATE' = viewstate,
'__EVENTVALIDATION' = EVENTVALIDATION,
'__EVENTTARGET' = "ddlProducts",
'ddlProducts' = x[1]
Automating the admin screens of the CMS is not an easy task, and unless it is something but the very rudimentary it is likely to break in the future as content changes.
You should look into the Sitecore Item Web API instead, which will allow you to access and manipulate Sitecore conent items via a REST API returning data in JSON format. You can also apply security to restrict access and the calls can be made either from client side or from server side C# code.
Sitecore Item Web API Client Library
Content-As-A-Service and the Sitecore Item Web API
SitecoreJunkie: Sitecore Item Web API
There is also a great walkthrough by Mike Reynolds in this Youtube video.
Example usage:
var query = new SitecoreExpressionQuery(SitecoreQueryType.Read);
query.Query = "/sitecore/content/Home/*";
var credentials = new SitecoreCredentials();
credentials.UserName = "extranet\\foo";
credentials.Password = "bar";
credentials.EncryptHeaders = true;
var context = new AuthenticatedSitecoreDataContext("host", credentials);
ISitecoreWebResponse response = context.GetResponse(query);
if (response.StatusCode == HttpStatusCode.OK)
{
foreach (WebApiItem item in response.Result.Items)
{
// the Key property of the KeyValuePair holds the field id
foreach (KeyValuePair<string, WebApiField> field in item.Fields)
{
Console.WriteLine("fieldid: " + field.Key);
Console.WriteLine("fieldname: " + field.Value.Name);
Console.WriteLine("fieldtype: " + field.Value.Type);
Console.WriteLine("fieldvalue: " + field.Value.Value);
}
}
}

Categories