Show downloaded html inside of string - javascript

Im trying to create kind of a user interface with a downloaded html-string and an iframe. What my 'Submitta' ActionResult does is returning a html-page as a JSON string. And then I try to append it to an iframe so I can record and save clicks. See code below:
$.ajax({
url: '/Home/Submitta/',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paket),
success: function (data) {
var iframe = document.getElementById('frame');
var html = data.Url;
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
renderat = true;
$('#frame').on('load', function () {
console.log("load");
var iframeDoc = document.getElementById('frame').contentWindow;
$(iframeDoc).mouseover(function (event) {
}).click(function (event) {
console.log($(event.target.valueOf()));
});
});
},
error: function (data) {
}
})
Which I am having problem with rendering due to a browser error:
Uncaught SecurityError: Blocked a frame with origin "http://localhost:xxxx" from accessing a frame with origin "null". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "data". Protocols must match.
Am I going at this project the wrong way? Is it not possible to work with iframes in this way?
For the record does this JQuery click function work when the iframe is directly rendered from a local .html file. But not when it has html appended to it.

Think of an iFrame like a window into another tab on your browser... opening a page within a page. What you're doing, is trying to transmit the data via json, generate the page on the client-side, and then put that page in the iframe... if that's the case, then you could just eliminate the iframte all together and put your generated HTML into a div or something using jQuery.
$.ajax({
url: '/Home/Submitta/',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paket),
success: function (data) {
// take "data" and do what you gotta do to
// get it into HTML...
var resulthtml = "";
// put that HTML generated above into
// your results div like this:
$("#resultsdiv").html(resulthtml);
},
error: function (err) {
$("#resultsdiv").html("Something went wrong.");
}
});

Related

How to call element.onload inside AJAX sucess function?

I am uploading a image using AJAX in php codeignitor and on upload return a JSON response containing path of uploaded image, then i insert that path into a img tag for preview
Now what i want to do is get the height and width of rendered img tag after updating its path, but the problem is i am getting a 0 always so please somebody help me out here
here is my JS
function uploadAd(){
// console.log($('#uploadedPDF').prop('files'));
var file_data = $('#uploadedAdFile').prop('files')[0];
var form_data = new FormData();
form_data.append('uploadedAdFile', file_data);
// alert(form_data);
$.ajax({
url: BASE_URL+'home/uploadAdFile', // point to server-side PHP script
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
async: false,
success: function(data){
console.log(data);
if(data.status == -1){
// If file extension Validation failed
$('#uploadedAdFileMsg').html(data.msg);
$('#uploadedAdFileMsg').removeClass('hidden');
$('#uploadedAdFilePreview').addClass('hidden');
}
else{
// If file extension Validation passed
$('#uploadedAdFilePreview').attr('src', data.path); // Render file in img tag
$('#uploadedAdFileMsg').addClass('hidden');
$('#uploadedAdFilePreview').removeClass('hidden');
console.log(document.getElementById('uploadedAdFilePreview').naturalWidth);
// console.log()
}
},
complete: function(){
console.log('Complte '+document.getElementById('uploadedAdFilePreview').naturalWidth);
}
}).done(function(){
console.log('Done '+document.getElementById('uploadedAdFilePreview').naturalWidth);
});
}
$(document).ajaxComplete(function(){
console.log('AJAX '+document.getElementById('uploadedAdFilePreview').naturalWidth);
})
as you can see I inserted get height code in various places but no luck
PS: I used clientHeight, height, naturalHeight as well but still got 0
so what I concluded is the height function is called before the img tag rendered its content hence it shows a 0
so can I include a onload type of function inside a AJAX success function ??
thanks
I Solved it :D ,
actually i was using onload on a Jquery returned object which is wrong , it should be used on document.getElement , so then i put a
element.onload = function(){ getHeight(); }
inside my success function os AJAX, and it worked :)

How to read dynamic url from JSON file?

I have a .json file (see below) with image URL containing variables like the path and the project name.
{"imgs":[
{
"gatewayImg": "resrcPath+_global_PROJECT_NAME+'/images/gateway-'+_global_PROJECT_NAME+'.png'"
}
]}
I also have my ajax request loading the file and on my request success I assign the attribute src and the source path to the image.
$.ajax({
async: false,
type: "GET",
global: false,
dataType: "json",
url: resrcPath+"imgRes.json",
success: function (data) {
var src = data.imgs[0].gatewayImg;
$('.gatewayImg').attr('src', src);
}
});
The problem is that when the I do this, the image isn't found on the local server and I get this localhost:8080/order/resrcPath+_global_PROJECT_NAME+'/images/gateway-'+_global_PROJECT_NAME+'.png' as the src.
But when I attribute the src as followed: $('.gatewayImg').attr('src', resrcPath+_global_PROJECT_NAME+'/images/gateway-'+_global_PROJECT_NAME+'.png'); the image shows up and the variables are well replaced by their correct value.
I don't know if my JSON is valid or not that way, and I need to know how to assign the src with the json value instead of writing the URL in the attribute function.
Your JSON is valid, but you have a string that needs to be executed (evaluated). If you have 100% control over the JSON file, you can eval the string, that assumes you have resrcPath,_global_PROJECT_NAME as globals.
var resrcPath = "/";
var _global_PROJECT_NAME = "global"
eval("resrcPath+_global_PROJECT_NAME+'/images/gateway-'+_global_PROJECT_NAME+'.png'")
=== "/global/images/gateway-global.png"
$.ajax({
async: false,
type: "GET",
global: false,
dataType: "json",
url: resrcPath+"imgRes.json",
success: function (data) {
var src = data.imgs[0].gatewayImg;
$('.gatewayImg').attr('src', eval(src));
}
});
The best solution would be to process the string on the server so you don't need to evaluate it again on the client and open holes in your program.

Outlook Office Addin not showing HTML page in div

This is my div:
<body>
<div id="content"></div>
</body>
and this is my code behind in js:
function jsonParser(sender) {
$.ajax({
type: "GET",
url: "http://MYURL/customers/outlook?email=" + sender + "&jsonp=true",
dataType: "jsonp",
success: function (htmlPage) {
document.getElementById("content").innerHTML = htmlPage.htmlText;
}
});
}
And this is the code that calls it:
function detectActionsForMe() {
var item = Office.cast.item.toItemRead(Office.context.mailbox.item);
var sender = item.sender.emailAddress;
jsonParser(sender);
}
I can't actually get the downloaded html page to show up in the Outlook (2016) addin window. I already tried using an iframe but I was obtaining nothing, neither.
I am sure about the page I am getting, I find just weird that it won't show up in the outlook box.
I found out what was missing, thanks to http://www.sitepoint.com/jsonp-examples/
Basically, I just added the following, to the ajax call:
contentType: "application/json",
dataType: "jsonp",
and it all worked! :)

Extract data from current URL and use it in ajax call as a paramenter

I am developing a website in which only 1 html page is there in which I first fethch the url & gets the id from url and send it to api using ajax call. On success, I displays data of the given id from url.My code is as-
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#main').hide();
var url = window.location.href;
var formno = url.substr(url.lastIndexOf('/') + 1);
if (formno != 'Login.html') {
var apiUrl = 'http://localhost:801/api/api/Patient/Get';
$.ajax({
url: apiUrl,
crossDomain: true,
contentType: "application/json",
type: 'GET',
data: { formNo: formno },
success: function (result) {
$('#main').show();
alert("Success" + result)
},
error: function (result) {
alert("error :: " + JSON.stringify(result))
}
});
}
});
</script>
when I use the url as abc.in#1 it displays the success alert but I want to give the url in format abc.in/1 at that time it gives
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Why it can not find the page? Is there any solution for this?
I want to give plain url as abc.in/1 where 1 is id and which is dynamic.
Is there any solution?
Your browser is probably trying to access document on location abc.in/1, which doesn't exist. You will need some server side logic for this, e.g. php router which will always serve your document, and additonal parameters will be processed by it. abc.in#1 anchor is different type of url parameter, which purpose is to be processed by document or javascript on client side.

Merging Javascript AJAX requests

I have a performance problem when loading a website over the network stored on an internal server. The performance issue is down to the multiple AJAX requests made in my Javascript file constantly trying to access an XML file and then getting an Image from a XML node or a Name from an XML node.
Is there a way I can merge the AJAX requests together to reduce the amount of requests from the client device to the XML file stored on the server.
My code is as below:
function getimage(getID,XMLImageID)
{
$("#" + getID).empty();
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(xml){
$(xml).find(XMLImageID).each(function(){
var image = $(this).find("image[href]").attr("href");
$('#'+ getID).append($("<img"+" class="+"Timages"+" src=\"" +image+"\"/>"));
});
},
error: function() {
alert("(getImage) An error occurred while processing XML file. Reasons could be: \n The XML cant be located. \n The XML is being used by another program. \n The XML is trying to parse incompatible characters. \n The XML syntax/tags are incorrect.");
}
});
}
function getdept(getid,XMLID)
{
var scriptTag = document.scripts[document.scripts.length - 1];
var parentTag = scriptTag.parentNode;
getid = parentTag.id;
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(xml){
$(xml).find(XMLID).each(function(){
var dept = $(this).find('Dept').text();
var id = $(this).attr("id");
var sName = $(this).find('Name').text();
$("#"+getid).append('<div class="Team_People" onmouseover="area_hover1(this);area_hover2(this)" href="#p'+id+'">'+dept+'<br />'+sName+'</div>');
});
},
error: function() {
alert("(getHierPeopleDept)An error occurred while processing XML file. Reasons could be: \n The XML cant be located. \n The XML is being used by another program. \n The XML is trying to parse incompatible characters. \n The XML syntax/tags are incorrect.");
}
});
}
The AJAX response uses a simplified code below, I just need to merge the code above to make it more neater rather than having multiple ajax requests. Not sure if this is possible (whether adding multiple parameters would work)?
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(xml){
$(xml).find(XMLID).each(function(){
//Get something from XML node
});
},
});
}
If anyone could guide me in the right direction that would be much appreciated!
Thanks
Regards
AJ
Create a global XML variable and query that with your function calls...
var XML = null;
function fetchXML(){
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(data){
XML = data;
},
error:function(){ alert('something went wrong');})
}
function getImage(id) {
$(XML).find(id).each(){ ... };
}
funcition getDept(id) {
$(XML).find(id).each(){ ... };
}

Categories

Resources