I have a header.html and header.js files because I want to use the same header through my webpages.
In header.js file, on window load I want it to console.log("header file loaded").
I also have index.html and index.js file for my homepage. In index.js, on window load I want it to console.log("index file loaded")
I called header.html in index.html file, in order to import the header for the homepage. This works fine.
based on js files the console output should
header file loaded
index file loaded
The problem I am having is that
it seems like header.js and index.js cannot work simultaneously
only the last referenced file gets outputed in the console
for example this format
<script src="js/header.js"></script>
<script src="js/index.js"></script>
will output
index file loaded
and this
<script src="js/index.js"></script>
<script src="js/header.js"></script>
will output
header file loaded
I use the code to import header.html in index.html
<head>
<div data-include="header"></div>
</head>
<body>
<script>
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var file = $(this).data('include') + '.html';
$(this).load(file);
});
});
</script>
</body>
this is the content of both js file
function retrieveInfo(data) {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/Sellers/' + userId).once('value').then(function(snapshot) {
console.log(userId)
console.log("index file loaded")
});
}
})
}
what am I doing wrong and how can I fix it to have both js file called?
You are doing it in a wrong way, .load() is used for loading HTML contents. You should be using .getScript(), to load the js and execute it.
According to docs:
.load()
Load data from the server and place the returned HTML into the matched element.
.getScript()
Load a JavaScript file from the server using a GET HTTP request, then execute it.
Here is an example for using getScript:
$.ajax({
url: url,
dataType: "script",
success: function() {
alert("script loaded");
}
});
In your case it would be:
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var JS = $(this).data('include') + '.js';
var file = $(this).data('include') + '.html';
$(this).load(file);
$.ajax({
url: JS,
dataType: "script",
success: function() {
alert(file + " loaded");
}
});
});
});
Related
I'm using summernote html text editor on my site. I want to download images to my server when user put an image url to Image URL area then press to Insert Image button.
Currently summernote only get image's source for src attribute. I want to store images on my own Amazon S3 Bucket or VPS.
There are many docs about summernote image upload but all of them for upload from pc not from URL.
How can I overwrite this feature?
Image dialog
So since you are not able to read dataUrl of cross-origin images in your client-side script the decision is to get url from Image URL area and send it to your backend. There you may use a simple php script to download the image.
The example includes both client and backend codes. Both tested. All you need is to put these two scripts to one of your web server's directories and give it a try.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Summernote</title>
<!-- include libraries(jQuery, bootstrap) -->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.js"></script>
</head>
<body>
<div id="summernote">Hello Summernote</div>
<script type="text/javascript">
$(document).ready(function() {
$('#summernote').summernote();
$('button[data-original-title="Picture"]').click(function(){
// Set handler on Inset Image button when dialog window is opened
$('.modal-dialog .note-image-btn').one('click', function(e) {
// Get Image URL area
var imageUrl = $('.modal-dialog .note-image-url').val();
// Send it to your backend
$.ajax({
url: "image_loader.php",
data: "url="+imageUrl,
type: "POST",
dataType: 'json'
}).success(function(data) {
if (typeof data[0] === 'string') {
$('img[src="'+imageUrl+'"]').attr('src', data);
} else {
// What to do if image downloading failed
window.alert('oops');
}
}).error(function() {
// What to do if ajax request failed
window.alert('oops');
});
});
});
});
</script>
</body>
</html>
image_loader.php
<?php
if ($_POST['url']) {
// Here you'd better put some logic to check that $_POST['url'] is a correct url before use it
$image = file_get_contents($_POST['url']);
if ($image) {
// Put downloaded image on your server
$file = fopen('imagename.jpeg', 'w');
fwrite($file, $image);
fclose($file);
}
/**
* Now your code needs to echo one of the following:
* string Url of an uploaded image on your server
* bool False if it failed
*
* To avoid bool to string conversion during output response needs to be sent as JSON
*/
$response = ($image) ? array('/PATH_TO_IMAGE_DIRECTORY_IF_NEEDED/imagename.jpeg') : array(false);
echo json_encode($response);
}
For example with this image https://imgsnap.com/images/2015/02/23/abstract_0005.jpg
UPDATE (to your comment about img styling)
Put the following line in summernote.js to trigger a special event when image url has been handled by the editor.
$(document).trigger('imageUrlInserted', src);
Put it on line 4095 (according to my version of file) inside of insertImage() method before
$image.css('width', Math.min($editable.width(), $image.width()));
Now in index.php inside of
$('.modal-dialog .note-image-btn').one('click', function(e) {
...
...
});
replace all the code with this
// Get Image URL area
var imageUrl = $('.modal-dialog .note-image-url').val();
// Send it to your backend after the image been handled by the editor
$(document).on('imageUrlInserted', function(e, sourceUrl) {
if (sourceUrl === imageUrl) {
$.ajax({
url: "image_loader.php",
data: "url="+imageUrl,
type: "POST",
dataType: 'json'
}).success(function(data) {
if (typeof data[0] === 'string') {
$('img[src="'+imageUrl+'"]').attr('src', data).removeAttr('style');
} else {
// What to do if image downloading failed
window.alert('oops');
}
}).error(function() {
// What to do if ajax request failed
window.alert('oops');
});
}
});
I have:
test.json - contains the content to be uploaded into the HTML page
test.js - contains the function that sends an Ajax request to the JSON file, parses, compiles with Handelbars Temlate and puts the content into the HTML page (using innerHTTML).
addcontent.js - javascript file which calls the function from the test.js file
index.html - contains the Handlebars Template, Div
where the content will be placed after processing, and a link to the
addcontent.js.
Everything works, if inside index.html there is a link directly to test.js.
Everything works if I wrap the code inside test.js in a function with variables and call this function in the same file.
But if I call this function from addcontent.js and connecting addcontent.js and test.js using commonJS module approach, it does not work.
Probably I made a syntax mistake somewhere, but I don't see it.
P.S. I use NodeJS, NPM, HTTP-server and I'm going to merge all javascript files using browserify after all
//test.js
module.exports = function addContent (jsonDir, templId, finId){
function sendGet(callback) {
/* create an AJAX request using XMLHttpRequest*/
var xhr = new XMLHttpRequest();
/*reference json url taken from: http://www.jsontest.com/*/
/* Specify the type of request by using XMLHttpRequest "open",
here 'GET'(argument one) refers to request type
"http://date.jsontest.com/" (argument two) refers to JSON file location*/
xhr.open('GET', jsonDir);
/*Using onload event handler you can check status of your request*/
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};
/*Using onerror event handler you can check error state, if your request failed to get the data*/
xhr.onerror = function () {
alert("Network Error");
};
/*send the request to server*/
xhr.send();
}
//For template-1
var dateTemplate = document.getElementById(templId).innerHTML;
var template = Handlebars.compile(dateTemplate);
sendGet(function (response) {
document.getElementById(finId).innerHTML += template(response);
})
}
/* test.json */
{
"time": "03:47:36 PM",
"milliseconds_since_epoch": 1471794456318,
"date": "08-21-2016-123",
"test": "lalala 123"
}
/* addcontent.js */
var addContent = require('./test');
addContent("json/test.json", "date-template", 'testData');
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="handlebars-v4.0.5(2).js"></script>
</head>
<body>
<!-- template-1 -->
<div id="testData"></div>
<script id="date-template" type="text/x-handlebars-template">
Date:<span> <b>{{date}}</b> </span> <br/> Time: <span><b>{{time}}</b>
</span>
</script>
<script type="text/javascript" src="addcontext.js"></script>
</body>
</html>
I have a script file called trim.js. I'm trying to call a function prepareURL() from this file in my index.html file. However I'm getting the following error:
ReferenceError: Can't find variable: prepareURL
I make sure to import my script doing the following:
<script type="text/javascript" src="./js/trim.js">
</script>
<script type="text/javascript">
$(function() {
$('#simple_sketch').sketch();
$('#simple_sketch').sketch('color','#fff');
$('#simple_sketch').sketch('size','6');
});
function predict() {
//Create Image URL
var imageURL = prepareURL('#simple_sketch')
}
The function in my trim.js file looks like this:
function prepareURL(c) {
//My code
}
How can I call prepareURL from my index.html file?
I just want to export a webpage loaded inside an iFrame. But I want to have action from an outer iFrame.
Here's my code to clarify things:
<html>
<body>
some contents here....
<div id="main">
<iframe id="myiframe" src="template/index.html"></iframe>
</div>
Export
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
function downloadInnerHtml(filename, elId, mimeType) {
var elHtml = document.getElementById(elId).innerHTML;
var link = document.createElement('a');
mimeType = mimeType || 'text/plain';
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
link.click();
}
var fileName = 'newlstter.html';
$('#downloadLink').click(function(){
downloadInnerHtml(fileName, 'main','text/html');
});
});
</script>
</body>
</html>
When I click the export button the HTML file is exported and it will include the iFrame. But if I use these codes inside the inner HTML file it will export.
But I need to export that current HTML page from the outter site. Exactly like my code above. But I just want to export only the inner HTML.
Can any one give me some suggestion for this?
Note: Please I need jQuery or JS code, not PHP.
Thanks!
I suggest using an AJAX; the following fiddle returns just the HTML that you need: https://jsfiddle.net/yLL48one/2/
$.get( "/yLL48one/1/", function( data ) {
console.log( data );
});
Before, I had this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var optPrompt = "- Select One -";
var subCats;
var parentCats;
var nextBtn;
var ParentChanged = function() {
ClearDescription();
if (this.selectedIndex == 0) {
$(subCats).html($("<option>").text(optPrompt));
}
$.getJSON('<%=Url.Action("GetChildCategories") %>', { parentId: $(this).val() },
function(data) {
subCats.options.length = 0;
$("<option>").text(optPrompt).appendTo(subCats);
$(data).each(function() {
$("<option>").attr("value", this.ID).text(this.Name).appendTo(subCats);
});
});
}
var DisplayDescription = function(catId) {
$.ajax({
url: '<%=Url.Action("GetDescription") %>',
data: { categoryId: catId },
dataType: 'html',
success: function(data) {
$("p#categoryDescription").html(data);
}
});
}
var ChildChanged = function() {
var catSelected = this.selectedIndex != 0;
if (!catSelected) ClearDescription();
else DisplayDescription($(this).val());
}
var ClearDescription = function() {
$("p#categoryDescription").html('');
}
$(function() {
parentCats = $("select#Category").get(0);
subCats = $("select#Subcategory").get(0);
nextBtn = $("input#nextButton").get(0);
$(parentCats).change(ParentChanged);
$(subCats).change(ChildChanged);
});
</script>
</head>
Then I put all of my inline script into a file (myScript.js) and changed my HTML to this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/Scripts/myScript.js" type="text/javascript"></script>
</head>
And now nothing is working. I opened up my page in IE7 and it had a page error that read:
Line: 54
Error: Unknown name.
Line 54 happens to be the last line of my external javascript file.
What am I doing wrong?
Am I right in saying that this is ASP.Net? If it is, inline scripts like:
<%=Url.Action("GetDescription") %>
cannot go in the external JavaScript file.
Did you put the < script > tag inside your myScript.js? If yes, remove them.
Your myScript.js should start with
var optPrompt = "- Select One -";
Since you are now serving the js as a static file, rather than via your ASP, lines like
<%=Url.Action("GetChildCategories") %>
will no longer work as the server doesn't interpret them and replace them with the correct values. You'll need to hard-code them in the script, or leave those lines as inline scripts in the main page and set them as global variables which you can then reference from the external file.