Programmatically view content of html element loaded from another file - javascript

I would like to get the contents of a file on the server into a string. What is the easiest way to do this? Right now I am trying:
<script type="text/template" src="partials/someTemplate.html"
id="someTemplate"></script>
<script>
console.log($('#someTemplate').html()); //nothing comes up
</script>
A hacky way to do this is:
$('<div>').appendTo(document.body)
.load('partials/someTemplate.html', function () {console.log(this.innerHTML);} );
and then get the innerHTML of that, but that's a waste of an HTML element. Any thoughts? I feel like this should be silly easy.

Just use $.get():
var html;
$.get('partials/someTemplate.html', function(res)
{
html = res;
});

You basically need to use an asynchronous server request (ajax) to get the content of a file and process it later.
This can be done in pure JavaScript using XMLHttpRequest but the most popular and easiest way to do this is using jQuery's $.ajax function.
$.ajax({
url: "partials/someTemplate.html"
}).done(function( content ) {
console.log( "Your returned content is " + content );
});
You can configure this ajax call in many ways as described in documentation, you can pass parameters to the file, cache the request or demand a specific content type to be returned if that is necessary, but given example would do just fine for what you are trying to accomplish.
Please note that there are many ways to do an ajax request in jQuery, like .load(), $.post(), $.get(), $.getScript() and $.getJSON() but those are all just shorthand methods for an Ajax request so if you use those you are basically using an $.ajax with some predefined parameters.
Also, make sure that you need to use JavaScript and an async request at all. Getting content of a file inside some other file is mostly often done using some server side processing language like PHP (require() and include()),.NET, Java etc., and while that seems obvious for some people I felt obligated to say that since you didn't provide enaugh information about why you need that content and what you want to do with it.

Related

Ajax call. Passing value to another php file

I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'

How to load an external js file as plain text and assign to variable as a string

Really sorry if this is a dumb question but I can't seem to get this to work. As the title says i am trying to load an external js file and assign it to a variable as plain text. The project is a simple js "compiler" that stitches together a number of js files and minifies them into one. I am currently using the $.get() method and appending the response to a string.
The problem is that the js file that handles the above also needs to be included in the final minified file. I can load in all the other files and stitch them together just fine but when i load this main file into itself sourcing a js file it seems to evaluate and overwrite itself and so stops the process.
For the time being i have got around the problem by loading in a copy as a .txt file but it means i have to keep two files up to date which isn't ideal.
I found this article but it refers to javascript loaded via script tags in the head.
Any help would be appreciated. I will happily post code but not sure which bits would be useful.
Update: I probably should have mentioned that the project needs to run entirely client side so i can't use PHP/.NET pages. All the files I'm loading in are on the same domain though.
Try to use Ajax.get() :
var script;
$.get('script.js', function(data) {
script = data;
});
for Ajax.get() it will work inside your domain, you can't call external domains, if your application requires loading external JS file then my guess is that you have to use PHP or another server-side language as:
var script;
$.get('getScript.php', {url: "http://test.com/script.js"}function(data) {
script = data;
});
in getScript.php you can use CURL or file_get_contents
Note that $.get() and $.post() and $.ajax() are all the same thing.
$.get and $.post are just shorthand versions of $.ajax() that come with presets (obviously, type: "GET" and type:"POST" for one...). I prefer using $.ajax because the format can be more structured, and therefore easier to learn/use.
Javascript/jQuery would look something like this:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "loadmyfile.php",
data: 'filename=js/myscript.js',
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#myhiddentext').val(whatigot);
} //END success fn
}); //END $.ajax
}); //END $(document).ready()
</script>
Important: Note that you would need to do all the post-AJAX processing inside the success function. See this link for some simple AJAX examples.
Note that you can send data across to the PHP file by specifying a data: parameter in the AJAX code block. Optionally, you can leave out that line and simply hard-code the filename into the PHP file.
The text of the retrieved js file comes back into the AJAX success function (from the PHP file) as a string in the variable specified as the function param (in this case, called 'whatigot'). Do what you want with it; I have stored it inside a hidden <input> control in case you wish to retrieve the text OUTSIDE the AJAX success function.
PHP would look something like this:
loadmyfile.php
<?php
$fn = $_POST['filename'];
$thefile = file_get_contents($fn);
echo $thefile;
References:
PHP file_get_contents

How to include a file OR PHP code with JS?

How can I include code, for example using Javascript? Or if that can't be done, how can I include a whole PHP file?
P.S. Found some script called "require" or "include," but I prefer two lines of code instead of a huge library (using jQuery though). If that can't be done, let me know, I will try to think of something else.
EDIT:
Okay, an example of what I want to do:
function foo() { if(x = 1) return 1; else return 0; }
Then if the function returns 1, I want to either add HTML/PHP code to DIV tags OR I want to include a PHP file containing that code.
EDIT #2:
What about only HTML?
document.getElementById('test').innerHTML = 'a cool link';
That doesn't seem to work either.
I have an empty div tag with id="test" in my code.
function foo() {
if(x = 1) {$("#divid").load("somephp.php");return 1;}
else return 0;
}
Or
if (foo()) $("#divid").load("somephp.php");
The only files could Javascript includes is Javascript files, what ever the extension is. and the only way to do it is using
<script src="path/to some/file.ext"></script>
You should note that the file should be javascript text contents, else errors may be generated.
Javascript can call any file as long as it is on your server.It can't call files on the user's local files, for obvious security reasons.
However, javascript cannot, and will never be able to call PHP code, as in it cannot execute php code. This is because since javascript is client side, users can call their own javascript on your page, and execute PHP code, and potentially mess up your site or browse your backend.
You can, however add HTML code to your page using javascript, fairly simply using the innerHTML property of DOM elements or JQuery.
Javascript can also call more javascript code if you wanted, using eval()
If you wanted to call files off your server onto the page using javascript, you'd have to use AJAX
Google it up, and you can code it from scratch, or use JQuery's convenient AJAX handler.
Let's say you had a php file myfile.php that had some html/php, and you wanted to insert it into a div with the id "mydiv", or in css, "#mydiv"
If you just want to quickly load the html/php and push it into the div:
$("#mydiv").load("myfile.php");
If you want to have maximum control of the response from the html/php file:
$.ajax({
url: "myfile.php", // url to load
success : function(data) { // on success function
// data is the response of the ajax request, the response text
// you can manipulate it here
manipulateData(data);
$('#mydiv').html(data); // set the html of the div
}
});

Using JSONP when returning XML

I asked an earlier question which was definitely helpful and let me know about JSONP. However, I see that I have to specify JSONP as the datatype. Now, as far as I know, that is the return type of the data coming back, which would be XML. Can XML be returned using JSONP or am I limited to it coming back as JSONP format? Thanks!
You're limited to JSONP (and not XML) because of how it works. JSONP turns into this:
<script src="myPage?callback=myFunction" type="text/javscript">
So when you take the content, it's effectively doing this:
<script type="text/javascript">
myFunction({ data: value, data2: value2 });
</script>
What comes back is actual running JavaScript, so it can't be XML, you'll get all sorts of syntax errors, exactly as you would doing this:
<script type="text/javascript">
<elem>
<data>value</data>
<data2>value2</data2>
</elem>
</script>
As you can imagine, the JavaScript parser isn't going to like that very much, and doesn't know what to do with it. jQuery can parse XML in most cases without any trouble, but if you're using JSONP and it's for cross-domain requests...well JSONP is your only option there, unless you wrote a proxy page on your site that didn't violate same-origin policy rules, and used it as a proxy to fetch the XML through.
The idea is to send back executable code from the server. Write a jQuery plugin or extend the ajax function to return the XML string as a function parameter.
myCallback("
<root>
<person>
<first>John</first>
<last>Doe</last>
</person>
</root>")
The plugin will parse this string to XML and return it back to your actual callback. As far as your callback is concerned, it is unaware of the string -> xml conversion process.
Here's an existing implementation.
The most ideal interface to this with jQuery would be,
$.ajax({
url: 'http://example.com/resource?type=xml',
dataType: 'xmlp',
success: function(xml) { .. }
});
but since messing around and rewriting jQuery.ajax is problematic, you could write this as a separate namespaced plugin itself which will use getScript underneath.
$.myNamespace.ajax({
..
});
For this to work, you would need control of the server. The server has to know that XML is requested, and respond with a function call which contains the XML string as a parameter. Assuming the callback name you sent over to the remote server was foo, the server will have to respond with something like:
foo("<names><name>..</name></names>")
I think if you were using a browser that supported E4X, then there would be no need to wrap the XML inside a string. The server could simply return the XML as an argument to the callback function:
foo(
<names>
<name>John Doe</name>
</names>
)
But unfortunately, E4X is not widely supported yet.
You can write XML in Javascript function inside in /* comment */ and convert this function to text with method functionname.toString() and parsing text between "/*" and "*/" with JSONP's callback function, that works in all old browsers. Example xml_via_jsonp.js :
function myfunc()
{/*
<xml>
<div class="container">
<div class="panel panel-info col-lg-10 col-lg-offset-1 added-panel">
<div class="panel-heading">Random1 - Random2</div>
<div class="panel-body">
<div>Random3</div>
</div>
</div>
</div>
</xml>
*/}
function callback(func)
{
var myhtml = func.toString();
var htmlstart = myhtml.indexOf('/*');
var htmlend = myhtml.lastIndexOf('*/');
return myhtml.substr(htmlstart+2, htmlend-htmlstart-2);
}

jQuery, Ajax and getting a complete html structure back

I'm new to jQuery and to some extent JavaScript programming. I've successfully started to use jQuery for my Ajax calls however I'm stumped and I'm sure this is a newbie question but here goes.
I'm trying to return in an Ajax call a complete html structure, to the point a table structure. However what keeps happening is that jQuery either strips the html tags away and only inserts the deepest level of "text" or the special characters like <,>, etc get replaced with the escaped ones
I need to know how to turn off this processing of the received characters. Using firebug I see the responses going out of my WebServer correctly but the page received by the user and thus processed by jQuery are incorrect. A quick example will so what I mean.
I'm sending something like this
<results><table id="test"><tr>test</tr></table></results>
what shows up on my page if I do a page source view is this.
<results><table....
so you can see the special characters are getting converted and I don't know how to stop it.
The idea is for the <results></results> to be the xml tag and the text of that tag to be what gets placed into an existing <div> on my page.
Here is the JavaScript that I'm using to pull down the response and inserts:
$.post(url, params, function(data)
{
$('#queryresultsblock').text(data)
}, "html");
I've tried various options other than "html" like, "xml", "text" etc. They all do various things, the "html" gets me the closest so far.
The simplest way is just to return your raw HTML and use the html method of jQuery.
Your result:
<table id="test"><tr>test</tr></table>
Your Javascript call:
$.post(url, params, function(data){ $('#queryresultsblock').html(data) })
Another solution with less control — you can only do a GET request — but simpler is to use load:
$("#queryresultsblock").load(url);
If you must return your result in a results XML tag, you can try adding a jQuery selector to your load call:
$("#queryresultsblock").load(url + " #test");
You can't put unescaped HTML inside of XML. There are two options I see as good ways to go.
One way is to send escaped HTML in the XML, then have some JavaScript on the client side unescape that HTML. So you would send
<results><results><table....
And the javascript would convert the < to < and such.
The other option, and what I would do, is to use JSON instead of XML.
{'results': "<table id="test"><tr>test</tr></table>" }
The JavaScript should be able to extract that HTML structure as a string and insert it directly into your page without any sort of escaping or unescaping.
The other thing you could do is create an external .html file with just your HTML code snippet in it. So create include.html with
<results><table id="test"><tr>test</tr></table></results>
As the contents, then use a jquery .load function to get it onto the page. See it in action here.

Categories