JavaScript searching for a user based on their username? - javascript

I've created a function that uses getJSON to retrieve a data set found on an API website of registered Github Users
<!DOCTYPE html>
<!---->
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function(){
var user = $('#search').val();
$.getJSON("https://api.github.com/users/" + user)
.done(function(data) {
var br = "<br>";
var p = $("<p id='users'></p>");
var name = "Username: "+ user.login + br;
var pic = "Avatar Picture:" + br + "<img src='"+user.avatar_url+"'/>" +br;
var homeURl = "Homepage URL: "+"<a href='"+user.html_url+"'>"+user.html_url+"</a>" +br;
var location = "Location: "+"Null" +br;
var admin = "Admin: "+user.site_admin;
p.append("<p>"+ name + pic + homeURl + location + admin +"</p>");
$("#results").empty().append(p);
})
.fail(function(jqXHR) {
console.log("Error: " + jqXHR.status);
})
.always(function() {
console.log("Random Users Request finished");
});
});
</script>
</head>
<body>
<input id="search" type = "text">
<button>Search</button>
<div id="results"></div>
</body>
</html>
As you can tell I have began to modify it so that instead of displaying all users it only displayers the user that has been searched
var user = $('#search').val();
$.getJSON("https://api.github.com/users/" + user)
This snippet of code grabes the username entered in the text area and passes it to the getJSON method in the Url. An example URL is "https://api.github.com/users/mojombo", thus if the user enters "mojombo" then their profile would appear
This function is accessed via a button
<input id="search" type = "text">
<button>Search</button>
However when you search for the example user, in fact any user no data is displayed and a blank screen remains

You have not connected your function to the button.
As it stands, it runs before the user has typed anything into the search field (thus requesting "https://api.github.com/users/" because user at that time is an empty string) , and won't react at all to a button click.
Instead of just
$(function(){
/* code */
});
do
$(function(){
$('button').on('click', function(){
/* code that runs when button is clicked */
})
});

Related

printing the contents of list in java

Trying write javascript that prints "username=john01" and "password=password123" from the url below. Currently it prints nothing...
index.html?username=john01&password=password123&lt=_c1F9F2B16-96B3-9D7B-CC19-D22A43D4FCA1_kA54D6D0E-881B-2792-22D3-B857150B1EFC&_eventId=submit&submit=Sign+In
<html>
<body>
<p> This code is for educational purposes only, and is not to be used with malicious intent. </p>
<script>
string = window.location.search;
content = string.split("");
usernameStart = 1;
usernameEnd = content.indexOf("&",0);
username = content.substring(usernameStart,usernameEnd));
document.write("Your username is " + username);
</script>
</body>
</html>
var url = 'index.html?username=john01&password=password123&lt=_c1F9F2B16-96B3-9D7B-CC19-D22A43D4FCA1_kA54D6D0E';
var username = url.match(/username=([^&]*)/)[1];
var password = url.match(/password=([^&]*)/)[1];
document.getElementById('userinfo').innerHTML = 'Your username is ' + username + '<br/>And your password is ' + password;
You can try it directly on my JSFiddle
If you replace 'url' with 'window.location' and remove the first line, it should work from the url.

Spotify Api Results Ajax

In the image I have the code to display only the first element ( song, image , artist, etc ... ) .
I would like to know how to make it show me :
When a user clicks on that button, show a new modal with all the
results of the tracks search you performed previously.
When a user clicks on one of the track names, update the player with
that track's information, including its audio.
The button is already created.
$('#song_btn').on('click', function Search_Song (event) {
event.preventDefault();
var song = $('#song_input').val();
var request = $.get('https://api.spotify.com/v1/search?q=' + song +'&type=track');
function Data_Songs (song) {
var track = song.tracks.items[0];
$('.song_title').text(track.name);
$('.artist_name').text(track.artists[0].name);
var cover = '<img src="' + track.album.images[0].url + '">';
$('.cover_image').html(cover);
var audio = '<audio class="js-player" src="' + track.preview_url + '">';
$('.audio').html(audio);
var more_results = '<br/><button type="submit" class="btn btn-primary" id="more_btn">Ver más Resultados</button>';
$('.more_result').html(more_results);
};
function handle_Error () {
console.error('¡¡ Ha Fallado !!');
}
request.done(Data_Songs);
request.fail(handle_Error);
});
So it seems like you have button to trigger the event...Here are your next steps:
Take an input (through a text field for example) and search for it through the API.
Next, obtain the parsed JSON from the API.
Then you'll be able to do what you are doing in your Data_Songs function...
Here's my implementation:
$('#song_btn').on('click', function(){
var BASE_URL = 'https://api.spotify.com/v1/'
var QUERY = $('#search_field').val(); // This is the value of your text field
var spotify_json = $.get(BASE_URL + 'search?type=track&query=' + QUERY, function(data){
console.log(data.tracks); // Do whatever you want with them after here!
// Ex. alert(data.tracks[0].href);
})
})
Note that I used a success handler on the $.get() method, which is a little different from your code.
To use your Data_Songs function in the $.get() function,
var spotify_json = $.get(BASE_URL + 'search?type=track&query=' + QUERY, Data_Songs(data));

Navigating to HTML page within javascript

I have this survey that stores to local storage. The user is prompted 'are you sure' once clicking submit. I'm trying to navigate to a confirmation HTML page(Confirmation.html) in my directory after user clicks 'ok' . But I'm not able to achieve both storing values and navigating to work. Can get any one only, it seems. Any help would be appreciated.
function clicked() {
if (confirm('Are you sure you want to submit? You will not be able to go back.')) {
form.submit();
} else {
return false;
}
}
$('form').submit(function () {
var person = $("#FirstName").val() + "." + $('#LastName').val();
$('input, select, textarea').each(function () {
var value = $(this).val(),
name = $(this).attr('name');
localStorage[person + "." + name] = value;
window.location.href = "Confirmation.html";
console.log('stored key: ' + name + ' stored value: ' + value);
});
});
<button type="submit" value="Save" id="Save" onclick="clicked();" >Submit Form</button>
If the above does not show my problem, here is the whole in jsfiddle
try this
<script>
$( document ).ready(function() {
$('#Save').click(function (e) {
if (confirm('Are you sure you want to submit? You will not be able to go back.')) {
var person = $("#FirstName").val() + "." + $('#LastName').val();
$('input, select, textarea').each(function () {
var value = $(this).val(),
name = $(this).attr('name');
localStorage[person + "." + name] = value;
window.location.href = "Confirmation.html";
console.log('stored key: ' + name + ' stored value: ' + value);
});
}
});
});
</script>
and remove onclick="clicked();" from button.
I am not sure why you need the confirmation.html page. Consider my opinions as follows:
1st: you are already asking the user for the confirmation giving him a messagebox. Thereafter you should only submit the form data (after any additional validation) to a server-side page (which I believe you have mentioned in the action value of the form).
2nd: If you still need the confirmation.html page then you should redirect to confirmation.html from that server-side page but not from your form page(the current page). Now it depends on the usage of confirmation.html that you should redirect to confirmation.html before/after feeding the form data into the database(or doing something else).

PHP backend in Spotify App not working

I'm trying to make a spotify app that takes in user information and sends it to an SQL database. However, I don't want this to be done using ajax since I want the submission of the information to move the user to a new page while the information is posted to the database in the background.
Here's my code so far:
function complete2() {
var name = document.getElementById("inputname").value;
var form = '<form action="http://site.net/dbconnect.php" method="post" style="display:none">' + '<input type="text" name="name" value="' + name + '">' + '</form>';
$('body').append(form);
$(form).submit();
}
</script>
</head>
<body>
<form id = "submitform" name = "submitform" action = "index.html" method = "POST" onsubmit = "complete2();" >
Name: <input type = "text" id = "inputname"> <br>
<input type = "submit" value = "Create">
</form>
</body>
</html>
So i know you dont want to use AJAX but if you want to load a differnt html file in your local app and Spotify doesnt respect a location header to an internal resource then youre stuck with ajax. However you can make it simialr to what would happen with a standard post something like:
$(function(){
$('#submitform').submit(function(e){
e.preventDefault();
$.post(
$(this).attr('action'),
{'inputname': $(this).find('#inputname').val()},
function(){ window.location.href = 'sp://yourapp/nextpage.html'; }
);
});
});
Here is a sample to get data
$.getJSON("http://www.exx.com/getjsondata.php", function (data) {
parsetheresponse(data) ;
}
Here is a sample to post data (still in JSON)
$.post("http://www.exx.com/postdataspotify.php", { albumname: "test", username: "test2" });
Hope it will help.
Don't forget to put http://www.exx.com in manifest file.

Tracking values using JavaScript

on page A
test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session"));
Response.Redirect("EnterSession.aspx?session=" + e.CommandArgument.ToString());
on page B
_gaq.push(['pageTrackerTime._trackEvent', 'category', 'action', document.location.href, roundleaveSiteEnd]);
when a user clicks a button on page A , he will be directed to page B and there I used document.location.href to track the current URL. now I would like to track as well session_name from page A using JavaScript.
how can I do this
the original code was like this
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "SELECT * FROM Tmyapp_Session;";
SqlDataReader thisReader = thisCommand.ExecuteReader();
while (thisReader.Read())
{
test.Controls.Add(GetLabel(thisReader["session_id"].ToString(), thisReader["session_name"].ToString()));
string[] compare = secondResult.Split(';');
foreach (string word in compare)
{
if (word == thisReader["session_id"].ToString())
{
test.Controls.Add(GetButton(thisReader["session_id"].ToString(), "Join Session"));
I had to change the last code to
test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session"));
session_id to session_name
because i want to url to have the value of the session_name
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
// include getCookie and setCookie functions here
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
var username = getCookie("username");
if (username != null) { // registered user
document.writeln("Welcome back " +
username + ".");
var visits = getCookie("visits");
document.writeln(" You have been here " +
visits + " time(s) before.");
setCookie("visits",parseInt(visits)+1);
}
else { // new user
var username = prompt("What is your name ?","");
if (username != null) {
setCookie("username",username);
setCookie("visits",1);
document.writeln("Thank you. Please reload this page.");
}
}
</SCRIPT>
</BODY>
</HTML>
Hope this will work !!!
Looks like you just need to get the session_name from the querystring. Check out this post here, it has a couple of nice solutions for doing that.
I see two ways of accomplishing what you want, you could add another querystring
/url.aspx?session_name=[session_name]&session_id=[session_id]
or in a session variable
session["session_id"] = session_id;

Categories

Resources