How to update JavaScript variable using PHP - javascript

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.

Related

How to access JSON file in JavaScript?

I have a JSON file as data.json and I have an HTML file with JavaScript embedded in it. I want to access data from the JSON file in a simple HTML(file:///C:/Users/XYZ/Desktop/htmlpage.html) file and NOT in a server-client manner(http://....). I have tried following simple code to import JSON file.
<!DOCTYPE html>
<html>
<body>
<p>Access an array value of a JSON object.</p>
<p id="demo"></p>
<script type="text/javascript" src="F:/Folder/data.json">
var myObj, x;
x = data[0].topic;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
I have read this method of using
<script type="text/javascript" src="F:/Folder/data.json">
on other StackOverflow Questions. But it is not working.
Please tell me the simplest way to access the data in the JSON file.
You could try writing something like this in your JSON file in order to assign the data to a variable:
window.data = JSON.parse('insert your json string here');
You can then access window.data in your page's javascript. You can also omit window. and just assign and/or read from data, which is the same as window.data.
Perhaps a cleaner approach would be to use an AJAX request either with jQuery or vanilla Javascript, both approaches have many answers available on this site.
You could also look into a solution with jQuery.getJSON(): Loading local JSON file
If you are able to use PHP for your desired task (accessing data from JSON file and doing some stuff with data) it will be easier to use PHP to open JSON files. You can use following code to access JSON files.
<?php
$str = file_get_contents('data.json');
$json = json_decode($str, true);
?>
Here $json will be the outermost object (if file starts with '{') / array (if file starts with '['). Then you can use it in a regular way.
Maybe some of you can think that why I'm posting PHP solution in Javascript question? But I found this very much easier than opening file in Javascript. So if you are allowed to use PHP go with that.

Wordpress get post id with a php file

I have been stuck on this for weeks. I have an HTML slide presentation using Reveal.js. I want to run a php script on the very last slide.
This is an HTML button on the last slide within a Wordpress post:
<button onclick="myFunction()">Open php file</button>
<script>
function myFunction() {
window.open("../../testing/test.php", "_self");
}
</script>
This is the code inside the test.php file that I am trying to run but it returns null:
define('WP_USE_THEMES', false);
require_once('../wp-load.php');
echo "Post ID: ".get_the_ID(); // Returns nulls but I want this to return 86.
The post id is 86. I can hard code it into the html (if I have to) but I don't want to hard code it into the php file. Also, I would prefer not to use jquery. How can I get the post id into the php file? Thanks.
Have you tried using global $post variable??
global $post;
And after that, you can get the id,
echo "Post ID: ".$post->
Another approach is using $wpdb global variable to make database queries.
You can also use JavaScript to send your post id to another php file using javaScript forms, Ajax or jQuery. jQuery Post.
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Save variable to text file serverside using jquery

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.

Loading dynamic php-generated javascript

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>

How to access session variable from JavaScript file (.js) file?

I have to access session variable from javascript file
I am using below code to access from javascript,
var sessionValue = '<%=Session["username"]%>'
alert(sessionValue)
it is working well when the script function is placed inside the aspx page...but when I use the same code in .js file it is not working
I have seen all the related answers, nothing is useful for me, so don't mark it as duplicate
i think try to write your session value to a hidden html element and read value of this hidden element with javascript as follow :
<input type="hidden" id="session" value="'<%=Session["username"]%>'">
at your js:
var sessionValue =document.getElementById("session").value;
Depends on what is your scripting languauge in server side,
if it is JSP or PHP following should work.
var sessionValue = "'"+<%=Session["username"]%>+"'"
alert(sessionValue)

Categories

Resources