I need an advice how to dynamically change HTML data.
My web page will have some form, which will call a PHP function, which I am planing to return JSON array (I can accept also other output, except raw HTML).
Than i want the page content to be replaced with the JSON values.
The idea of that is to have the HTML code separated from the PHP function.
Can you please tell me if this is a good practice and if yes, can you please give me some example ?
Thanks in advice !
Yes it is actually a good practice - I do this every day .
See the web is fast advancing and the more we separate concerns the more flexible we get . Now here are the facts :
With the introduction of Progressive Web Apps , creating an app shell
(Basically a skeleton of the website without data) is recommended so
that new data is loaded from ajax/fetch see this link
Imagine when you want to do a tv version of your website/webapp - you
will only need to create an app shell where the JSON data will be
used to fill in the data
I advocate for separation of concerns since it will be much easier to add more platform & device support since you will only be worried about the template / shell and not the data
Here is an example :
filename/url : localhost:8080/index.php
<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
?>
Then on the client side
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
#userInfo{
height: 100px;
float: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="userInfo"></div>
<script>
(function() {
var myUrl = "https://localhost:8080/index.php";
$.getJSON( myUrl)
.done(function( data ) {
/*
{"name":"John","age":30,"city":"New York"}
*/
var userInfo = document.getElementById('userInfo');
userInfo.innerHTML = '<p>Name :'+ data.name +'</p>
<p>Age:'+ data.age+'</p>
<p>City:'+ data.city+'</p>';
});
})();
</script>
</body>
</html>
Related
I have some routine task (change some column types in MSSQL) on multiple server.
So, I'm trying to make a script program that connects to MSSQL and change structure of some tables.
What I've done so far...
I made a text file on Desktop and wrote the code below in the file
<!DOCTYPE html>
<html>
<head>
<script>
var objConnection = new ActiveXObject("adodb.connection");
var strConn = "driver={sql server};server=192.168.139.121;database=mytest;uid=testuser;password=testpw";
objConnection.Open(strConn);
var rs = new ActiveXObject("ADODB.Recordset");
(queries for changing table structure)..
</script>
</head>
<body>
</body>
After that, I saved it as HTML file and executed it with Internet Explorer.
But, No response.. I found that after executing 'objConnection.Open(strConn);' IE waits for response forever.. Is there any library or program to be installed to execute all the code above? please give me some hints
You can try this (Works only in IE) :
<!DOCTYPE html>
<html>
<head>
<script>
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";
connection.Open(connectionstring);
//your queries here
rs.close;
connection.close;
</script>
</head>
<body>
</body>
</html>
You really shouldn´t use client side script like javascript to access databases for several reasons like bad practice, security issues etc. You can use .Net, PHP, JAVA etc which are server side language and better way to use these to interact with the databases.
I am currently testing DOMPDF and got it working quite nice for my purposes, including CSS styling, displaying content fetched from a mysql database etc.
Now I tried to use some Javascript, but it doesn't work. I used a very simple script for testing:
HTML somewhere on the page:
<div id='mydiv1' style='width: 100%;height:20px;background:#ddd;'></div>
The JS (just above the closing </body> tag (but I also tried it right after the opening <body> tag):
<script>
document.getElementById('mydiv1').innerHTML = 'this is a test';
</script>
When I echo this page in the browser (I am echoing a variable which contains the complete HTML/PHP page), that text appears in the DIV. When I put the same variable in DOMPDF's loadHtml and then render and output it, the script-generated text doesn't appear in the PDF (the rest of the page does).
So my question is: Is there any way to make Javascript work in DOMPDF-generated PDFs?
Unfortunately, DOMPDF doesn't support javascript. You may consider looking at something like phantomjs, which can be used to save pdf files, as well.
There is a DomPDF option to turn on inline javascript:
$isJavascriptEnabled = true;
Heres an example of how to use the DomPDF options:
$HTML = <<<HTML
!DOCTYPE html>
<html>
<head>
<body>
some html
</body>
<script> somejs </script>
</head>
</html>
HTML;
require_once "sites/all/libraries/dompdf/autoload.inc.php";
use Dompdf\Dompdf;
use Dompdf\Options;
$options = new Options();
$options->set('isJavascriptEnabled', TRUE);
$dompdf = new Dompdf($options);
$dompdf->load_html($HTML);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream('blah.pdf');
I took this from DomPDF's options page: https://github.com/dompdf/dompdf/blob/master/src/Options.php
I am having difficulty with a specific JQuery $.post call to a PHP-based processor. I created a test page with the code below located here: http://goo.gl/Bg7H2u
Note this is located on a subdomain, but we are not doing cross-domain posting. Everything should be included on the subdomain.
There do not seem to be any JS errors as reported in the error console.
The processor /get-data.html is the general purpose PHP processor, and, if you load the processor page with the right value, it returns a dataset from the MySQL database in JSON format. We have this working on the main domain without issue, and other $.post calls seem to work OK from this subdomain (not to this /get-data.html processor, but other processors that process form content).
See the actual processor output here: http://goo.gl/yOzrm2
I must be missing something obvious, but I am coming up empty. Thoughts?
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=320px, initial-scale=1">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var prices;
$(document).ready(function(){
$.post( "/get-data.html", { table: 'prices' },
function( data ) {
prices = data;
alert(prices);
}, 'json');
});
</script>
</head>
<body>
<div style="overflow-x: hidden;" id="divMain">
</div>
</body>
</html>
Thanks for any advice you can provide.
If you do View Source on the processor output, you'll see that your script is returning:
<p>{"Basic Plan":["349"],"Basic":["349"],"Premium Plan":["549"],"Premium":["549"],"Standard Plan":["429"],"Standard":["429"],"Bonus Plan":["175"],"Additional Central AC System":["99"],"Additional central heating system":["99"],"Central Vacuum":["99"],"Whole home humidifier":["49"],"Pool (in-ground)":["179"],"Spa (in-ground)":["179"],"Septic System":["99"],"Sump Pump":["99"],"Well pump":["99"],"Whole home water softener":["99"],"Lawn sprinkler system (in-ground)":["99"],"Wine refrigerator":["49"],"Ice maker (free standing)":["49"],"Home phone (unlimited)":["49"],"TV Protection (Flat screen up to 60 inches)":["99"],"PC Protection (laptop or desktop)":["49"]}</p>
There's <p> at the beginning and </p> at the end. This is not valid JSON. You need to fix the server script so that it doesn't print anything other than the JSON (whitespace is OK, that's it).
1.confirm that /get-data.html is the correct relational url for your file location.
If you navigate directly to the /get-data.html, does it produce the results that you are after.
try running the same code without , 'json' and see if it works.
hope this helps
I have java script file that reads in a csv file, and has many functions to to visualize the data differently, using d3. I want each visualization to be displayed in different html pages. Ive made every html page, refer to the javascript file. Each page also has its own script that calls functions from the referred javascript file.
The problem, I am facing is that when ever I go to a new page, the function gets called before the data being read. Only works when refreshing the page. I there a way to just read the data in once, and every page can access it.
If you look at the code below, callingFunction() returns undefined (maybe because data is not stored in var data?) The callingFunction() works fine when the page is refreshed.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>D3</title>
**<script src="my.js"></script>** //my script file
</head>
<body>
<script>
callFunction(); //uses var data defined in my.js
</script>
Here is the "my.js":
var data;
function data(file){d3.csv("file", function (error, data) {
ds = data;
callFunction();
}
load your script after the target DOM :
<canvas></canvas>
...........................
<script type="text/javascript"></script>
Use angularJs Js library: it organize your js code according to MVC design pattern.
If you have more than one method to implement a business logic , Use console.time & console.timeEnd to evaluate code performance .
console.time('anID');
// Here your code
console.timeEnd('anID');
We all know what <script src="/something.js"></script> does. That file is loaded in the page and the script is run.
Is there any way to override the default behaviour of interpreting <script> elements?
I want the same syntax (<script src='...'></script>) that will only get the code from something.js (probably via XHR/jQuery ajax) and pass it to a foo (...) {...} function. Then I will care what I will do with it.
To clarify the problem:
I can easily create a pseudo <script> tag alternative using:
<div data-script-src="/1.js"></div>
<div data-script-src="/2.js"></div>
<div data-script-src="/3.js"></div>
<div data-script-src="/4.js"></div>
And then in the js side I would do:
var $scripts = $("[data-script-src]")
, scriptContents = [];
(function loadInOrder (i) {
if (!$scripts[i]) { alert("Loaded"); }
$.ajax($($scripts[i]).attr("data-script-src"), function (data) {
scriptContents[i] = data;
loadInOrder(++i);
});
})(0);
But how can I replace div[data-script] with <script>? How can I force the browser NOT to load the <script> tags that have the attribute data-load="false", for example?
I think your best bet here is to use onbeforescriptexecute. This event fires right before the script executes, so you can then modify the type attribute to something other than text/javascript (thus telling the browser not to execute the contents). This will still load the data from the server.
Unfortunately, onbeforescriptexecute is only supported in FF/Opera.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script>
document.addEventListener("beforescriptexecute", function (e) {
console.log(e.target.innerHTML || e.target.src);
}, true);
</script>
<script>
console.log("12");
</script>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
Hi
</body>
</html>
The console output will be:
'console.log("12")'
'http://code.jquery.com/jquery-1.10.2.min.js'
Create Your own PHP file, which will work as a kind of a gate. Then
<?php
$file = file_get_contents(your_url);
$file = str_replace('<script', '<myscript', $file);
$file = str_replace('</script>', '</myscript>', $file);
echo $file;
?>
And then if needed add Your type of real script that will search for myscript tags and run Javascript code...
You can use div element as well (if scripts are loaded in body, and You need validation):
substitute: '<script' -> '<div data-id="my-script" '
substitute: '<script' -> '</div>'
PS. I don't know if these are Your sites or sites from internet, that You want the default behaviour to be overwritten. So always be careful of what You are "file_getting_contents" because, this will be echoed directly to Your browser.