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

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);
}

Related

How can I run a function on page load and then after click?

hi this is my very first time using jquery on any project at all. I am needing a little help if someone can
on my page i have some code to load a json file this file contains menu details for the main menu such as
name / action / poster
this is my code
var Items = "";
var flixAPI = "https://example.com/api.php?action=MAIN";
$.getJSON(flixAPI, function (data) {
$.each(data, function (i, item) {
Items += "<div class='img'>";
Items += "<a target='_blank' href='" + item.ACTION + "'>";
Items += "<img src='"+ item.POSTER +"' alt='" + item.NAME + "'>";
Items += "</a>";
Items += "<div class='desc'>" + item.NAME.substr(0, 16) + "</div>";
Items += "</div>";
});
$('#content').html(Items);
});
i can get this code working when i place it into the document ready.
my issue is after the main menu is populated and added to the page i then need to stop the page redirecting when a href link is clicked and get the value of the href link to then send another get json request to load the next page
i have tried loading the main menu on the document ready and then sticking one call into a .click binding to load the next set of items based on the href link clicked but when i try do this inside or outside the document ready the .click binded function wont work
Put the code in a named function so you can call it from both places.
function getFlix(flixAPI) {
var Items = "";
$.getJSON(flixAPI, function(data) {
$.each(data, function(i, item) {
Items += "<div class='img'>";
Items += "<a class='menu-link' target='_blank' href='" + item.ACTION + "'>";
Items += "<img src='" + item.POSTER + "' alt='" + item.NAME + "'>";
Items += "</a>";
Items += "<div class='desc'>" + item.NAME.substr(0, 16) + "</div>";
Items += "</div>";
});
$('#content').html(Items);
});
}
$(document).ready(function() {
getFlix("https://example.com/api.php?action=MAIN");
$("#content").on("click", ".menu-link", function(e) {
e.preventDefault();
getFlix(this.href);
});
});
This uses event delegation because the menu links are added dynamically. See Event binding on dynamically created elements?
You would need to identify the menu items with either classes or id's.
Then you would have to define the onClick event for each one of those who you need to fetch the JSON for.
ON the onClick event, you need to use e.stoppropagation or e.preventdefault (check the usage online) and then use ajax to fetch the JSON and populate whatever you are populating.

Javascript - InnerHTML doesn't edit the DOM

I'm working on a project with Laravel. Now I'm coding the feature which prints all activities responsible. Before I was using foreach loop in PHP to print all of my activities (from the DB).
But now I have to use JS to print these activities because I want to add a filter (and avoid page to reload).
I have created this script in my view :
<script>
containerE = document.getElementById("container");
var request = new XMLHttpRequest();
request.open("GET","{{route('APIManifs')}}", false);
request.send(null);
responses = JSON.parse(request.responseText);
function expandResults(value){
for (var i in responses){
if (responses[i].status === value) {
containerE.innerHTML = containerE.innerHTML +
"<div class=\'col-md-5 offset-1\' id=\'1\'>" +
"<div class=\'card\'>" +
"<a href='/manif/" + responses[i].id + "'"+" ><div class=\'card-header\' style=\'text-align: center\'>"+
"<img src='"+responses[i].image+"'><br>"+
responses[i].name+" | "+responses[i].date_add+"<br>"+
"</div> </a>"+
"<div class=\'card-body\'>"+
"Nom : "+responses[i].name+"<br>"+
"Description : "+responses[i].description+"<br>"+
"</div>"+
"</div>"+
"</div>";
containerE.innerHTML = containerE.innerHTML + "Arg";
console.log(responses[i].status+"=="+value);
}
else{
console.log(responses[i].status+"<>"+value);
}
}
}
</script>
I got the information but impossible to print my HTML in the DOM! When I copy paste the inner HTML code in the console it's work.
Do you have any ideas on how to accomplish this?
Thank's in advance!

Avoid duplicated function call in jquery?

I have build a function getuser() in which I recieve json data from php into javascript. I call this function when document gets ready. My problem is that I am also using jquery post for live updation of that record and for that reason I have to call that function getuser() again due to this it shows duplicate result. First when document gets ready socend on jquery post function.
HTML
<!--It has onclick event-->
<button type="submit" class="btn btn-primary modify" onclick="update_user()">UPDATE</button>
JQUERY
//This is function which gets json array from php
function getuser() {
$.get("getuser.php", function (data) {
var data = JSON.parse(data);
for (var i = 0, len = data.length; i < len; ++i) {
var student = data[i];
var slash = " / ";
$("#output").append("<tr><td>" + student.name + "</td><td>" + student.gender + "</td><td>" + student.age + "</td>" +
"<td>" + student.city + "</td><td><a href='#' style='text-decoration: none' class='update' id='" + student.id + "' onclick='reply_click(this.id)'>Update</a>" + slash + "<a style='text-decoration: none' href='#'>Delete</a></td></tr>");
}
});
}
//when document gets ready it will show the record
if($(document).ready()) {
// getuser();
getuser();
}
//This is jquery post. When I click button (in html section) it will get form values and sent to php page
//in return it will call getuser() function again which results of duplicate display of record
$(document).ready(function(){
$('.modify').click(function() {
var gender = '';
if($('.male').is(':checked')){
gender='Male';
}else{
gender='Female';
}
$.post("update.php",
{name: $('.name').val(),gender:gender,city:$('.city').val(),age:$('.age').val(),id:$('.id').val()},
function (data) {
//here is the function call again
getuser();
}
);
});
});
Kindy tell me that is there any way I avoid second call in post function and the record gets update without function call again.I need to avoid duplicate result. Thanks in advance!
First off, you need to read the docs on jquery document ready, and learn the difference between a function reference and actually calling a function. document.ready expects you to pass in a function definition to be called when the page is ready. It doesn't actively tell you if the page is ready, the first way you're calling it. The second way you're calling it is actually correct.
Second, replace $("#output").append with $("#output").html, which will update/replace the contents of that element every time, instead of just adding more and more.
Your if test will always return true because document.ready returns the JQuery object. So, you are always causing the call to getuser() to happen.
You can see the return value from document.ready() here:
console.log($(document).ready());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is an incorrect usage of document.ready(). You don't need to write a test for document.ready, just write a callback function for that event and let the browser do it correctly for you.
Read the docs on document.ready()
Solution:
This:
//when document gets ready it will show the record
if($(document).ready()) {
// getuser();
getuser();
}
Should be this:
//when document gets ready it will show the record
$( document ).ready(getuser);
Or even:
$(getuser);
As for you getting the results a second time, just overwrite the old results instead of appending them.
This: $("#output").append(...
Should be: $("#output").html(...
All of you thanks for your suggestions. I have found the solution here by just adding $("#tbody").html(''); in getuser() before loop. Here is the code which works fine for me
function getuser() {
$.get("getuser.php", function (data) {
var data = JSON.parse(data);
$("#tbody").html('');//newly added
for (var i = 0, len = data.length; i < len; ++i) {
var student = data[i];
var slash = " / ";
$("#output").append("<tr><td>" + student.name + "</td><td>" + student.gender + "</td><td>" + student.age + "</td>" +
"<td>" + student.city + "</td><td><a href='#' style='text-decoration: none' class='update' id='" + student.id + "' onclick='reply_click(this.id)'>Update</a>" + slash + "<a style='text-decoration: none' href='#'>Delete</a></td></tr>");
}
});
}
All of you thanks again!

ASP.NET MVC attaches current path to remote Url Request

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.

Image tag won't accept src

I am trying to make an image take a value in as a source, after the image tag (and a related radio button) has been created using JavaScript. I have discerned the following from testing and alert outputs:
If the image src is provided at the creation of the image tag using an exact filepath, it will show the image correctly (e.g. src='images/0.jpg'). However, this is not helpful since I need it to work for any given image, not a specific one.
If the image src is provided at the creation of the image tag using a variable containing a filepath, it fails to generate the image tag or the radio button at all (e.g. src='" + result + '").
NOTE: The last example is not present in the code below. The result was found by moving the '$.post' section to the line directly under the 'out +=' line within the for loop.
If the image src is left blank at the creation of the image tag, the image tag and radio button are created, though the image is blank as expected. If I then try to use 'getElementByID(imgID).src' to change the image source after this, it fails to do anything. ('imgID' here is an example, not what the code says).
On top of the above, using alerts and dumping info into divs indicate that the comicID is being correctly posted, and the filepath of the image src is definitely being found, and is being copied into the variable 'result' correctly, even one line before the creation of the tag or the attempt to edit it using 'getElementById'.
At this point I'm stumped, I don't know what could logically be stopping the src from reading in.
--
Javascript:
<script>
// Loads the user's comic list from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Irrelevant manipulation of HTML.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
out += "<hr><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='' ><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
document.getElementById("loadList").innerHTML=out;
for(j=0; j< arr.length; j++)
{
tempID = (arr[j].comicID);
$.post("getCover.php", {comicID:tempID}, function(result)
{
document.getElementById("loadList").innerHTML+="<p>"+result+"</p>";
document.getElementById("com"+arr[j].comicID).src = result;
}
);
}
}
}
</script>
PHP (getCover.php):
<?php
if (isset($_POST["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_POST["comicID"];
$query = ("SELECT pageLocation FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
print_r($row["pageLocation"]);
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
To my knowledge, loadList.php is working perfectly, so I didn't list its code to keep things relevant.
I copied your code and tweaked it a little so I could run it without the web services and it works great. Here is the HTML page I created:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
// JSON parsing for 'loadComic'.
function loadComicJSON()
{
var arr = [{comicID: 1},{comicID: 2},{comicID: 3}];
var result = "monkey.jpeg";
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Irrelevant manipulation of HTML.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
out += "<hr><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='' ><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
document.getElementById("loadList").innerHTML=out;
for(j=0; j< arr.length; j++)
{
var imgSrc;
tempID = (arr[j].comicID);
document.getElementById("loadList").innerHTML+="<p>"+result+"</p>";
document.getElementById("com"+arr[j].comicID).src = result;
}
}
}
</script>
</head>
<body>
<div id="loadList"></div>
<button onclick="loadComicJSON()">Try it</button>
</body>
</html>
As you can see, I created an array of JSON objects that hold the comicID and am statically creating the image as 'monkey.jpeg'.
The code works so there is either an issue with the 'response' that you pass into your loadComicJSON method or the result from your POST method.
Add a couple of console.log statements and look at the two values I mentioned and you will likely see the issue.
Solved the issue myself. It turned out that the $.post needed to be $.get and that it needed to technically be outside of a loop (i.e. in its own function) to work properly. Works fine now after that and a couple minor tweaks.

Categories