I'm making a website which must be as lightweight as possible. There is a portion of javascript code I want to turn into a module using a separate file, so the code will be loaded after a certain onClick event.
I can successfully load the javascript code:
var myscript = document.createElement('script');
myscript.src = "modules/mymodule.js";
document.head.appendChild(myscript);
My problem is that my javascript code has some language-dependent variables that I generate php. Is there a way of running php on my javascript file prior to dynamic loading, or is it too late? Maybe using AJAX?
For people who look at this answer; please do not do this. Only run PHP files through the PHP interpreter. Doing this is an unnecessary security risk.
Depending on your web server, running PHP on JavaScript files is as simple as changing your webserver config.
Follow the instructions in this link: http://www.plus2net.com/php_tutorial/php5-iis7-configuration.php
However, when it prompts you to enter *.php, enter *.js.
By doing so, all your JavaScript files will be run through the PHP interpreter.
I think you must send your variable names and some date to your php doc.
then manipulate these variable names in your code then generate the right javascript code.
you should use AJAX to send your variable names .
You could just render it in PHP, then load it in as a JavaScript file.
MyScript.php
<?php
$number = 5;
echo "var number = {$number}"
?>
index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function loadScript(url){
$.getScript( "MyScript.php", function( data, textStatus, jqxhr ) {
console.log( number ); // 5
});
}
</script>
</head>
</html>
Related
I am trying to save a variable for counting the views of my personal website, I dont need to use php because its literally a viewcount. I know how to retrieve the count from the server using $.post, but how would I retrieve it (Edit: In the simplest way possible.)?
The website I'm trying to do it with is http://artsicleprojects.com/
Thanks in advance!
You will need PHP for this question, because it is dealing with server-side actions. First, you need to make a server-side script to increment the text file's number. Then, you will need to make a client-side script to make a request to the server. This script increments a number in the text file every time the request is made. Anyway, here's how I would do it (Note: this code is un-tested):
PHP:
<?php
/*Reads and collects current count.*/
$rfile = fopen("views.txt", "r") or die("Unable to open file!");
$count = fread($rfile,filesize("views.txt"));
fclose($rfile);
/*Increments the count.*/
$wfile = fopen("views.txt", "w");
$ncount = $count + 1;
fwrite($wfile, $ncount);
fclose($wfile);
?>
Note on code: for this code to work correctly, you may need a text file already made (views.txt), in the same directory as the PHP script, with a single "0" written in it.
JavaScript (with jQuery):
$.post("phpscript.php", function(data, status){
console.log(status);
});
This also is supposed to be in the same directory as the script to work.
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 2 years ago.
How do I pass have a Javascript script request a PHP page and pass data to it? How do I then have the PHP script pass data back to the Javascript script?
client.js:
data = {tohex: 4919, sum: [1, 3, 5]};
// how would this script pass data to server.php and access the response?
server.php:
$tohex = ... ; // How would this be set to data.tohex?
$sum = ...; // How would this be set to data.sum?
// How would this be sent to client.js?
array(base_convert($tohex, 16), array_sum($sum))
Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.
An example (using traditional event registration model for simplicity):
<!-- headers etc. omitted -->
<script>
function callPHP(params) {
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "get_data.php";
httpc.open("POST", url, true); // sending as POST
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
alert(httpc.responseText); // some processing here, or whatever you want to do with the response
}
};
httpc.send(params);
}
</script>
call PHP script
<!-- rest of document omitted -->
Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)
See also Mozilla's documentation for further examples
I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution:
My simple client side code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<title>Test Page</title>
<script>
function passVal(){
var data = {
fn: "filename",
str: "this_is_a_dummy_test_string"
};
$.post("test.php", data);
}
passVal();
</script>
</head>
<body>
</body>
</html>
And php code on server side:
<?php
$fn = $_POST['fn'];
$str = $_POST['str'];
$file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
echo fwrite($file,$str);
fclose($file);
?>
Hope this works for you and future readers!
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
Using cookies is a easy way. You can use jquery and a pluging as jquery.cookie or create your own.
Using Jquery + jquery.cookie, by example
<script>
var php_value = '<?php echo $php_variable; ?>';
var infobar_active = $.cookie('php_value');
var infobar_alert = any_process(infobar_active);
//set a cookie to readit via php
$.cookie('infobar_alerta', infobar_alerta );
</script>
<?php
var js_value = code to read a cookie
?>
I've found this usefull Server-Side and Hybrid Frameworks:
http://www.phplivex.com/
http://www.ashleyit.com/rs/
I've been using Ashley's RSJS Script to update values in HTML without any problem for a long time until I met JQuery (ajax, load, etc.)
There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.
<script language="javascript" type="text/javascript">
function _vals(target, value){
form1.all("target").value=target;
form1.all("value").value=value;
form1.submit();
}
</script>
Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.
I'm sure there's probably more methods which are better, but these are just a few that spring to mind.
EDIT: Building on this from what others have said using the above method you would have an anchor tag like
<a onclick="_vals('name', 'val')" href="#">My Link</a>
And then in your PHP you can get form data using
$val = $_POST['value'];
So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.
The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax
I've read many articles in this site or other sites (Redirect with POST to application/csv without form, jQuery.post(), PHP and redirects, ... ) but without any valuable solutions.
My problem is the following :
in my site (html5, JQuery), there is a table. A feature of the site
is to export the table as a csv file which will be available for
download,
This feature is implemented as follow :
2.1 a javascript is called which extracts the data of the table,
2.2 this JS redirect to a php service and pass as arguments the datas. The code is the
following :
var url= jmcnet.request.getOrigin()+'/commons/php/dt_csv_export.php' ;
location.href = url+"?action=generate&csv_type=export_task&csv_data=" +encodeURIComponent(csv);
2.3 The php script format the input (csv_data parameter), write a temporay file and returns the content of the temporary file. The code is the following :
$h = #fopen($csv_file_name, 'w');
fputcsv($h, $csv_row, ',', '"');
fclose($h);
// export file content to JS
header('Content-Encoding: UTF-8');
header('Content-Type: text/ csv; charset =UTF-8');
header('Content-Disposition: attachment; filename=export-table.csv');
header(' Pragma: no-cache');
echo "\xEF\xBB\xBF"; // UTF-8 BOM
readfile($csv_file_name);
2.4 The php file delete (unlink) the temporary file and exit,
My problem is that when the table is long, the URL called is not valid and the JS call to Php is down.
So, I imagine the 3 following solutions but no one is evident and all leads to other problems :
S1 : dont do a GET but a POST in JS. So the size of the csv_data
doesn't matter anymore. The problem is that I will have the content
of the csv file in JS var after the call succeed and I don't know or
find how to redirect to a page which content is in a JS var ? I
guess I will lose all header information doing this.
S2 : compress in JS the csv_data parameter and decompress it in Php.
I just don't know how to do that and if it possible ....
S3 : call the php with a POST. Modify the Php to return the URL of
the temporary file, and do a redirect in JS to this temporay URL.
The problems are that my Php must generate a file into a dir
directly visible on the Internet, the file name must be unique and
there is no way to simply delete the file after it has been read by
browser (and I hate cron or what else).
I'm sure I'm not the first one to have this problem, so I need your help to see what is the best practice for this problem.
I think you may be over-complicating this just a bit. There is no need for all of the JS redirect stuff, you can just point your forms action attribute to your csv_export php code and use POST to send your data.
if needed, you can modify the max size of a post request by editing the post_max_size option in your php.ini. heres what mine looks like:
; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size = 8M
as for writing to a temporary file, php has built in I/O streams to handle that. for your purposes you'll probably want to use php://memory or php://temp (more info on those here: http://www.php.net/manual/en/wrappers.php.php)
so you can do something like this:
SAMPLE HTML:
<html>
<head>
<!-- include jquery because you say you are using it -->
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
//just a dummy function to represent your js to extract csv data from a table
function extract_table_data(){
var csv = "field1,field2,field3\n\
value1,value2,value3\n\
value4,value5,value5";
return csv;
}
$( document ).ready(function() {
//export link click handler
$('#export_link').click(function() {
$('#csv_data').val(extract_table_data());
$('#theform').submit();
});
});
</script>
</head>
<body>
<a id='export_link'>Export CSV</a>
<form id='theform' method='post' action='dropcsv.php'>
<input type='hidden' name='csv_data' id='csv_data'/>
</form>
</body>
</html>
dropcsv.php
//filename for our csv attachment
$export_filename = 'thefile.csv';
//grab csv data
$csv_data = $_POST['csv_data'];
//open file in memory
$f = fopen('php://memory', 'w'); //use php://temp if you want a tmp file instead
//load up csv file
fwrite($f, $csv_data);
// go back to the beginning of the file
fseek($f, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="'.$export_filename.'"');
fpassthru($f);
fclose($f);
of course don't forget to add your error checking and sanitize the input.
I have a JavaScript file named a pricing.js which contains this content in it:
var price_arr = new Array('$ 16.95','$ 30.95','$ 49.95','$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95');
But I want to to update this part of JavaScript file using PHP so please help me in this how can I update this part of the content from JavaScript file using PHP?
'$ 16.95','$ 30.95','$ 49.95','$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95'
Please understand that Javascript is Client Side code and PHP is server side code.
There can be 2 possible ways or scenarios which you want to achieve:
If you want to manipulate the JS file before sending it to client, you can rename the Javascript file to have .php extension and write php code to provide a variable. For Ex:
<?php
// write php code to create a string of values using a for loop
$price_array_string = "'$ 16.95','$ 30.95','$ 49.95',
'$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95'";
// Javscript Code var price_arr = new Array(`<?`php echo $price_array_string ?>);
The other alternative is that you get the value of price array by making an Ajax Request to a PHP web service.
Simply give the pricing.js file a .php extension. You can then include PHP in the javascript file the way you would for any other page. Just be sure your HTML code specifies that it's still "text/javascript" when you load it. You'll probably want to set the content-type in the PHP file as well, like so: header("Content-type: text/javascript");
Using your PHP script you can put a value in an HTML5 data attribute of an element on your page and then read it from your JavaScript, e.g. <body data-array="'$ 16.95','$ 30.95'"> can be generated with PHP, and then read with JS: var are = new Array($('body').attr('data-array').split(',')). Here jQuery is used in order to read the attribute value, but you can also do it with pure JavaScript.
This is my first post and I'm sorry if I'm doing it wrong but here we go:
I've been working on a project that should scrape values from a website. The values are variables in a javascript array. I'm using the PHP Simple HTML DOM and it works with the normal scripts but not the one stored in CDATA-blocks. Therefore, I'm looking for a way to scrape data within the CDATA-block. Unfortunately, all the help I could find was for XML-files and I'm scraping from a HTML file.
The javascript I'm trying to scrape is a follows:
<script type="text/javascript">
//<![CDATA[
var data = [{"value":8.41,"color":"1C5A0D","text":"17/11"},{"value":9.86,"color":"1C5A0D","text":"18/11"},{"value":7.72,"color":"1C5A0D","text":"19/11"},{"value":9.42,"color":"1C5A0D","text":"20/11"}];
//]]>
</script>
What I need to scrape is the "value"-variable in the var data.
The problem was that I tried to replace the CDATA string on an object.
The following code works perfectly :-)
include('simple_html_dom.php');
$lines = file_get_contents('http://www.virtualmanager.com/players/7793477-danijel-pavliuk/training');
$lines = str_replace("//<![CDATA[","",$lines);
$lines = str_replace("//]]>","",$lines);
$html = str_get_html($lines);
foreach($html->find('script') as $element) {
echo $element->innertext;
}
I will provide you with more information if needed.
A decent HTML parser shouldn't require Javascript to be wrapped in a CDATA block. If they're throwing it off, just remove them from the HTML before parsing, doing something like this:
Download the HTML file into a string, using file_get_contents() or cURL if your host disabled HTTP support in that function.
Get rid of the //<![CDATA[ and //]]> bits using str_replace()
Parse the HTML from the cleaned string using Simple DOM's str_get_html()
Process the DOM object as before.