How to add a variable to location.href when creating new buttons in jquery? - onclick

I am adding new buttons in jquery and each button should have its own specific url. But adding a variable to the URL seems to be a problem.
I searched numerous sites and pages. No solution found. Here is my code:
$.ajax({
type:'POST',
url:'includes/Get_number_of_days.inc.php',
dataType: 'json',
success: function(response){
var len = response.length;
for (var a = 0; a < len; a++) {
var afdeling = response[a].Competitie_Naam_Kort;
var y = response[a].Speelweek;
var newbutton = $('<input/>').attr({
type: "button",
value: a,
id: afdeling + y,
class: "button-" + afdeling + y,
onClick: "/ADL/Competitie/Uitslagen.html?" + afdeling + y
});
newbutton.appendTo(div);
}
}
});
The buttons show up all right, but nothing happens when I click them. It must have to do something with the syntax in onClick: "/ADL/Competitie/Uitslagen.html?" + afdeling + y. But I can't figure out what the correct syntax should be. All help greatly appreciated of course...

Related

Ajax call not getting data which is in json format from API

I am trying to call api function from asp.net core razor page from news.cshtml page using below ajax function.
Its giving undefined error for console.log(len);... if i remove this then nothing happens no data, no error
$.ajax({
url: "api/news/getallnews/1",
type: "GET",
dataType: "json",
success: function (response) {
//console.log(response);
var len = response.length;
console.log(len);
var table = $("<table><tr><th>Details</th></tr>");
for (var i = 0; i < len; i++) {
// console.log("i "+i);
table.append("<tr><td>Title:</td><td>" + response[i].newsHeading + "</td></tr>");
}
table.append("</table>");
$("#news").html(table);
}
});
json Data returnet by api, i am just showing one row while my api returns around 36
{"data":[
{
"newsID":2076,
"newsHeading":"New Title is here",
"newsBrief":"New Brief is here",
"newsDetails":"\u003Cp\u003E\r\n\t\u003Cem\u003E New details in HTML format are here.\u003C/p\u003E\r\n",
"newsDate":"2020-01-28T00:00:00",
"languageID":1
}]}
Try this:
var len = response.data.length;
console.log(len);

ng-repeat not binding after successful ajax call

I want to use the ng-repeat directive to bind some data to a div. though the call is successful and i am getting the data and storing it in a scope variable im anot able to use the ng-repeat to display it
<div data-ng-app="myapp" id="sidestatus" style="position:fixed;top:50%;right:0;height:200px;width:200px;background-color:red;" data-ng-controller="myctrl">//wont bind here after successful execution
<ul>
<li data-ng-repeat="x in obj">
{{x.heading+' '+x.id+' '+x.name }}
</li>
</ul>
</div>
my javascript
var app = angular.module("myapp", []);
app.controller("myctrl", function ($scope, $http) {
var obj2=new Array();
$.ajax({
type: "POST",
url: "NotifierService.asmx/getdata",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function (response) {
var res = response.d;
var res4 = res.split(",");
for (var i = 0; i < res4.length; i++) {
var res2 = res4[i].split(":");
obj2[i] = {}
obj2[i].heading = res2[0];
var res3 = res2[1].split("/");
obj2[i].id = res3[0];
obj2[i].name = res3[1];
}
$scope.obj = obj2;
//successfully execute the success function everytime
},
error:function () { alert("failure");}
});
});
data being sent
"heading1:23/name1,heading2:24/name2"
Whenever you execute some code outside AngularJS "controlled" functions, AngularJS doesn't know if something may have change in any of the scopes, and because of this it don't try to find the changes and modify the presentation with the changes if there are any.
In your code, you are making an Ajax call with jQuery. The callback of that Ajax call is executed outside of AngularJS controlled code and it happens what I explained previously. So what you have to do is inform AngularJS that something may have changed in the scope. You have two options to do this.
$scope.$digest() is used to tell AngularJS to check for changes. So you're code could look something like this:
success:function (response) {
var res4 = res.split(",");
var res = response.d;
for (var i = 0; i < res4.length; i++) {
//...
}
$scope.obj = obj2;
$scope.$digest(); //hey AngularJS, look for changes to update the scope!
}
Another way is to use $scope.$apply. This method tells AngularJS to execute the function passed as an argument and afterwards (whether the function executed correctly or not, throwing and error for example) check for changes in the scopes. So your code could look something like:
success:function (response) {
$scope.$apply(function() { //hey AngularJS, execute this function and update the view!
var res = response.d;
var res4 = res.split(",");
for (var i = 0; i < res4.length; i++) {
//...
}
$scope.obj = obj2;
})
}
Like #LionC mentioned, you should look into why $http throws an error.
You can try to do:
success: function () {
$scope.$evalAsync(function () {
var res = response.d;
var res4 = res.split(",");
for (var i = 0; i < res4.length; i++) {
var res2 = res4[i].split(":");
obj2[i] = {}
obj2[i].heading = res2[0];
var res3 = res2[1].split("/");
obj2[i].id = res3[0];
obj2[i].name = res3[1];
}
$scope.obj = obj2;
});
}
But I thoroughly recommend you do not!
More info here: "Thinking in AngularJS" if I have a jQuery background?
Hope this helps!
Plunk demo : http://embed.plnkr.co/YWQ1LyZWm2fzwgPxX4kk/preview
The essential use of $scope.$evalAsync is to get angular to apply the changes in scope to the DOM. There are other ways to do this too : http://www.panda-os.com/2015/01/angularjs-apply-digest-and-evalasync/#.VZ0JIPmqqko
Hope this helps!
Using availsync function may solve the problem. If not, try to use settimeout. Its just because of two way binding problem.

Google Maps v3 MarkerManager v1.1 LatLngToPixel undefined

I’m having problems upgrading to Google Maps v3 from v2. In particular with MarkerManager. I haven’t worked with maps before and am helping out someone whose developer abandoned them who developed the maps in v2.
The map is to show a maximum of 100 markers that when clicked on show an infobox. (There is also a telerik RadGrid bound to with the results.) It all seems to work until it gets into DisplayAllMarkers() mgr.addMarkers() (see below). It fails in ProjectionHelperOverlay.prototype.LatLngToPixel with Uncaught TypeError: Cannot call method ‘lng’ of undefined. I’ve tried putting in alerts in AddMarker if lat or lng are undefined, but none were alerted. The previous calls to MarkerManager.prototype.addMarkerBatch_ set mPoint to undefined which was then passed to getTilePoint which calls LatLngToPixel where it fails.
I’m thinking it’s a problem with listeners, but have tried various listeners without success. I would really appreciate some help with this as I have been unable to make progress for some time and am letting down the client and don’t know what to try next.
Select SearchResult.js snippet of code:
$(document).ready(function () {
InitializeMap(originalScale);
});
var map;
var batch = [];
var mgr;
var geocoder = null;
function InitializeMap(scale) {
map = new google.maps.Map(
document.getElementById('MapContainer'), {
center: new google.maps.LatLng(Latitude, Longitude),
zoom: scale,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
var listener = google.maps.event.addListener(map, "bounds_changed", function () {
MapMoved();
google.maps.event.removeListener(listener);
});
}
var south, west, north, east, zoom;
function MapMoved() {
zoom = map.getZoom();
//zoom = map.setZoom();
var bounds = map.getBounds();
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
south = sw.lat();
west = sw.lng();
north = ne.lat();
east = ne.lng();
Search();
}
The Search(); loads up the search parameters (including the north, south, east, west co-ordinates) and calls a telerik ajax request.
C# snippet:
if (Properties.Count >= 1 || zoom == "0") //display properties
{
RadAjaxManager1.ResponseScripts.Add("ClearAll();");
Properties.ForEach(p =>
{
string script = "AddMarker(" + p.ID.ToString() + "," + p.LatitudeShort.ToString() + "," + p.LongitudeShort.ToString() + ");";
RadAjaxManager1.ResponseScripts.Add(script);
});
RadAjaxManager1.ResponseScripts.Add("DisplayAllMarkers();");
}
else //zoom out map – which will start the search process all over again.
{
string delta = "1";
RadAjaxManager1.ResponseScripts.Add("ZoomOut(" + delta + ");");
}
SearchResult.js snippet continued:
function ClearAll() {
batch = [];
}
function AddMarker(id, lat, lng) {
batch.push(CreatePropertyMarker(lat, lng, id));
}
function DisplayAllMarkers() {
mgr = new MarkerManager(map, { trackMarkers: true });
google.maps.event.addListener(mgr, 'loaded', function () {
mgr.clearMarkers();
mgr.addMarkers(batch, 3, 17); // **Failing in here!!!**
mgr.refresh();
});
}
function CreatePropertyMarker(lat, lng, id) {
var redIcon3 = {
url: '../images/HouseIcon_ForGoogleMap.png',
size: new google.maps.Size(22, 22),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 22)
};
var marker3 = new google.maps.Marker(new google.maps.LatLng(lat, lng), redIcon3);
google.maps.event.addListener(marker3, 'click', function () {
var data = "{'Id': '" + id + "'}";
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: 'searchresult.aspx/GetPropertyPopOut',
data: data,
success: function (data) {
var popout = data.d;
marker3.openExtInfoWindow(map, "custom_info_window_red", popout, { beakOffset: -1 });
},
error: function (result) {
alert('status:' + result.status + ' statusText:' + result.statusText);
}
});
});
return marker3;
}
Script order and versions:
jquery-ui-1.9.1.custom.min.css
Google Maps: v3 (I have also tried specifying particular version 3 numbers e.g. v=3.12 http://maps.googleapis.com/maps/api/js?key=MY_KEY&sensor=false
jquery-1.8.2.js
jquery-ui-1.9.1.custom.min.js
extinfowindow.js v2.0
MarkerManager.js v1.1
SearchResult.js
jquery-ui-1.8.16.custom.min.js
jquery-1.6.2.min.js
After tying a load of different things I eventually found out the problem was when creating the marker it needed position set. I changed the line in CreatePropertyMarker from:
var marker3 = new google.maps.Marker(new google.maps.LatLng(lat, lng), redIcon3);
to:
var marker3 = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
icon: redIcon3
});

Best way to load css for partial views loaded using ajax

I'm working on my application that creates tabs dynamically and fills them with partial views using ajax.
My question is: how to load css for this views? What's the best way to do it? I mean I can't load the css file on the partial view (no head) or could i?
Some code: the tabManager (a partial view loaded on the main page):
<script>
var tabTemplate = "<li class='#{color}'><a id='#{id}'href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>"; // base format for the tabs
$(document).ready(function () {
var tabs = $("#tabs").tabs(); // apply jQuery ui to tabs
$("a.menuButton").click(function () {
var urlContent = $(this).data("direction");
var label = $(this).data("label");
var idTab = $(this).data("id");
var color = $(this).data("color");
var exist = false;
var counter = 0;
$('#tabs ul li a').each(function (i) { // tab already exist o no hay que crear una tabla?
counter = counter + 1; // index counter
if (this.id == "#" + idTab) { // Tab already exist?
exist = true;
$("#tabs").tabs("option", "active", counter - 1); //activate existing element
}
});
if (idTab == "-1") { // is a clickable element?
exist = true;
}
if (exist == false) { // create new tab
addTab(idTab, label, color); // basic tab
getTabContent(idTab, urlContent); // content for new tab
var lastTab = $('#tabs >ul >li').size() - 1; // get count of tabs
$("#tabs").tabs("option", "active", lastTab); // select last created tab
}
});
function getTabContent(idT, urlC) { // ajax call to partial view
$.ajax({
url: urlC,
type: 'GET',
async: false,
success: function (result) {
$("#"+idT).html(result);
}
});
};
function addTab(idT, labT, color) { //create new tab
var label = labT,
id = idT,
li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label).replace(/#\{id\}/g, "#" + id).replace(/#\{color\}/g, color)),
tabContentHtml = "Cargando...";
tabs.find(".ui-tabs-nav").append(li);
tabs.append("<div id='" + id + "'><p>" + tabContentHtml + "</p></div>");
tabs.tabs("refresh");
}
// close icon: removing the tab on click
tabs.delegate("span.ui-icon-close", "click", function () {
var panelId = $(this).closest("li").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
});
tabs.bind("keyup", function (event) {
if (event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE) {
var panelId = tabs.find(".ui-tabs-active").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
}
});
});
</script>
<div id=tabs>
<ul>
</ul>
A button example:
<li><a class="menuButton" href="#" title="Permisos" data-id="tab3" data-direction="Permiso/_Administrar" data-label="Label" data-color="blue"><img src="#Res_icons.More">Permisos</a><li>
i found my answer here: http://dean.resplace.net/blog/2012/09/jquery-load-css-with-ajax-all-browsers/
the code:
<script type="text/javascript">
$(document).ready(function () {
$("head").append("<link href='...' rel='stylesheet'>");
});
</script>

SimpleModal doesn't work in IE 9 (inside Iframe)

I'm getting following error when using IE 9 (Chrome and FireFox works great):
SCRIPT438: Object doesn't support property or method 'removeExpression'
jquery.simplemodal.1.4.2.min.js, line 16 character 133
Simple Modal is called inside Iframe. jQuery.min (1.7.1) is included before SimpleModal (1.4.2) in the Iframe.
The code responsible for showing modal dialog:
function OpenContextByClass(cssClass, posY, posX) {
var winHeight = $(window).height();
var winWidth = $(window).width();
$('.' + cssClass).modal({
overlayClose: true,
position: [posY, posX],
appendTo: 'form',
onOpen: function (dialog) { dialog.overlay.fadeIn('fast', function () { dialog.container.slideDown('fast', function () { dialog.data.fadeIn('fast'); }); }); },
onShow: function (d) {
var self = this;
self.container = d.container[0];
var title = $('.' + cssClass, self.container);
title.show();
$('.' + cssClass, self.container).show();
setTimeout(function () {
var currentPositionX = posX;
var currentPositionY = posY;
var currentWidth = $('.' + cssClass, self.container).width() + 50;
var currentHeight = $('.' + cssClass, self.container).height() + 50;
posY = (currentPositionY + currentHeight) < winHeight ? currentPositionY : (winHeight - currentHeight);
posX = (currentPositionX + currentWidth) < winWidth ? currentPositionX : (winWidth - currentWidth);
d.container.animate(
{ left: posX, top: posY },
500,
function () {
$('.' + cssClass, self.container).show();
}
);
}, 550);
}
});
}
I have got the same problem. And I found this article: http://help.dottoro.com/ljuvxilu.php
The support for dynamic properties has been removed in Internet Explorer 9, so none of the getExpression, removeExpression, setExpression and recalc methods are supported. These methods exist in version 8, but using them raises exceptions.

Resources