I'm trying to learn Javascript, and I need help with this question that i have been pondering on for a while now.
I need help with writing a script that prompts for the abbreviation of a New England state and alerts the capital of that state. For example if your user inputs NH, your script should alert Concord.
Only using the most simple JavaScript:
var capitals = { ME: "Augusta", NH: "Concord", VT: "Montpelier", MA: "Boston", CT: "Hartford", RI: "Providence" };
var abb = prompt('Abbreviation?');
alert(capitals[abb]);
There are a couple ways you could do this: if you want to use javascript exclusively, you have two options:
Store the associated values in a javascript object
var capitals = {AL:"Montgomery",AK:"uhhh..alaska's capital",...};
and then your function might look like this:
function GetCapitalFor(abbr){
alert(capitals[abbr]);
}
Use a third party library
I don't know of one in particular, but I'm sure one exists.
If you are also working with a server, you could store the pairs in a database and then run the function on the server (probably using AJAX). Something like this:
$.ajax({
type:"POST",
data: {abbreviation: abbr}, //where abbr is the user's input (MAKE SURE TO SANITIZE)
success: function(result)
{ alert(result);}
});
and on the server side, you'll query a database table for the abbreviation.
For something as trivial as this though, I'd probably just go with option 1.
Related
I'm working on tincan JavaScript API. The issue my data format is total change and TinCan have specified a why to pass data along with call. Help me to adjust my data in TinCan Api format. Here is sample data one of my call.
var data = {
"groupId": "groupId",
"groupName": "gNameEncrypt",
"tutorNames": "tutorNames",
"actorNames": "actorNames",
"otherNames": "otherNames"
};
Current what i do i simply decode this data and send it like this.
var actionList = new TinCan(
{
recordStores: [{
endpoint: "http://example.com",
username: username,
password: password,
allowFail: false
}]
});
var action = new TinCan.Agent({
"name": "insert"
});
actionList.getStatements({
'params': {
'agent': action,
'verb': {
'id': $.base64.encode(data)
}
},
'callback': function (err, data) {
console.info(data.more);
var urlref = "http://<?php echo $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . $uriParts[0] . "?" ?>t=" + data.more.TutorToken;
window.location.href = urlref;
}
});
crypt.finish();
});
There are really two parts here:
need to get data into an xAPI (formerly Tin Can) format, and
the code itself.
In depth,
I think you need to take another look at how xAPI is used in general. Data is stored a JSON "Statement" object that has 3 required properties and various other optional ones. These properties often contain complex objects that are very extensible. It is hard to tell from what you've shown what you are really trying to capture and what the best approach would be. I suggest reading some material about the xAPI statement format. http://experienceapi.com/statements-101/ is a good starting point, and to get at least some coverage of all the possibilities continue with http://experienceapi.com/statements/ .
The code you've listed is attempting to get already stored statements based on two parameters rather than trying to store a statement. The two parameters being "agent" and "verb". In this case We can't tell what the verb is supposed to be since we don't know what data contains, I suspect this isn't going to make sense as a verb which is intended to be the action of a statement. Having said that the fact that the "actor" has a value of action is questionable, as that really sounds more like what a "verb" should contain. Getting the statements right as part of #1 should make obvious how you would retrieve those statements. As far as storing those statements, if you're using the TinCan interface object you would need to use the sendStatement method of that object. But this interface is no longer recommended, the recommended practice is to construct a TinCan.LRS object and interact directly with it, in which case you'd be using the saveStatement method.
I would recommend looking at the "Basic Usage" section of the project home page here: http://rusticisoftware.github.io/TinCanJS/ for more specifics look at the API doc: http://rusticisoftware.github.io/TinCanJS/doc/api/latest/
Can't seem to figure out a way to disable filtering with typeahead. Basically I just need the autocomplete (or rather drop-down search hint) functionality of it. I am doing a zip code search and resulting postal codes don't necessarily match the queried ones. How do I make it show all matches without doing extra filtering on those again?
Below is the code I have:
var dealers = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/form/find-dealer?postalCode=',
prepare: function (query, settings) {
settings.url += encodeURIComponent(query);
settings.type = 'POST';
settings.contentType = "application/json; charset=UTF-8";
return settings;
}
}
});
$('input[name=postalCode]').typeahead({
minLength: 3
}, {
name: 'dealers',
display: function (data) {
return data.title;
},
source: dealers.ttAdapter()
});
Note: I know it seems a bit awkward to do a zip code search that way, but the purpose of the designer was for users to search interchangeably by dealer name and zip code.
Additional Info: typeahead.bundle.js - v0.11.1
It seems showing all without any (matching) query isn't possible:
https://github.com/twitter/typeahead.js/issues/1308
Though some are trying it with minlength=0 like this:
https://github.com/twitter/typeahead.js/issues/1251
And it looks it was possible in an older version:
https://github.com/twitter/typeahead.js/pull/719
Btw the plugin is no longer being developed and the manual is incomplete. An improved one can be found at this fork: https://github.com/corejavascript/typeahead.js/tree/master/doc
Having said that, you may be better off with another autosuggest, or a plugin like select2, which does show results by default and can use external sources.
If you want send a query to AJAX & get data from your database & add all JSON result for result of typehead (You have a data filter with database & send clean data with AJAX & JSON, But type head has extra filtering & don't show anything or some of your data), You must do it :
Open bootstrap-typeahead.js & find
item.toLowerCase().indexOf(this.query.toLowerCase())
And replace it to :
item.toLowerCase().indexOf(item.toLowerCase())
Will you can show all results from Ajax JSON ...
Not pretty, since the library has been forked and no longer oficially supported by the creator, but this fix did it for me https://github.com/twitter/typeahead.js/pull/1212 . Basically when in remote mode, it returns all matches, which is actually the proper behavior as I see it.
This SO thread helped twitter typeahead ajax results not all shown
I am having an issue with jQuery autocomplete. Basically I have a search bar, and when you type in what you're looking for the jQuery code I have calls a php script which does a MySQL query and returns everything I need and fills in the text boxes accordingly. What I then want to do is take the value I receive from that autocomplete, and use it in another autocomplete to fill in more data. The tricky part is that the data I need to get with the 2nd query is located in a different table than the first query, which share a relationship. My question is do I need a completely separate function to do this, or can I simply put both queries in the 1 php script and have the information from the first query be used for my 2nd query.
Any help is appreciated thanks!
Here is the jQuery function:
$(function() {
/* $('#abbrev').val("");
*/
$("#q16_location16").autocomplete({
source: "location_query.php",
minLength: 1,
select: function(event, ui) {
$('#q16_location161').val(ui.item.LocationID);
$('#SystemName').val(ui.item.SystemName);
$('#SiteAddress1').val(ui.item.SiteAddress1);
$('#SiteAddress2').val(ui.item.SiteAddress2);
$('#SiteCPP').val(ui.item.SiteCPP);
$('#Contact').val(ui.item.Contact);
$('#SiteLocationHours').val(ui.item.SiteLocationHours);
}
});
});
and the php script:
/* If connection to database, run sql statement. */
if ($conn)
{
$fetch = mysql_query("
SELECT Location.LocationID,
Location.SystemName,
Location.SiteAddress1,
Location.SiteAddress2,
CONCAT_WS(' ', Location.SiteCity, Location.SiteProvince, Location.SitePostalCode) AS SiteCPP,
CONCAT_WS(' ', Location.ContactName, Location.ContactPhone, Location.ContactEmail) AS Contact,
Location.SiteLocationHours,
CONCAT_WS(' ', SystemName, SiteNameLocation, SiteAddress1, SiteCity, SiteProvince, SitePostalCode) as expr2
FROM Location
WHERE Location.SystemName like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteNameLocation like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteAddress1 like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteCity like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteProvince like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SitePostalCode like '%".mysql_real_escape_string($_GET['term'])."% '
LIMIT 0,15");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['LocationID'] = $row['LocationID'];
$row_array['value'] = $row['expr2'];
$row_array['SystemName'] = $row['SystemName'];
$row_array['SiteAddress1'] = $row['SiteAddress1'];
$row_array['SiteAddress2'] = $row['SiteAddress2'];
$row_array['SiteCPP'] = $row['SiteCPP'];
$row_array['Contact'] = $row['Contact'];
$row_array['SiteLocationHours'] = $row['SiteLocationHours'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr, $return_arr2);
So when the user types in "New York" they can can select that option. In my example New York has an ID of 5. I also have a query that selects different streets in new york but this is in a separate table. in my streets table however, there is a "LocationID" column that for every street in new york will have a value of 5. So I want to take that ID of 5 when a user enters in new york and generate all the streets from a different table which also have that ID. I have tried multiple things in terms of creating a new function but I am just unsure of how I would pass that ID to the function.
Thanks
You can use one PHP script for this. Here's about what I'd think the basic structure will look like:
Pass two values to "location_query.php". The first value would be the name of the table that you want to query. The second value could be the selection result from the auto-complete text box.
Create a prepared statement in "location_query.php" from the two values that were passed to "location_query.php".
Perform your query.
JSON encode the result (just like you did before).
I'd also like to point out a security concern with your code. You should be using Mysqli and prepared statements instead of PHP's MySQL and mysql_real_escape_string. mysql_real_escape_string has been shown to have security deficiencies that can lead to security breaches and PHP's MySQL class has been deprecated. Mysqli and Prepared statements are much safer, and, in my opinion, provide for cleaner code since it allows for the separation of the SQL and the parameters.
Hope this helps!
EDIT: I think I understand what you're trying to do now, but I think there's a better way to go about doing it. Instead of assigning the id value to a hidden field and trying to have jquery detect every time that field is changed, I would just do the following:
For your first text box's select method:
select:function(event, ui) {
$.get("location_query.php", {
searchterm:$(ui).val()
}, yourFunction);
}
Here's an example implementation of "queryFinished":
function queryFinished(data, textStatus, jqXHR) {
var mJSON = $.parseJSON(data);
/* mJSON is the parsed JSON data returned from your "location_query.php"
script.*/
//TODO the rest of your code
}
Here's what's going on:
We define a custom function to be called when the first text box has a new item selected. This functions only purpose is to call a GET on "location_query.php".
Then, we pass the value of the selected field from the first text box via our GET call.
We then create a function to be called when GET returns.
Finally, we parse the encoded JSON that is returned by "location_query.php". After that, you can perform whatever tasks you need with the parsed JSON (mJSON in our example).
Taking this approach keeps us from having to worry about "listening" for a value change in our hidden ID field and makes everything nice and clean.
So thanks to SO I can pass an object from node to the client, but then getting it into a knockout view model is a bit awkward. These are the steps I have so far (I've included links to the relevant lines as they appear in my github project. Thought the context might help.):
Apply JSON.stringify and pass to the jade file
recipeJSON: JSON.stringify(recipe);
Wrap this in a function in a header script that just parses the JSON and returns the result
script
function getRecipeObject() {
var r = '!{recipeJSON}';
return JSON.parse(r);
}
Call this function and pass the result to a view model constructor
self.recipe = ko.observable(new Recipe(getRecipeObject()));
This works but is there a better way?
Question clarification (Edit): I feel step 2 shouldn't be necessary. Is there a way to directly pass the JSON from node to the Recipe() constructor, without the getRecipeObject() acting as an intermediate step? I tried passing recipeJSON in directly like so
self.recipe = ko.observable(JSON.parse('!{recipeJSON}'));
That doesn't work I think because its not a jade template and has no access to the variable.
According to the answer to this question rendering data into scripts is bad practice and I should instead make an XHR call on page load instead.
Edit
I just saw you linked a github repo! So you're already familiar with most of this...you even have an endpoint set up at /recipe/:id/view, so now I'm really confused...what isn't working out for you? Just the last step of deserialization using ko.utils.*?
Sorry about all the exposition -- I thought this was way more rudimentary than it actually was; I hope no offense taken there!
You really don't want to return a script to execute -- instead, treat this as a DTO: an object that just stores data (no behaviors). An example would be:
{
recipeID: 12,
reviewIDs: [42, 12, 55, 31],
rating: 4.2
recipeName: "A super tasty pie!"
}
This object (representation) is a projection -- a simplified version of the full data stored in the database.
The next step is to create an endpoint to access that data on the server. Let's assume you're using Express:
var app = express();
app.get('/recipes/:recipeID', function(req, res) {
var recipeID = req.params.recipeID;
// It would be cool if this existed, huh?
getRecipeAsync(recipeID, function(recipe) {
res.status(200).json(recipe);
});
});
If you send a GET request to your (hypothetical) application (let's say it's https://localhost:8080/recipes/12), you'll get json representing the (admittedly imaginary) recipe with ID 12.
You can accomplish getting the JSON with jQuery (or any other library that makes XHR nice and pretty)
var recipeID = 12;
$.ajax({
url: "/recipes/" + recipeID,
type: "GET"
}).then(function(recipe) {
console.log("Hey! I got the recipe: %O", recipe);
// Note: you might need to use ko.utils.fromJS(recipe) if the returned
// data is JSON that ISN'T deserialized into an object
var recipeObservable = ko.utils.fromJS(recipe);
});
That's about everything you need to know. Obviously, the devil's in the details, but that's basic idea; let me know if that helps!
Im using foursquare API in a web app, and I have the call to foursquare and the results dead on, but I can't parse it out in the way that I want. I don't want to use a 3rd party parser because those have confused me thoroughly. I want the app to alert out a list of clickable venue names, by distance, and when clicked a variable is assigned to the lat and lng of that venue.
$(document).ready(function(){
$.getJSON("https://api.foursquare.com/v2/venues/search?ll=-27.58818,-48.523248&
client_id=9&client_secret=9&v=20111107",
function(data){
//code here
});
});
The results look like this:
{"meta":
{"code":200},
"response":
{"venues":
[{"id":"4c158143a1010f47a1364e18",
"name":"Parma Pizza",
"contact":{"phone":"+554832346363","formattedPhone":"+55 48 3234-6363"},
"location":{"address":"R. Lauro Linhares, 1052",
"lat":-27.588341,
"lng":48.5232834,
"distance":18,
So far ive tried 3rd party Jackson with fail, alerting out names with fail, document.write with fail, and some type of .$each remover which also failed. Please help I am so stuck.
jQuery is already parsing your JSON file with $.getJSON. Unless you're using an old browser you don't need a 3rd party JSON parsing library. (Although you should include JSON3.js in your code base just in case someone trying to use your site is in an old browser. Just include it. You don't need to do anything else other than that.)
The data variable being passed into the callback function is a JavaScript object. You can then just do data.meta.code to get the value of code (200), or data.response[0].name to return Parma Pizza.
As for generating your list you're going to have to do the hard work. You can use $.each to iterate though the places easily though:
$.getJSON("https://api.foursquare.com/v2/venues/search?ll=-27.58818,-48.523248&client_id=9&client_secret=9&v=20111107", function(data){
$.each(data.response, function(index, elm){
console.log(elm.name);
});
});
Will print out a list of all the venue names returned from your query.
# Celeste
I think you can fix it by adding .venues in the code from tkone.
Atleast this worked for me.
$.getJSON("https://api.foursquare.com/v2/venues/search?ll=-27.58818,-48.523248&client_id=9&client_secret=9&v=20111107", function(data){
$.each(data.response.venues, function(index, elm){
console.log(elm.name);
});
Sorry for not commenting on tkone's answer, but I don't have reputation enough to comment :/ strange system ....