ASP.NET MVC attaches current path to remote Url Request - javascript

I am trying to display a remote web app in a modal div. All of this code was already created in an Asp.net webforms app. I am trying to reproduce it in an MVC App using the code that is already written. It uses Javascript to create an iFrame to display the application in a modal popup. The problem that I am having is that at some point (I can't figure out where or when after stepping through the code), MVC concatenates the current window location with the RequestedUrl and I end up with the following error:
The function that creates the iFrame in the popup is:
function CreateModalPopupHtmlElementsExitWithClickSave(ModalBoxDivObject, TargetDivName, TargetSource, TargetWidth, TargetHeight, ButtonText, SpanText) {
var iframe = CreateHtmlElement('div', { 'id': 'iframeDiv' });
iframe.innerHTML = "<iframe width='" + TargetWidth + "' height='" + TargetHeight + "' id='iframeModalPopup' style='border-width:1px; border-color:#333; background:#FFF; border-style:solid;' src=" + encodeURIComponent(TargetSource) + "' scrolling='yes' marginwidth='1' marginheight='1' frameborder='1'/>";
ModalBoxDivObject.appendChild(iframe);
var div = CreateHtmlElement('div', { 'id': 'CloseDiv' });
div.innerHTML = "<div style='text-align: center;'><span id='txt' style='font-family:arial;background-color: White;'>" + SpanText + "</span><input type='button' onclick='HideModalDivExitWithClickSave();' value='" + ButtonText + "' id='HideModalDivButton' /></div>"
ModalBoxDivObject.appendChild(div);
}
The Target is set with the following function:
function ShowManagementdDiv(imageTypeID, Guid, selectedYear) {
debugger;
var TargetWidth = 950;
var TargetHeight = 670;
bModalPopupActivated = true; window.clearTimeout(t);
DisplayModalDivExitWithClickSave('box', TargetWidth, TargetHeight, 'http://localhost/PECIMS/DocumentManagement.aspx?eid=' + imageTypeID + '&Edx=' + Guid + '&y=' + selectedYear, 'Close', 'Click to close window. ');
}
The target is set correctly when it hits the function that sets up the iFrame:
When it hits the function the (TargetSource) is the correct Url, but when the popup displays, MVC has added the current window location to it. How do I remove the default web path from the RequestedUrl?
Any assistance is greatly appreciated.

Related

why document.write method throws "access denied" error in second attempt

Following javascript is being used to open a window. It creates a form and then submit data to different server. This code executes when I click a button in my web application. First time it works fine. It open a window and post data but when I close newly opened window and click on the same button again IE throws "Access Denied" at last line pWindow.document.write(html);
Please let me know if you have any suggestion for me.
function openWindowWithPost(url, windowName, windowOptions, params) {
pWindow = null;
pWindow = window.open("", windowName, windowOptions);
if (!pWindow) return false;
var html = "";
html += "<html><head></head><body><form id='formid' method='post' action='" + url + "'>";
for (var i in params) {
if (params.hasOwnProperty(i)) {
html += "<input type='hidden' name='" + i + "' value='" + params[i] + "'/>";
}
}
html += "</form><script type='text/javascript'>document.getElementById(\"formid\").submit()</script></body></html>";
pWindow.document.write(html);
}

access to DOM add dynamiclly, getScript, ajax

I use jQuery ajax to read context on my page dynamicly. But part of DOM is load in javaScript function call by getScript in ajax .done. But just after I load new content I need to get elements by class and use it in next function. Unfortunatly I can't find elements, that I create in javaScript function, and script with that function I call using jQuery getScript.
ok, my code:
$(document).ready(function() {
$('.link').click(function(){
var subpage = $(this).attr('data-subpage');
var src = 'subpages/'+ subpage + '/' + subpage +'.php';
var script = 'subpages/'+ subpage + '/js/' + subpage +'.js';
$.ajax({
url: src,
context: document.body,
dataType: 'html',
success: function(responseText){
$('#text').html(responseText); // responseText has only container <div id="insideText"></div> that I use in one function and load there by html() several divs. One of this div has class 'translate'. I need it in function Translator
}
})
.done(function(){
$.getScript(script); // here I call script where I load several divs to #insideText
Translator($('.active').attr('data-lang')).getTranslation() // part of function have to find all div.translate, but can't find it if they're load in script call in getScript. And this is a problem.
})
})
})
I hope, I explaine my problem quite clear. If not, plaese ask, I'll try again.
There's some way to do that?
//update//
After this script, call by getScript I still have problem with second 'done':
const Presenter = function(){
var presented, show, fullDesc, cont;
presented = [
{
url: 'demo/colorsGame/',
name: 'Graj w kolorki!',
desc: 'Graj w kolorki! Wybierz taki sam kolor, w jakim napisana jest nazwa wylosowanego koloru. Spiesz się, czas ucieka coraz szybciej i szybciej. Uważaj, bo mózg może cię oszukać i uznać za ważniejsze to, co jest napisane, a nie to co widzisz. Zobacz ile punktów jesteś w stanie zdobyć zanim popełnisz trzy błędy. Ćwicz swoją koncentrację.'
},
{
url: 'demo/sampleUserProfile/',
name: 'Sample User Profil',
desc: 'Mała próbka możliwości reactJS. Wkonany z użyciem biblioteki reactJS, menadzera pakietów webpack oraz na środowisku nodeJS przykładowy profil użytkownika. Like-uj i obserwuj do woli, a jeśli chcesz, wypowiedz się pod profilem.'
}
];
show = function(url, desc, name) {
fullDesc =
"<a href ='" + url + "'>" +
"<h1 class='translate'>" + name + "</h1>" +
"</a>" +
"<div>" +
"<p class='translate'>" + desc + "</p>" +
"</div>";
cont =
"<div id='webmin' class='clearfix'>" +
"<div>" +
fullDesc +
"</div>" +
"<div>" +
"<iframe src='" + url + "' scrolling='no'>" +
"ups, twoja przeglądarka nie obsługuje ramek" +
"</iframe>" +
"</div>"+
"</div>";
return cont;
};
return {
show: show,
presented: presented
}
};
display = function(){
var len, url, name, desc;
len = Presenter().presented.length;
for(let i = 0; i <= len; i++){
url = Presenter().presented[i].url;
name = Presenter().presented[i].name;
desc = Presenter().presented[i].desc;
$('#insidetext.apps').append(Presenter().show(url, desc, name));
}
};
display();
Hmm, I'm wondering, if iframe is not a problem here? And don't let script to be done to end?
getScript is just another ajax call and returns an xhr object which exposes done and fail methods. Use those methods to ensure your dom is properly loaded before trying to access it.
$(document).ready(function() {
$('.link').click(function(){
var subpage = $(this).attr('data-subpage');
var src = 'subpages/'+ subpage + '/' + subpage +'.php';
var script = 'subpages/'+ subpage + '/js/' + subpage +'.js';
$.ajax({
url: src,
context: document.body,
dataType: 'html'
})
.done(function(responseText){
$('#text').html(responseText);
$.getScript(script).done(function() {
Translator($('.active').attr('data-lang')).getTranslation() ;
}
})
})
})
Also, you should implement the .fail methods, in case your ajax requests fail.

Why does loading a new html page reset javascript variables? How do I save those variables?

So I have this piece of code in an html file called demo.html
<img class="card-img-top" src="src/San_Francisco_Opera_House.jpg"
onclick="buyFunction('src/San_Francisco_Opera_House.jpg',
'SF opera house', 'price: $360,000')" alt="Card image cap">
This runs this javascript function which loads a new HTML page. I want to display the image in the new page,
function buyFunction(housePhotoString, addressString, priceString) {
$(location).attr('href', 'buy.html');
houseAttributes.housePhoto = housePhotoString;
houseAttributes.address = addressString;
houseAttributes.price = priceString;
$(document).ready(function() {
setPicturePriceAndAddress();
});
};
function setPicturePriceAndAddress() {
let strHTML = "";
strHTML +=
+"<img class=\"card-img-top\" src=\"" + houseAttributes.housePhoto + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + houseAttributes.address + "</h4>" +
"<p class=\"card-text\">" + houseAttributes.price + "</p>" +
"</div>";
$("#housePhotoBuy").html(strHTML);
};
But all the values gets reset. Or is there another way to send information to the new html file without having to save variables?
You could potentially store the variables in session storage on demo.html and then call them inside of buy.html
demo.html:
function buyFunction(housePhotoString, addressString, priceString) {
sessionStorage.setItem('housePhoto', housePhotoString);
sessionStorage.setItem('address', addressString);
sessionStorage.setItem('price', priceString);
$(location).attr('href', 'buy.html');
}
buy.html:
$(document).ready(function() {
var housePhotoString = sessionStorage.getItem('housePhoto');
var addressString = sessionStorage.getItem('address');
var priceString = sessionStorage.getItem('price');
setPicturePriceAndAddress(housePhotoString, addressString, priceString);
});
function setPicturePriceAndAddress(housePhotoString, addressString, priceString) {
let strHTML = "";
strHTML +=
+"<img class=\"card-img-top\" src=\"" + housePhotoString + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + addressString + "</h4>" +
"<p class=\"card-text\">" + priceString + "</p>" +
"</div>";
$("#housePhotoBuy").html(strHTML);
};
JavaScript is a client side language. Basically it is run on the web browser when it loads the page. Therefore, when a particular page is unloaded (moving away from the page, going to another page, closing the tab etc), the javascript values used in the page is flushed unless you take measures to save them.
For this, you can look into localStorage which saves the data in the browser and can be reused. Another method you can use is to set cookies which can also allow you to store and retrieve data from the user's browser between page loads.
You can store the variable in the localstorage and access the variables from anywhere under the same domain name , i.e you can use it another html file specified under same domain name
for example for your sample I created a little http server and then made a POC out of that
say your main script is contained in some index.html as your code block like this
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
</head>
<script type="text/javascript">
function buyFunction(housePhotoString, addressString, priceString) {
$(location).attr('href', 'buy.html');
houseAttributes.housePhoto = housePhotoString;
houseAttributes.address = addressString;
houseAttributes.price = priceString;
$(document).ready(function() {
//pass the houseAttributes object to setPicturePriceandAddress for better use of functions in js
setPicturePriceAndAddress(houseAttributes);
});
};
function setPicturePriceAndAddress(houseAttributes) {
let strHTML = "";
strHTML =
"<img class=\"card-img-top\" src=\"" + houseAttributes.housePhoto + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + houseAttributes.address + "</h4>" +
"<p class=\"card-text\">" + houseAttributes.price + "</p>" +
"</div>";
console.log('data',strHTML);
//storing only for one time
var dataToSave = localStorage.setItem('strHtml',strHTML)
//storing for multiple time
var arr = [];
if(localStorage.getItem('arrOfStr')){
arr = JSON.parse(localStorage.getItem('arrOfStr'))
}
arr.push(strHTML);
localStorage.setItem('arrOfStr',JSON.stringify(arr))
$("#housePhotoBuy").html(strHTML);
};
function getSavedValue(){
var data = localStorage.getItem('strHtml')
var data2 = JSON.parse(localStorage.getItem('arrOfStr'))
console.log(data,data2);
}
</script>
</html>
Then you are accessing if in your file buy.html file
<html>
<head></head>
<body>
<h1>Buy</h1>
<script type="text/javascript">
function getSavedValue(){
var data = localStorage.getItem('strHtml')
var data2 = JSON.parse(localStorage.getItem('arrOfStr'))
console.log(data,data2);
}
getSavedValue()
</script>
</body>
</html>
and under the same domain name like for example if your index.html is in http://localhost:5000
and your buy.html is in http://localhost:5000/buy.html then you will be able to retrive all values stored in the buy.html in form of array if you want to store all the responses for a particular client or you can just access one single variable.I have made both the example you can use whatever you like according to your choice. If it's less than 5mb or something like that you can use localstorage and it is better to use than in cookie or session storage because they serve different purposes and they should be kept apart for saving extra data like this buy information for a particular client

How to add my photostream?

I want to add my photostream to my website I have tried multiple bits of code
https://gist.github.com/willdurand/5705453 (cant find the set id)
and
jQuery.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=675729#N22&lang=en-us&format=json&jsoncallback=?", function(data){
jQuery.each(data.items, function(i,item){
jQuery("<img/>").attr("src", item.media.m).appendTo("#images")
.wrap("<a href='" + item.link + "'></a>");
});
});
suppose I need to find id to add the public feed to my photostream?
edit this seems to work but throws a 403.
<script>
jQuery(function(){
var apikey = 'xxxxxxx';
var userid = 'xxxxxx';
jQuery.getJSON('http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key='+apikey+'&user_id='+userid+'&format=json&jsoncallback=?',
function(data){
jQuery.each(data.photos.photo, function(i,item){
var purl = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg';
var pid = item.id;
var container = '<div class="image-container" style="background: url(' + purl+ ');"></div>';
jQuery(container).appendTo('#images');
});
});
});
</script>
this works just have to set the images to public.
I have taken the exact code you have posted below and applied it to a JSFiddle.
jQuery.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=675729#N22&lang=en-us&format=json&jsoncallback=?", function(data){
jQuery.each(data.items, function(i,item){
jQuery("<img/>").attr("src", item.media.m).appendTo("#images")
.wrap("<a href='" + item.link + "'></a>");
});
});
http://jsfiddle.net/mYnQy/
The images are returned correctly and the links are working too, I would imagine that you should check that you have a div with an ID of "images" located on your page and that you have no other javascript that is causing an error on your page.
Check this by using developer tools in your browser of choice and taking a look at the Console.

How to get more JSON data on scroll or while scrolling?

I have the following code below which returns some results when the user searches a term.
Once i get some results,I want to add feature which will allow me to get more data when scrolling down ward?
NOTE: I dont want to use any plugin(s).
$(document).ready(function() {
$("#submit").click(function (event) { // wire up this as an onclick event to the submit button.
var searchTerm = $("#search").val(); // get the user-entered search term
var URL = "http://api.flickr.com/services/feeds/photos_public.gne";
//var URL = "http://api.flickr.com/services/feeds/photos_public.gne";
var ID = "25053835#N03";
//var MYID-"84215563#N08";
//var tagmode="&tagmode=any";
//var format ="&format=json";
var tags="&tags="+ searchTerm;
var tagmode="&tagmode=any";
var jsonFormat = "&format=json&jsoncallback=?";
var ajaxURL= URL+"?jsoncallback=?id="+ID+tags+tagmode+jsonFormat;
//var ajaxURL= URL+"?"+tags+tagmode+jsonFormat;
$.getJSON(ajaxURL,function(data){
//$("h1").text(data.title);
//alert(data.length);
var photoHTML;
$("#photos").empty();
if (data.items.length) {
alert(data.items.length);
$.each(data.items, function(i,photo) {
//var photoHTML = "<h4>" +photo.tags + "</h4>";
photoHTML = "<p>";
photoHTML += '<a href="' + photo.link + '">';
photoHTML += '<img src="' + photo.media.m + '" alt="' + photo.media.m + '" title="' + photo.media.m + '"></a>';
photoHTML = "</p>";
$('#photos').append(photoHTML).fadeIn(200);
});
} else {
alert(data.items.length);
photoHTML = "<h2> No Results</h2>";
$('#photos').append(photoHTML).fadeIn(200);
}
//$('#photos').append(photoHTML).fadeIn(200);
});
});
});
You could use the jquery .scroll() method. You have two options, save all data when page loads then display as user scrolls OR make ajax request every time there is a scroll down request.
$("#yourSelector").on('scroll', function(){
// do stuff
});
or simply using the shortcut:
$("#yourSelector").scroll(function(){
// do stuff
});
I hope this helps!
Here is a link to jquery scroll api to know about the options (such as specifying scroll DOWN): http://api.jquery.com/scroll/
You can also bind scroll event using jquery:
Put your whole code into a function:
function myfun(){
//-- you code
}
and call myfun() from both event:
on click event-
$("#submit").click(function (event) {
myfun();
});
on scroll event -
$("#yourSelector").scroll(function(){
myfun();
});

Categories