How to read dynamic url from JSON file? - javascript

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.

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 :)

Run if/else script with only part of a URL

I am trying to edit my Javascript to pull different data via an AJAX call based upon only part of a URL. Currently, my if/else script looks like this:
if (window.location.href=="london") {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data-london.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
} else {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
}
This doesn't work as currently written since if window.location.href=="london") is only part of the URL, not the full URL. Is there a way to edit this script to run only based off of the last bit of the page URL? For example: /london, /nw, etc.? Is there a better way to accomplish this task?
Instead of
if (window.location.href=="london") {
Use below code
var URL = window.location.href;
if(URL.indexOf("london") !== -1)
The .indexOf function will find out a substring is exist or not in a string. And in your case you wants "london" is exist or not in URL.
I assume you are asking, when the url something like 'https://example.com/london' , so you just want to include or get the value of london. below code will help to provide always last bit of value of the url.
window.location.pathname.splitOnLast('/')[1]
it will give you '/london'. or you can just check the existence of theondon in the url.
Firstly it is not necessary to use if else like above
You can use like below
var dataurl = document.URL
$.ajax({
url: 'somepage.php',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});
in somepage.php file you can process the data however you want based on the dataurl
And also in javascript you can do like below
var urlTopost="other.php";
if(document.url.indexOf("london")!==-1)
{
urlTopost="london.php";
}
$.ajax({
url: urlTopost,
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});

Show downloaded html inside of string

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

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(){ ... };
}

jquery $.ajax automatically evaluates javascript file

I have a file list, when the user double clicks a file, it is displayed in an editor,
The problem is, after opening a javascript file, all bootstrap functions get undefined.
UPDATE:
function openFile(file){
var filename = file.getPath();
$.ajax({
url: "${fileStorageServiceBaseUrl}" + applicationId + "/files/"+ resType + filename,
type: "GET",
success: function(response) {
editor.setFile(filename, response);
}
});
openResType = resType;
$("#saveButton").prop("disabled",false);
}
After calling this function, bootstrap functions get undefined. I'm calling it from the console, not via events now.
function openFile(file){
var filename = file.getPath();
$.ajax({
url: "${fileStorageServiceBaseUrl}" + applicationId + "/files/"+ resType + filename,
type: "GET",
dataType: "text", // THIS LINE SOLVED IT!
success: function(response) {
editor.setFile(filename, response);
}
});
openResType = resType;
$("#saveButton").prop("disabled",false);
}
From the jquery documentation:
dataType: (default: Intelligent? Guess (xml, json, script, or html)) Type: String.
The type of data that you're expecting back from the server.
"script" (this was getting selected by default): Evaluates the response as JavaScript and returns it as plain text.

Categories

Resources