Change CSS font-face dynamically with JavaScript/JQuery - javascript

I'm trying to develop a code that is able to change the font of an element dynamically by using a font file (TTF) uploaded. The code below works fine in Chrome, Opera and Firefox, but doesn't work in IE, Edge and Safari.
<html>
<head>
<style>
#my-font {
margin-top: 50px;
font-size: 20pt;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(function(){
$("#font").change(function(){
// post the font file to the php script that will move the file uploaded to the folder "fonts"
$.ajax( {
url: 'movefontfile.php',
type: 'POST',
data: new FormData($("#send")[0]),
processData: false,
contentType: false,
}).done(function(name){
// set the font face
var f = new FontFace("myfont", "url(fonts/"+name+")", {});
f.load().then(function (loadedFace) {
document.fonts.add(loadedFace);
var fptags = document.getElementById('my-font');
fptags.style.fontFamily = "myfont, sans-serif";
});
});
})
});
</script>
</head>
<body>
<form id="send">
<input type="file" id="font" name="font">
</form>
<p id="my-font">
This is a font text
</p>
</body>
</html>
This is the php code:
<?php
$name = $_FILES['font']['name'];
move_uploaded_file($_FILES['font']['tmp_name'], 'fonts/'.$name);
echo $name;
?>
Someone could help me? I need a code that works in every popular browser. Thanks.

IE and Edge don't have support for the JavaScript FontFace object. You might have better luck dynamically creating the CSS #font-face code, like so:
$.ajax( {
url: 'movefontfile.php',
type: 'POST',
data: new FormData($("#send")[0]),
processData: false,
contentType: false,
}).done(function(data){
$('<style>').text("#font-face {font-family: 'myfont'; src: url('fonts/myfont.ttf');}");
var fptags = document.getElementById('my-font');
fptags.style.fontFamily = "myfont, sans-serif";
});

Try to use the browser debugger by pressing F12 key and check the font on the <p> tag.
<p id="my-font">
Fix it on console window and update your code accordingly.

I find a solution that works in Safari and Edge, but doesn't works to IE yet.
It is very ugly, but works:
<html>
<head>
<style>
#my-font {
margin-top: 50px;
font-size: 20pt;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var font;
$(function(){
$("#font").change(function(){
// post the font file to the php script that will move the file uploaded to the folder "fonts"
$.ajax( {
url: 'movefontfile.php',
type: 'POST',
data: new FormData($("#send")[0]),
processData: false,
contentType: false,
}).done(function(data){
$('link[rel=stylesheet][href="'+font+'.css"]').remove();
font = data;
$('head').append('<link rel="stylesheet" type="text/css" href="'+data+'.css">');
$('#my-font').css('font-family', 'myfont, sans-serif');
});
})
});
</script>
</head>
<body>
<form id="send">
<input type="file" id="font" name="font">
</form>
<p id="my-font">
This is a font text
</p>
</body>
</html>
And the PHP script:
<?php
$name = $_FILES['font']['name'];
move_uploaded_file($_FILES['font']['tmp_name'], 'fonts/'.$name);
$css = file_get_contents('font-face-aux.css');
$css = str_replace('?FONT_NAME?', $name, $css);
$f = fopen($name.'.css', 'w');
fwrite($f, $css);
fclose($f);
echo $name;
?>
And the auxiliar CSS:
#font-face {
font-family: 'myfont';
src: url('fonts/?FONT_NAME?');
}

Related

How to write data to a text file using javascript without ActiveXObject?

I need to store data in server-side.I tried to make an Ajax call to PHP:
upload.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<style>
#test{
padding:20px 50px;
background:#ccc;
color:#000;
}
</style>
<script>
$(function(){
$('#test').click(function(){
$.ajax({
url: "http://localhost:8012/myFolder/upload.php",
type : 'POST',
data: {"foo": "bar"},
processData: false,
contentType: 'application/json'
});
});
});
</script>
</head>
<body>
<button id="test">KLICK</button>
</body>
</html>
upload.php:
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fwrite($fh,$_POST['data']);
fwrite($fh,$_POST['foo']);
fwrite($fh,$_POST["foo"]);
fwrite($fh,$_POST[foo]);
fclose($fh);
?>
but It doesn't work.The data is not wrriten to testFile.txt.
I will appreciate your help.
Thanks in advance.
No, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least.
If you wanted to get/store information server-side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc. script that can then get/store the data in the server. If you meant store data on the client machine, this is impossible with JavaScript alone.
If you are only trying to store a small amount of information for an unreliable period of time regarding a specific user, I think you want cookies.
Updated:
Below is a simple code that you are looking for. There is a simple form with four fields. On clicking of submit, it calls the server file and that PHP file will have the code to write the data to a file.
$("#submit").click(function(){
var paramsToSend = {};
var i = 1;
$("input[name='myanswer[]']").each(function(){
paramsToSend[i] = $(this).val();
i++;
});
$("#dataToSend").html(JSON.stringify(paramsToSend));
$.ajax({
type: "POST",
url: 'URL_HERE/post.php',
data: {params:JSON.stringify(paramsToSend)},
success: function(data) {
console.log("SUCCESS!!!");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputsl">
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
</div>
<button id="submit">
Submit
</button>
<div id="dataToSend"></div>
PHP code can be:
file_put_contents('filename.txt', $_POST['params']);

After including page I am facing ajax error (Not Found)

I am working on notification system. So I am following this blog (http://www.phptutorials.club/ajax-notification-in-php-with-example/).
Please see the code.
It's working fine and it's giving me a notification, but the problem is if I include the page in another index.php page, then it's giving me (error (Not Found).
I renamed the index.php as notification.php and I am including it on my website index.php page. So after including it's giving me an error but without including it's working fine.
Please suggest I know PHP but don't know about ajax and jquery,js.
Please see my code below.
notification.php
<style>
#notification_count {
padding: 0px 3px 3px 7px;
background: #cc0000;
color: #ffffff;
font-weight: bold;
margin-left: 77px;
border-radius: 9px;
-moz-border-radius: 9px;
-webkit-border-radius: 9px;
position: absolute;
margin-top: -1px;
font-size: 10px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
function addmsg(type, msg) {
$('#notification_count').html(msg);
}
function waitForMsg() {
$.ajax({
type: "GET",
url: "select.php",
async: true,
cache: false,
timeout: 50000,
success: function(data) {
addmsg("new", data);
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
};
$(document).ready(function() {
waitForMsg();
});
</script>
<span id="notification_count"></span>
Notifications
<div id="HTMLnoti" style="textalign:center"></div>
<script>
</script>
select.php
<?php include "../../includes/db.php" ?>
<?php
$sql = "SELECT * from comments where comment_status = 'unapproved'";
global $connection;
$select_comments= mysqli_query($connection, $sql) or die('Could not look up user information; ' . mysqli_error($connection));
$count = mysqli_num_rows($select_comments);
echo $count;
mysqli_close($connection);
?>
So after including the notification.php file in index.php.it's giving me an error.
But without including this file. it's working fine.
<!-- Notification panel-->
<?php include "../includes/notification.php" ?>
First check if your include path is correct. Try:
<?php include "../../includes/notification.php" ?>
Additionally, check the path to select.php in your ajax call
$.ajax({
type: "GET",
url: "select.php",
...
Second, you should think about splitting notification.php into three parts:
put CSS into main .css file
JavaScript code should be in notification.js
HTML code you can leave in notification.php
Then include notification.php in the index.php after you have included .css and .js files.

how to include js file using script tag in jquery codes?

I want to include js file in jQuery scripts, when data is fetched from database using $.ajax and do something without refreshing the page
for example:
$.ajax({
type: 'POST',
url: "content.php",
data: {vals: "value"},
success : function(response) {
$(body).append(response)
showScrollStyle();
}
});
function showScrollStyle() {
// here should include 3 js file for change scroll style
}
response will show a div with 500px height and width that have overflow:auto; style and if text of div will be more than of 500px; vertical scroll will be show automatially, I have 3 js file that I should include there for change scroll styles and type.
I tried $.getScrpit() function but it will refresh the page and will show just a white page.
how can I do this? thank you
EDIT 1:
I created some codes that i think can explain what i want
HTML CODE
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="jquery.mCustomScrollbar.concat.min.js"></script>
<script>
$(document).ready(function(e) {
textScroll()
function textScroll() {
$.ajax({
type: 'POST',
url: "content.php",
data: {val: "text_div"},
success : function(response) {
$("body").append(response);
showScrollStyle()
}
});
}
});
function showScrollStyle() {
// jquery.mCustomScrollbar.concat.min.js should import in here for work with new elemnts
}
</script>
<link rel="stylesheet" href="style/scroll_style.css">
<style>
body {
background-color:#369;
}
</style>
</head>
<body>
</body>
</html>
PHP CODE
<?php
include 'Connections.php'; // connect to database
$val = $_POST['val'];
$query = "SELECT contains FROM textarea WHERE name='".$val."' LIMIT 1";
// echo $query;
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row['contains'];
}
}
else
{
echo $mysqli->error;
}
?>
SOMETHING STORED IN textarea TABLE
<div style=" display:inline-block; margin:auto; width:800px; height:400px; overflow:auto;" id="rulesScroll" class="font c_blue_dark mCustomScrollbar interfo_section">
<span style=" display:inline-block; margin:30px; font-size:44px;" id="newsContain">
text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
</span>
</div>
Note: if you need to jquery.mCustomScrollbar.concat.min.js you can download scroll bar plugIn in here http://manos.malihu.gr/jquery-custom-content-scroller/
I have used $.getScript function and it is working fine for me. Have you used function in right way? Please check below code.
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getScript demo</title>
<style>
.block {
background-color: blue;
width: 150px;
height: 70px;
margin: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body id="body">
<button onclick="load()" id="load">» Load</button>
<button id="go">» Run</button>
<div class="block"></div>
<script>
function load()
{
$.ajax({
type: 'GET',
url: "/search",
data: {vals: "value"},
success : function(response) {
$("#body").append(response);
showScrollStyle();
}
});
}
function showScrollStyle() {
// here should include 3 js file for change scroll style
var url = "https://code.jquery.com/color/jquery.color.js";
$.getScript( url, function()
{
$( "#go" ).click(function() {
$( ".block" )
.animate({
backgroundColor: "rgb(255, 180, 180)"
}, 1000 )
.delay( 500 )
.animate({
backgroundColor: "olive"
}, 1000 )
.delay( 500 )
.animate({
backgroundColor: "#00f"
}, 1000 );
});
});
}
</script>
</body>
</html>
This code is not refreshing the page.

I'm getting corrupted image when converting base64 image using webcam.js

here's my html with javascript using webcam.js. I just followed the https://github.com/jhuckaby/webcamjs on how you will implement it using existing form.
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="../webcam.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
Webcam.snap( function(data_uri) {
var raw_image_data = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
document.getElementById('mydata').value = raw_image_data;
document.getElementById('myform').submit();
} );
</script>
<!-- A button for taking snaps -->
<form id="myform" method="post" action="myscript.php">
<input id="mydata" type="hidden" name="mydata" value=""/>
<input type=button value="Take Snapshot" onClick="take_snapshot()">
<input type="submit" value="submit">
</form>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="'+data_uri+'"/>';
} );
}
</script>
here's the myscript.php to save the image. I successfully save the PATH in the database but I'm getting a corrupted .jpg file (file size always in 7 bytes).
<?php
include 'connect.php';
$encoded_data = $_POST['mydata']; // to get the base 64 code image link
$name = base64_decode($encoded_data); // to convert base 64 code
$name = date('YmdHis');
$newname="images/".$name.".jpg";
$file = file_put_contents( $newname, file_get_contents('php://input') );
if (!$file) {
print "Error occured here";
exit();
}
else
{
$sql="INSERT INTO image (images) VALUES('$newname')";
$result=mysqli_query($con,$sql);
$value=mysqli_insert_id($con);
$_SESSION["myvalue"]=$value;
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $newname;
print "$url\n";
?>
After all the trail and errors i found out you'll need to convert the base64 string to a blob and then attach to a file before sending.
var binaryImg = atob(base64string);
var length = binaryImg.length;
var ab = new ArrayBuffer(length);
var ua = new Uint8Array(ab);
for (var i = 0; i < length; i++) {
ua[i] = binaryImg.charCodeAt(i);
}
var blob = new Blob([ab], {
type: "image/jpeg"
});enter code here
var imgFile = new File([blob], 'photo.jpeg', {type: 'image/jpeg'});
Now you can use the imgFile to send across to a remote server.

Broken code -- How do I properly use AJAX to prevent this section of website from loading?

I closely followed an AJAX tutorial ( https://www.youtube.com/watch?v=WwngGtboldU ) to learn how to prevent certain sections of a website from loading. You can see at 17:50 he clicks the links and, rather than the entire page loading, only a certain section loads in.
However, it's simply not working for me. When I click "Cats" or "Dogs", the entire page loads. It's very frustrating! Could anyone figure out what might be going wrong in my version? I've been using XAMPP, by the way, and I always test this by opening cats.php or dogs.php.
style.css
body{
background-color: aqua;
}
ul#nav {
list-style:none;
padding:0;
margin: 0 0 10px 0;
}
ul#nav li {
display:inline;
margin-right:10px;
}
header.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>History API</title>
</head>
<body>
<nav id="main">
<ul>
<li>Cats</li>
<li>Dogs</li>
</ul>
</nav>
footer.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var nav, content, fetchAndInsert;
nav = $('nav#main');
content = $('section#content');
//Fetches and inserts content into the container
fetchAndInsert = function(href) {
$.ajax({
url: 'http://localhost/BlankApacheHistoryAPI/content' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data){
content.html(data);
}
});
});
//User goes back/forward
$(window).on('popstate', function() {
fetchAndInsert(location.pathname);
});
nav.find('a').on('click', function(e) {
var href = $(this).attr('href');
//Manipulate history
history.pushState(null, null, href);
//Fetch and insert content
fetchAndInsert(href);
e.preventDefault();
});
});
</script>
</body>
</html>
cats.php
<?php
require 'views/header.php';
?>
<section id="content">
<?php require 'content/cats.php'; ?>
</section>
<?php
require 'views/footer.php';
?>
content/cats.php
Cats say meow
dogs.php
<?php
require 'views/header.php';
?>
<section id="content">
<?php require 'content/dogs.php'; ?>
</section>
<?php
require 'views/footer.php';
?>
content/dogs.php
Dogs say woof
I think you are missing the last forward slash:
url: 'http://localhost/BlankApacheHistoryAPI/content' + href.split('/').pop(),
should be
url: 'http://localhost/BlankApacheHistoryAPI/content/' + href.split('/').pop(),
At the end of your fetchAndInsert = function(href) you wrote }); while in fact the paranthesis should be there. Change it to }; (hint: check your developer console (F12) to see any error messages)
Remove history.pushState(null, null, href); - it's actually redirecting you to the link ("the entire page loads")

Categories