this is my first time here so i hope i don't break any rules.
I have a Jquery code that retrieves info from an API that is written from a .net controller. Retrieving the infomration from the API works well, but now that i have to make the user sign in to view the API(Json), it of course stopped working in jquery. Is there anyway i can let the Jquery code "sign in" so it can retrieve data from that API while it's protected with password (authorize)?
Thanks
UPDATE
here is the Jquery Code
$(document).ready(function () {
var showData = $('#show-data');
$.getJSON('url/here', function (data) {
console.log(data);
var items = data.map(function (item) {
return item.id + ': ' + item.firstName + ': ' + item.lastName;
});
showData.empty();
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
});
});
Related
I currently have a Rails application that uses Turbolinks. In this app, I am trying to track the amount of time spent on a specific view. I have looked at countless questions and gone through multiple variations of called window.onbeforeunload, window.beforeunload, window.on('beforeunload')... My current attempt is this:
$(document).ready(function() {
var start = Date.now();
var id = gon.subjId;
var rand_index = gon.randIndex;
var index = gon.index;
console.log('showing article ' + index + ' at index ' + rand_index + ' for ' + id);
$(document).on('turbolinks:before-change', function() {
$.post('/log', {subj_id: id, article: {index: index, rand_index: rand_index, time_spent: Date.now()-start}},
function(response) {
});
})
});
I know that the function using the AJAX request works; however, it is not called. How can I get this function to call when the back button is pressed?
I'm still not sure what the underlying error was but I changed the script to this and works like a charm:
$(document).ready(function() {
var start = Date.now();
var id = gon.subjId;
var rand_index = gon.randIndex;
var index = gon.index;
console.log('showing article ' + index + ' at index ' + rand_index + ' for ' + id);
function logVisit() {
console.log('logging visit');
$.post('/log', {subj_id: id, article: {index: index, rand_index: rand_index, time_spent: Date.now()-start}},
function(response) {
});
document.removeEventListener('turbolinks:before-cache', logVisit);
}
document.addEventListener('turbolinks:before-cache', logVisit);
});
I'm trying to display more info of the museum when a museum name is clicked fro the option dropdown box. I am getting my data from a json array. I was able to populate the option box with the name of the museum but could not display more details. Could anyone please help me with this. I'm using jquery for this code.
function getMuseums() {
var museumSelect = $("<select id=\"museumlist\" name=\"museumlist\" onChange=\"getMuseumInfo()\" />");
var info = $("<span>Select Museum: </span>")
$.get("museums.php",function(data,status) {
var response = '';
var json = $.parseJSON(data);
museums = json.museums;
$.each(museums, function (index, item) {
$('<option />').attr({"value" : index}).text(item.museum_name).appendTo(museumSelect);
/*response += "<option value='"+index+"'>" + item.museum_name + "</option>";
$("#museumlist").html(response);*/
});
$('#content').empty().append(info, museumSelect);
$("<div id=\"museumDetails\" />").appendTo("#MuseumDiv");
getMuseumInfo()
});
}
function getMuseumInfo() {
var museum_id = $("#museumlist").val();
selectedMuseumid = museum_id;
$("#MuseumDiv").empty().append("<div id=\"museumDetails\"/>");
var url = "museums.php?museum_id=" +escape(museum_id);
$.get(url,function(data,status) {
var json = $.parseJSON(data);
museums = json.museums;
var museum_name = museums.museum_name;
var museum_description = museums.museum_description;
var museumInfo = "<h3>" + museum_name + "</h3><p>" + museum_description + "</p>";
$("#museumDetails").empty().append(museumInfo);
});
}
You can pass option value to your function as a parameter getMuseumInfo(this.value):
var museumSelect = $("<select id=\"museumlist\" name=\"museumlist\" onChange=\"getMuseumInfo(this.value)\" />");
And than you can use iterate through museums and check if index is the same as option value, and then print only properties for that item.
$.each(museums, function(index, item) {
if (index == id) {
var museumInfo = "<h3>" + item.museum_name + "</h3><p>" + item.museum_description + "</p>";
$("#MuseumDiv").empty().append(museumInfo);
}
});
But better check working code (also turn on console in app):
codePen
NOTE:
I make example of request to create JSON data. I make get request to url:
https://api.myjson.com/bins/58j10
I've begun playing around with SignalR, of course starting with the initial chat hub that I suppose everybody does at one point or another. I want to modify it so that if the user types in HTML in their message, when it gets displayed it shows rendered HTML as oppose to just the string with HTML tags in it.
Here is my javascript:
<script type="text/javascript">
$(function () {
var chat = $.connection.chatHub;
chat.client.broadcastMessage = function (name, message) {
var encodedName = $('<div />').text(name).html();
var encodedMesg = $('<div />').text(message).html();
if (message === "joined session") {
$('#discussion').append('<li><strong>' + encodedName + ' ' + encodedMesg + '</strong></li>');
} else {
$('#discussion').append('<li><strong>' + encodedName + '</strong>:  ' + encodedMesg + '</li>');
}
};
$('#message').focus();
$.connection.hub.start().done(function () {
chat.server.send("#FullName", "joined session");
$('#sendmessage').click(function () {
chat.server.send("#FullName", $('#message').val());
$('#message').val("").focus();
});
});
});
The encodedMesg has "this is <b>bold</b>", but instead of rendering it as HTML, it just shows it as a string. How can I allow this to render as HTML?
I've tried encoding the < as < and > as > but that didn;t work. I also tried %3C and %3E but they didn;t work either.
Calling .text changes the text of an object and intentionally prevents html or scripts from being parsed.
You can get it to parse it by changing the value with .html
var encodedMesg = $('<div />').html(message);
use this:
var encodedMsg = $('').text(message).html();
I use WinJS in my application and try to print some content. Made my printer class according to this tutorial https://dzone.com/articles/windows-8-print-contract-%E2%80%93.
function registerForPrintContract(participiantData) {
var printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
printManager.addEventListener("printtaskrequested", onPrintTaskRequested, false);
}
function onPrintTaskRequested(printEvent) {
var printTask = printEvent.request.createPrintTask("Print Example", function (args) {
printCurrentPage(args);
printTask.oncompleted = onPrintTaskCompleted;
});
}
function printCurrentPage(args) {
var docHtml = document.createDocumentFragment();
docHtml.appendChild(createDocumentContent());
args.setSource(MSApp.getHtmlPrintDocumentSource(docHtml));
}
function createDocumentContent() {
var container = document.createElement("div");
container.innerHTML = "<h2>" + firstname + " " + lastname + "</h2>" +
"<h4>" + emailaddress1 + "<h4>";
return container;
}
function showPrintUI() {
Windows.Graphics.Printing.PrintManager.showPrintUIAsync();
}
My problem is that I do not know how to forward some object data to createDocumentContent() function. In this example I put firstname, lastname and email. Those data I cannot get from html page I need to send them on print button click.
All examples I saw are about printing current page or making new content from data which we can get from HTML page by querying DOM, no example where I can send custom object.
What is the best way to do this ?
My problem is that I do not know how to forward some object data to createDocumentContent() function. In this example I put firstname, lastname and email. Those data I cannot get from html page I need to send them on print button click.
Do you mean you want to put the html output of "<h2>"+firstname + " " +lastname+"</h2>"+"<h4>" + emailaddress1 + "<h4>" to your print page?
The behavior of innerHTML has changed in Windows Store App Development.
see HTML and DOM API changes list innerHTML section:
Content is filtered as through it was processed by the toStaticHTML method
But WinJS offers a method that you can utilize to inject HTML.
Here is the link to documentation of this method: WinJS.Utilities.insertAdjacentHTML
Here is a code snippet that shows a simple use this method:
function createDocumentContent() {
var obj = {
firstname: "winffee",
lastname: "xia",
emailaddress1:"test#126.com"
}
var htmlString = "<h2>" + obj.firstname + " " + obj.lastname + "</h2>" +
"<h4>" + obj.emailaddress1 + "<h4>";
var container = document.createElement("div");
WinJS.Utilities.insertAdjacentHTML(container, "beforeend", htmlString);
return container;
}
Lets say I have a angular view which gets populated from the service:
$http.get("" + window.ENDPOINT + "/main_things/" + $scope.mainThingId + ".json").success(function(data) {
return $scope.main_thing = data;
});
Let's say I want to load another bit of information to my page, but the other bit is utilizing some slow external services, so I want to load it asynchronously:
$http.get("" + window.ENDPOINT + "/secondary_things/" + $scope.parentMainThingId + ".json").success(function(data) {
return $scope.secondary_thing = data;
});
How can I structure my code in the angular controller so I can load the main_thing first and then load the secondary thing?
Any help would be appreciated.
By running second request in first request's success callback:
$http.get("" + window.ENDPOINT + "/main_things/" + $scope.mainThingId + ".json")
.success(function(data) {
$scope.main_thing = data;
$http.get("" + window.ENDPOINT + "/secondary_things/" + $scope.parentMainThingId + ".json")
.success(function(data) {
$scope.secondary_thing = data;
});
});