Youtube api running fine with html, incorrectly with aspx - asp.net

I'm relatively new with aspx and just tried to start moving my html page with youtube api with javascript into visual studio and aspx in order to move data into a database. In html the page seems to work fine and the next page button will successfully pass the pageToken. However, when I moved my html code to aspx, I noticed the page seems to refresh and drops my next page token, reloading the same front page. It also gives me a warning code that only occurs in aspx and not the html:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
Setting 'XMLHttpRequest.withCredentials' for synchronous requests is deprecated.
I am not adding any scripts using my jquerys, which I believe is the main cause of this warning. My nextPage function however does recall the api for additional requests.
In terms of moving the html to aspx all I do is copy all my html code and put it into the header and body respectively. Am I missing a step in migrating? Do I have to change my code when using aspx instead of html?
Here is my current ASPX page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="StyleSheet1.css" rel="stylesheet" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="JavaScript1.js"></script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
<style type="text/css">
#courses {
width: 566px;
}
.auto-style1 {
width: 556px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="video-container">
<table><tr>
<td class="auto-style1">
<h1> Rutgers Accounting Digital Library Directory </h1>
</td>
<td align="right"><div id="summary"></div></td>
</tr>
<tr><td class="auto-style1"><form action="search_results.asp" method="Post"><input type="text" name="search1" placeholder="Search Here" size="20"><input type="Submit" name="Submit" value="Submit"></form></td><td><form method="link" action="my_uploads.html" ><input type="Submit" name="Clear" value="Clear Filters"></form></td></tr>
<tr><td colspan="2">
<form>
<select id="courses" onchange="show()">
<option selected disabled>Select a Course</option>
</select>
</form>
</td></tr>
<div class="button-container">
<tr>
<td class="auto-style1"><button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button></td>
<td align="right"><button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button></td>
</tr>
<tr>
<table id="results"></table>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
Here is my javascript page:
// Define some variables used to remember state.
var playlistId, nextPageToken, prevPageToken, status, cid;
var totalr = 0;
var rpp = 0;
var sum;
var dur = '';
function onClientLoad() {
gapi.client.load('youtube', 'v3', handleAPILoaded);
}
// After the API loads, call a function to get the uploads playlist ID.
function handleAPILoaded() {
gapi.client.setApiKey('APIKEY');
requestUserUploadsPlaylistId();
}
// Call the Data API to retrieve the playlist ID that uniquely identifies the
// list of videos uploaded to the currently authenticated user's channel.
function requestUserUploadsPlaylistId() {
// See https://developers.google.com/youtube/v3/docs/channels/list
var request = gapi.client.youtube.channels.list({
part: 'contentDetails',
forUsername: 'rutgersweb'
});
request.execute(function (response) {
cid = response.result.items[0].id;
dropdown(cid);
playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
requestVideoPlaylist(playlistId);
});
}
// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
console.log(pageToken);
$('#results').html('');
console.log(pageToken);
var requestOptions = {
playlistId: playlistId,
part: 'snippet',
maxResults: 50
};
if (pageToken) {
requestOptions.pageToken = pageToken;
}
var request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(function (response) {
totalv = response.pageInfo.totalResults;
rrp = response.pageInfo.resultsPerPage;
sum = '<td>Results Per Page: ' + rrp + '</td><td>Total Pages: ' + Math.ceil(totalv / rrp) + '<td>Total Videos: ' + totalv + '</td>';
$(sum).replaceAll('#summary');
// Only show pagination buttons if there is a pagination token for the
// next or previous page of results.
nextPageToken = response.result.nextPageToken;
var nextVis = nextPageToken ? 'visible' : 'hidden';
$('#next-button').css('visibility', nextVis);
$('#next-button2').css('visibility', nextVis);
prevPageToken = response.result.prevPageToken
var prevVis = prevPageToken ? 'visible' : 'hidden';
$('#prev-button').css('visibility', prevVis);
$('#next-button2').css('visibility', nextVis);
var playlistItems = response.result.items;
if (playlistItems) {
$.each(playlistItems, function (index, item) {
displayResult(item.snippet);
});
} else {
$('#results').html('Sorry you have no uploaded videos');
}
});
}
function getVideoDetails(mmp, ddp, yyyyp, dur, vidId, videoTitle, used) {
var request = gapi.client.youtube.videos.list({
part: 'contentDetails',
id: vidId
});
request.execute(function (response) {
var str = JSON.stringify(response.result.items[0].contentDetails.duration);
str = str.replace(/"/g, "");
str = str.replace(/PT/g, "");
str = str.replace(/H/g, ":");
str = str.replace(/M/g, ":");
str = str.replace(/S/g, "");
str = str.split(':');
var ftime;
if (str[1] < 10) {
ftime = str[1];
str[1] = '0' + ftime;
}
if (str[2] < 10) {
ftime = str[2];
str[2] = '0' + ftime;
}
displayOutput(mmp, ddp, yyyyp, str, vidId, videoTitle, used);
});
}
// Create a listing for a video.
function displayResult(videoSnippet) {
var videoTitle = videoSnippet.title;
var videoId = videoSnippet.resourceId.videoId;
var videoDescription = videoSnippet.description;
var videoPub = videoSnippet.publishedAt;
//dur =
//PublishedAt Formatting to compare
ar3 = videoPub.split("T");
uselessd = ar3[0];
re = new RegExp("-", "g");
uselessd2 = uselessd.replace(re, "/");
usedd = uselessd2.split("/");
ddp = usedd[2];
mmp = usedd[1];
yyyyp = usedd[0];
//Description trimming to leave time stamps only
ar = undefined;
useless = undefined;
useless2 = undefined;
used = undefined;
ar2 = undefined;
ar = videoDescription.split("Time Stamps:");
useless = ar[0];
useless2 = ar[1];
if (useless2 != undefined) {
ar2 = useless2.split("Summary");
ar = ar2[0];
re = new RegExp("\n", "g");
useless = ar.replace(re, "<br>");
used = useless;
}
else
used = " ";
// outputArray=[mmp, ddp, yyyyp, dur, videoId, videoTitle,used]
// displayOutput(outputArray);
getVideoDetails(mmp, ddp, yyyyp, dur, videoId, videoTitle, used)
}
function displayOutput(mmp, ddp, yyyyp, dur, videoId, videoTitle, used) {
//output = '<tr><td colspan="3" align="right">Published On: '+oarray[0]+'/'+oarray[1]+'/'+oarray[2]+'<br>'+dur+'</td></tr><tr><td><img src="http://img.youtube.com/vi/'+oarray[4]+'/1.jpg"></img></td><td>'+oarray[5]+'</td></tr><tr><td colspan="2" align="right">'+oarray[6]+'<hr>';
if (dur[2])
output = '<tr><td colspan="3" align="right">Published On: ' + mmp + '/' + ddp + '/' + yyyyp + '<br>Length: ' + dur[0] + ':' + dur[1] + ':' + dur[2] + '</td></tr><tr><td><img src="http://img.youtube.com/vi/' + videoId + '/1.jpg"></img></td><td>' + videoTitle + '</td></tr><tr><td colspan="2" align="right">' + used + '<hr>';
else
output = '<tr><td colspan="3" align="right">Published On: ' + mmp + '/' + ddp + '/' + yyyyp + '<br>Length: ' + dur[0] + ':' + dur[1] + '</td></tr><tr><td><img src="http://img.youtube.com/vi/' + videoId + '/1.jpg"></img></td><td>' + videoTitle + '</td></tr><tr><td colspan="2" align="right">' + used + '<hr>';
//Append to results listStyleType
$('#results').append(output);
}
// Retrieve the next page of videos in the playlist.
function nextPage() {
console.log(nextPageToken);
requestVideoPlaylist(playlistId, nextPageToken);
}
// Retrieve the previous page of videos in the playlist.
function previousPage() {
requestVideoPlaylist(playlistId, prevPageToken);
}
function dropdown(cid) {
var requestOptions = {
channelId: cid,
part: 'snippet',
maxResults: 50
};
var request = gapi.client.youtube.playlists.list(requestOptions);
request.execute(function (response) {
var plists = response.result.items;
if (plists) {
$.each(plists, function (index, item) {
var drp = document.getElementById("courses");
var optn = document.createElement("OPTION");
optn.text = item.snippet.title;
optn.value = item.id;
drp.add(optn);
});
} else;
});
}
function show() {
var e = document.getElementById('courses');
var txt = e.options[e.selectedIndex].value;
requestVideoPlaylist(txt);
}
I know the code is a little messy, still trying to get better coding habits, and I should probably fix some useless variables.

Set the type="button" on your button controls to prevent them from submitting the page each time they are pressed:
For example, in your ASPX page use:
<td class="auto-style1"><button type="button" id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button></td>
<td align="right"><button type="button" id="next-button" class="paging-button" onclick="nextPage();">Next Page</button></td>

Related

Wordpress Cookie hidden field

In Wordpress, I try to write o cookie into a hidden field. I have a cookie:
if(isset($_GET['ecselis']))
{
$cookie_name = "ecselis";
$cookie_value = $_GET['ecselis'];
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
$_SESSION["ecselis"] = $cookie_value;
}
else if(isset($_COOKIE['ecselis'])) {
$_SESSION["ecselis"] = $_COOKIE['ecselis'];
}
else
{
}
This working fine. But I dont realy know how should I write it into a hidden field
<input id="ecselis_field" name="ecselis_field" type="hidden" value="" />
I tried
<input id="ecselis_field" name="ecselis_field" type="hidden" value="$.cookie('ecselis')" />
but it doesn't work at all.
Here is some solution for you, if you want to use js/jquery ( function for getting cookie getCookie() used from this answer ):
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
jQuery(document).ready(function ($) {
$('#ecselis_field').val(getCookie('ecselis'));
})
Add this code into some .js file of your theme/child theme or create your own one.
Tested and works.

refresh input field on button click

I have this form where the user can insert a quantity in an input field, and see the total in another input field. It works when you insert the numbers manually and I want it to work with buttons too, but i just can't get it to work.
Here's the code:
HTML
<form id="buyForm" method="post" action="cart.php">
<label>Choose quantity</label>
<div>
(+)increase
<input type="text" id="qty1" name="qty[]"/>
(-)decrease
</div>
<input type="text" id="cost1" value="50" style="display:none; visibility:hidden;" name="cost[]" />
<input type="text" id="price1" name="price[]" />
</form>
Js
// Calculate
function calc(idx) {
var price = parseFloat(document.getElementById("cost"+idx).value)*
parseFloat(document.getElementById("qty"+idx).value);
// alert(idx+":"+price);
document.getElementById("price"+idx).value= isNaN(price)?"0.00":price.toFixed(2);
}
window.onload=function() {
document.getElementsByName("qty[]")[0].onkeyup=function() {calc(1)};
document.getElementsByName("cost[]")[0].onkeyup=function() {calc(1)};
}
//Increase/decrease buttons
$(function() {
$(".button").click(function() {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
// AJAX save would go here
} else {
// Don't allow decrementing below zero
if (oldValue >= 1) {
var newVal = parseFloat(oldValue) - 1;
// AJAX save would go here
}
}
$button.parent().find("input").val(newVal);
});
});
Here it is as jsfiddle: http://jsfiddle.net/rcheH/5/
Can someone please help me with this?
Thanks in advance!

ASP.NET - Jquery to add textbox and dropdown list dynamically

I need to be able provide a table on web page with one row which has a two drop down list and one textbox and the user's should be able to add any number of rows they want. I need to to this using jquery so that i can avoid post back. Is this possible to be done in Jquery and if it is possible i was looking for some example which will be like a pointer
This should get you started... save as a .html file for an example
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
function createTextbox(){
return "<input type='text' />"
}
function createDropDown(){
return "<select><option>One</option><option>Two</option><option>Three</option></select>"
}
function createRow(){
return "<tr><td>" + createTextbox() + "</td><td>" + createDropDown() + "</td><td>" + createDropDown() + "</td></tr>";
}
function getValuesForPostback(){
//format as XML, JSON, or Whatever
var ToReturn = "<items>";
$('#sampleTable tr').each(function(){
ToReturn += "<item>";
//Get the textbox value
ToReturn += "<text>" + $(this).find('input[type=text]').val() + "</text>";
//Get the select values
$(this).find('select option:selected').each(function(){
ToReturn += "<select>" + $(this).val() + "</select>";
});
ToReturn += "</item>";
});
ToReturn += "</items>";
return ToReturn;
}
function submitValues()
{
alert(getValuesForPostback());
//NOW: Just ajax or post back this value to the server and parse for your data.
}
$(document).ready(function(){
$('#sampleTable').append(createRow());
$('#btnAdd').click(function(){
$('#sampleTable').append(createRow());
});
$('#btnSubmit').click(function(){
submitValues();
});
});
</script>
</head>
<body>
<table id="sampleTable">
</table>
<button id="btnAdd">Add</button>
<button id="btnSubmit">Submit</button>
</body>
</html>

Curious behaviour with CKEditor 3 with getData

Whenever I call getData() on my CKEditor it returns what appears to be some server generated script tags, aswell, and it has on occaision returned the firebug div as well, which seems a bit odd. So I don't think that it is related to asp specifically, but not sure
<script type="text/javascript">
$(function() {
if (queryString["fxml"]) {
$("#ckeditorPH").css("display","block").ckeditor();
}
});
CKEDITOR.plugins.registered['save'] = {
init: function(editor) {
var command = editor.addCommand('save', {
modes: {
wysiwyg: 1, source: 1
},
exec: function(editor) {
var $ck = $("#ckeditorPH").ckeditorGet();
$ck.updateElement();
$("#ckeContent").text($ck.getData()).html();
}
}
);
editor.ui.addButton('Save', { label: 'Save', command: 'save' });
}
}
</script>
<asp:Content ID="Content3" ContentPlaceHolderID="CPmainContent" Runat="Server">
<textarea id="ckeditorPH" style="display: none;" name="ckEditorPh" cols="1" rows="3"></textarea>
<div id="ckeContent"></div>
</asp:Content>
And some example returned code
<div id="footer">
asdsdasdasd</div>
<script type="text/javascript">
//<![CDATA[ var ctl00_ctl02_ImageArray = new Array('', '', '', '/Wiki WebResource.axd?d=orvFyKxqjn_MxWN6EePxi9qdFITpyPFIgsCG-7yiV981&t=634031320320031812', '/Wiki/WebResource.axd?d=orvFyKxqjn_MxWN6EePxiziK9rrZZZfuENrSUk7FQmY1&t=634031320320031812',
'/Wiki/WebResource.axd?d=orvFyKxqjn_MxWN6EePxixV5Wtl1sjTWzAxt10NTBqE1&t=634031320320031812');
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
WebForm_InitCallback();
var ctl00_ctl02_Data = new Object();
ctl00_ctl02_Data.images = ctl00_ctl02_ImageArray;
ctl00_ctl02_Data.collapseToolTip = "Collapse {0}";
ctl00_ctl02_Data.expandToolTip = "Expand {0}";
ctl00_ctl02_Data.expandState = theForm.elements['ctl00_ctl02_ExpandState'];
ctl00_ctl02_Data.selectedNodeID = theForm.elements['ctl00_ctl02_SelectedNode'];
for (var i=0;i<6;i++) {
var preLoad = new Image();
if (ctl00_ctl02_ImageArray[i].length > 0)
preLoad.src = ctl00_ctl02_ImageArray[i];
}
ctl00_ctl02_Data.lastIndex = 4;
ctl00_ctl02_Data.populateLog = theForm.elements['ctl00_ctl02_PopulateLog'];
ctl00_ctl02_Data.treeViewID = 'ctl00$ctl02';
ctl00_ctl02_Data.name = 'ctl00_ctl02_Data';
//]]>
</script>
The firebug element is due to problems in previous versions of Firebug and the latest 1.6 version fixes it.
For the rest of the scripts: I have never seen something like that.

JQuery refactoring help needed

Here's my javascript code:
<script type="text/javascript">
$(document).ready(function() {
var currentInput = '';
var currentLabel = '';
$("#userLookup").click(function() {
var url = "<%= Url.Action( "ListAll" , "User") %>";
currentInput = $("#User");
currentLabel = $("#lblUser");
openModal(url);
return false;
});
$("#locationLookup").click(function() {
var url = "<%= Url.Action( "ListAll" , "Location") %>";
currentInput = $("#Location");
currentLabel = $("#lblLocation");
openModal(url);
return false;
});
$(".selectable").live("click", function(e){
currentInput.val($(this).attr('id'));
var labelText = $(this).parent().parent().find('td').eq(2).html();
currentLabel.html(labelText);
$.fn.colorbox.close();
e.preventDefault();
});
});
function openModal(url){
$.fn.colorbox({
href:url
, open:true
, width: "400px"
, height: "300px"
});
}
</script>
And here's my HTML
<table width = "100%">
<tr>
<td>Asset User Id:</td>
<td><%= Html.TextBox("User", Model.User, (object)new{style = "width:100px", maxLength="20"})%>
<a id="userLookup" href="#">Lookup User</a>
<label id="lblUser"></label>
<%=Html.ValidationMessage("User")%></td>
</tr>
<tr>
<td>Location Id:</td>
<td><%= Html.TextBox("Location", Model.Location, (object)new{style = "width:100px", maxLength="20"})%>
<a id="locationLookup" href="#">Lookup Location</a>
<label id="lblLocation"></label>
<%=Html.ValidationMessage("Location")%></td>
</tr>
</table>
I have plenty of more lookup fields (which i omitted) similar to the two listed above and i was looking to see if anyone could help me come up with a cleaner/dry method of doing something like this?
Thanks
I would add the url for the modal box into the link itself. Then you could just add a class to that link to invoke the required functionality. It also means that you can have your JS in an external file and your JS doesn't have a dependence on the ASP.NET MVC Html helper methods.
Change your html to something like:
<table width = "100%">
<tr>
<td>Asset User Id:</td>
<td>
<%= Html.TextBox("User", Model.User, (object)new{style = "width:100px", maxLength="20"})%>
<%= ActionLink("Lookup User", "ListAll", "User", null, new { class="lookup-link" }) %>
<label id="lblUser"></label>
<%=Html.ValidationMessage("User")%>
</td>
</tr>
<tr>
<td>Location Id:</td>
<td>
<%= Html.TextBox("Location", Model.Location, (object)new{style = "width:100px", maxLength="20"})%>
<%= ActionLink("Lookup Location", "ListAll", "Location", null, new { class="lookup-link" }) %>
<label id="lblLocation"></label>
<%=Html.ValidationMessage("Location")%>
</td>
</tr>
</table>
Then you can simplify your jQuery to something like:
var currentInput = '';
var currentLabel = '';
$(".lookup-link").click(function() {
var url = $(this).attr("href");
currentInput = $(this).siblings("input")[0];
currentLabel = $(this).siblings("label")[0];
openModal(url);
return false;
});
I haven't tested any of this code, so there's probably a million errors. ;-)
HTHs,
Charles
You could have a sort of jquery plugin that attaches the click handlers for userLookup and locationLookup. It would probably take 3 arguments:
url
input
label
otherwise, you could have a function that takes 4 (the first being the item to bind the click handler to) and runs the exact code you have above.
Just don't go over the top. If you start adding more arguments for one-off solutions (e.g. boolean whether to show modal with "x" or "close" at the top), then probably you're just complicating things.
If you use a convention for naming all of your lookup elements you could create a general funciton that would work for all instances.
Something like:
OpenLookupModal(lookupId)
{
var inputName = lookupId.id.substr(0, lookupId.id.indexOf('Lookup'); //take all of the id before the word "lookup"
var currentInput = $("#" + inputName ));
var currentLabel = $("#lbl" + inputName);
openModal(url);
return false;
}
To use it:
$("#locationLookup").click(OpenLookupModal("#locationLookup"));
You could even get fancy and bind the click event of all id's ending in "Lookup" in one statement:
$("[id$='lookup']").click(OpenLookupModal(this));
Warning: This code is untested, but hopefully it gets the idea across.

Resources