Angularjs how to preserve url in function? - javascript

Hi I am developing one Angularjs application. I have three cascading drop downs. Based on the selected values in drop down i am binding div with data received from api(div with ng-repeat). I have implemented paging.
On page load i am binding first dropdown.
var arrMakes = new Array();
$http.get(url + 'api' + '/Vehicle/' + 'GetVehicleMake').success(function (data) {
$.map(data.data, function (item) {
arrMakes.push(item);
});
$scope.list = arrMakes;
var dynamicUrl = url + 'api' + '/Vehicle/' + 'Getcars/';
//bind data to Div randomly.
getcadetails(dynamicUrl);
}).error(function (status) {
});
function getcadetails(baseurl)
{
var arrallcarDetails = new Array();
$http.get(baseurl,{ params: $scope.pagingInfo }).success(function (data) {
$.map(data.data, function (item) {
arrallcarDetails.push(item);
});
$scope.carDetails = arrallcarDetails;
$scope.pagingInfo.totalItems = data.totalcount;
}).error(function (status) {
});
}
getcadetails is a function i am calling from different scenarios. For example,
ng-change event of first dropdown
$scope.getModel = function (selectedMake) {
var selectedMakeData = selectedMake.ID;
var arrModel = new Array();
$http.get(url + 'api' + '/Vehicle/' + selectedMakeData + '/GetVehicleModel').success(function (data) {
$.map(data.data, function (item) {
arrModel.push(item);
});
$scope.Modellist = arrModel;
var dynamicUrl = url + 'api' + '/Vehicle/' + 'Getcars/' + '?MakeID=' + selectedMakeData;
//bind data to Div randomly.
getcadetails(dynamicUrl);
}).error(function (status) {
});
}
In paging i have below function. This is executed when i click on page numbers for example 1,2, etc
$scope.pageChanged = function (currentPage) {
$scope.pagingInfo.pageNumber = currentPage;
getcardetails();
};
Here my problem starts. If i click on any page number $scope.pageChanged function executes. I will get page number to send it to server. after that i will call getcadetails(?). Now how can i get baseurl for getcadetails? Is there any way i can implement this in better way? Any help would be appreciated. Thank you.

i think u can define a variate for selectedMakeData, and define a function to create url. every time before invoke getcardetails() u should calculate the dynamicUrl.
code looks this:
var selectedMakeData = 0;
selection.addEventListener('change', () => {
selectedMakeData = newData;
});
$scope.pageChanged = function (currentPage) {
var url = getUrl();
$scope.pagingInfo.pageNumber = currentPage;
getcardetails(url);
};
function getUrl() {
// return url baseed on selectedMakeData
}

Related

Trying to get a correct url output

I am kinda new to asp.net mvc website with jquery, razor, javascript and html. Right now my actionlink has a problem where I cannot insert the filter part, into ..page/?sortMethod=StartDate
filters?=pending generates from a button (pending is just 1 of the many status)
?sortMethod=StartDate generates from actionlink.
I am trying to make them work together to get:
..page/?filters?=pending&sortMethod=StartDate
I tried to do a script that tries to replace the
This is the initial code, sortMethod is a string.
<script>
$(function () {
$("#filterUidClear").click(function () {
$("#filterUid").val('');
});
$('#filterPending').checkboxradio();
$('#filterDirect').checkboxradio();
$('#ApplyFilter').click(function () {
var params = "";
if ($('#filterPending')[0].checked) {
params = "filters=pending";
}
if ($('#filterDirect')[0].checked) {
if (params !== "") {
params = params + "&";
}
params = params + "filters=direct";
}
$("#param").val("?" + params);
window.location.href = "?" + params;
});
});
</script>
#Html.ActionLink("Leave Date", "Index", new { sortMethod = ViewBag.StartDate })
This is the new modified one
#Html.ActionLink("Leave Date", "Index", new { sortMethod = ViewBag.StartDate }, new { id = action })
<script>
$(function() {
$('#action').click(function() {
var filterparam = $("#param").val();
this.href = this.href + '?filters=' + encodeURIComponent(filterparam) + '&sortMethod=' + #ViewBag.StartDate;
});
</script>
I am trying to make them work together to get:
..page/?filters=pending&sortMethod=StartDate but to no avail.
The table will display filtered with pending results and sorted by date
Right now it displays ..page/?action&sortingMethod=StartDate
the table shows sorted by date but no filter and action is not being replaced by filter type e.g. ?filters=pending

JSON get data form url using javascript and than save the data to a var [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
<script type="text/javascript">
$(document).ready(function() {
var chanName = "";
loadchannelID("Pewdiepie");
function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$('#ytID').html(data.items[0].id);
//MAKE IT TO A VAR
});
}
function loadChannel(data) {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
var url1 = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url1, function(data){
$('#ytName').html(data.items[0].snippet.title);
$('#ytDis').html(data.items[0].snippet.description);
$('#ytImage').html(' <img class="img-circle" src=\"'+data.items[0].snippet.thumbnails.medium.url+'\" >');
});
}
setInterval( function() {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+chanName+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
}, 5000);
$('#update').click( function(){
loadchannelID($('#chnlName').val());
})
});
</script>
This is what is have done so far. I need to get the id form a Youtube channel but i have a Youtube name. So i need to convert the name to the youtube channel id. The "Function loadchannelID" is what i have so far, it works but i need to get the #ytID to a var. But I dont know how to do that. The other function is to show the data from the Channel ID and that will work aswell if the id is converted to a var. Please help! Thanks!
I hope this is what you want to achieve:
var chanName = "";
var chanID = 0;
loadchannelID("Pewdiepie");
function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
chanID = data.items[0].id;
$('#ytID').html(chanID);
loadChannel(chanID); // now, you know the ID, pass it to "loadChannel"
});
}
function loadChannel (id) {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
var url1 = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url1, function(data){
$('#ytName').html(data.items[0].snippet.title);
$('#ytDis').html(data.items[0].snippet.description);
$('#ytImage').html(' <img class="img-circle" src=\"'+data.items[0].snippet.thumbnails.medium.url+'\" >');
});
}
I am not clear if you are trying to get the value or you try to make the url but in both cases you can do:
if you want to get the param value you can use:
var url_string = "https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=Pewdiepie&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI";
var url = new URL(url_string);
var forUsername = url.searchParams.get("forUsername");
if you want to set the param you can do:
var forUsername = url.searchParams.set("forUsername", yourValueHere);
As ive already said, your code is async, so you may use Promises like this:
function loadchannelID(name){
return new Promise(function(resolve){
var chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$('#ytID').html(data.items[0].id);
//lets resolve the promise
resolve(data.items[0].id);
});
});
}
So you can use it like this:
loadChanelID("test").then(function(name){
alert("name is"+name);
});
If you change
function loadChannel(data) {
To:
function loadChannel(id){
You can do:
loadChanelID("test").then(loadChannel);
I assume you want to use your var within the class and chanName is your channel ID and name container array
(function($, jsYouTube){
var chanName = "";
$.getChannelID = function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$this.chanName['id'] = data.items[0].id ;
});
}
})(jQuery, 'jsYouTube');

AngularJs two way data binding doesn't work when add SignalR lib

My problem started when I tried to add a library SignalR in my AngularJs project. I do not know why but the data flow has stopped working properly, I mean that when I try to insert an object into an array I do not see it, but when I try to add another one I see first object, and when I try to add a third object I see only the second.
edit : all code in the angular controller.
app.controller('HomeCtrl', ['$scope', 'HttpSrv', '$state', function ($scope, HttpSrv, $state) {
$scope.messages = [];
activate();
function activate() {
if (HttpSrv.CheckToken()) {
loadPage();
}
};
$scope.$on("$destroy", function () {
con.stop();
});
function connectToChat() {
HttpSrv.http('GET', 'home/GetChatToken').then(function (res) {
localStorage.setItem('ChatToken', res.Result);
con.start({ jsonp: true }, function () { console.log('Start'); });
});
}
var con = $.hubConnection("http://localhost:4704/");
var hub = con.createHubProxy('ChatHub');
hub.on('fail', function (res) {
console.error(res);
});
hub.on('addMessage', addMessage);
$scope.trySend = function () {
hub.invoke('SendMessage', localStorage.getItem('ChatToken'), document.getElementById('messageBox').value);
};
function addMessage(name, message, elementId) {
var tempMessage = '<li id="' + elementId + '" class="right clearfix"><div class="chat-body clearfix">'
tempMessage += '<div class="header"><strong class="pull-left primary-font">' + name + ': </strong> <br />'
tempMessage += '</div><p>' + message + '</p></div></li>'
document.getElementById('chatBody').innerHTML += tempMessage;
document.getElementById('messageBox').value = '';
document.getElementById(elementId).scrollIntoView();
document.getElementById('chatBody').focus();
}
function loadPage() {
HttpSrv.http('GET', 'home/get').then(function (res) {
//console.log(res);
if (res.Status == 200 && res.Succeeded) {
connectToChat();
for (var i = 0; i < res.ListResult.length; i++) {
res.ListResult[i].CreateDate = res.ListResult[i].CreateDate.replace('T', ' ').slice(0, 19);
}
$scope.newsList = res.ListResult;
}
});
};}]);
(i use document.getElementById because of the problem)
First, you shouldn't be building markup in your code. Simply add the message to the list and use ng-repeat in your markup.
However, you also must make sure you use $scope.$apply() or $scope.$digest() when you are processing messages from signalR.
function addMessage(name, message, elementId) {
$scope.$apply(function(){
$scope.messages.push(message);
});
}

Pass Several Parameters to Url.Action under jQuery (Modal)

I research several post here about this topic and the best performance to me to pass several variables at Url.Action() / Url.Content() under a modal was:
$('a.rengComments').click(function (e) {
e.preventDefault();
var DocID = $('#fact_num').attr('fact_num');
var ArtID = $(this).attr('idnum');
var TipoDoc = $(this).attr('tipo');
var RengID = $(this).attr('rengnum');
var DocNum = $(this).attr('docnum');
var url = '#Url.Content("~/PMContent/CreateRenglonComments/?id=")' + DocID + '&ArtID=' + ArtID + '&TipoDoc=' + TipoDoc + '&RengID=' + RengID + '&DocNum=' + DocNum;
GetModal(url);
});
function GetModal(url) {
var form = $("#Modal-Charge form");
$('#ModalContent').load(url, function (html) {
$("#Modal-Charge").modal('show');
});
}
This post present a good and elegant solution but under modal doesn't work for me, the window.location.href = url.replace('_param_', encodeURIComponent(param)); doesn't replace the parameters
Exist any other solution apart those two publish here at the post?
Thanks you

calling JQuery HTTP GET request inside javascript function

I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}
//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}
jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});
Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}

Categories