How to communicate between javascript and php?

In summary, the user types in a web address, like "myapp.com", which then runs display.php which accesses the database and retrieves the required data.
  • #1
aheight
321
109
Hi,

I am having problems integrating HTML, Javascript and PHP. I am using the instructions at this website to transfer data from PHP to Javascript:

http://www.dyn-web.com/tutorials/php-js/scalar.php

and have set up the following simple code to simply transfer a PHP array to Javascript but I can't confirm it's working: the alert(jvar) command is not printing to the console. I'm not even sure I should name it *.html or *.php or if I should run it on the server or in the browser. I would like to learn how to transfer data between PHP and Javascript and was wondering if someone could help me. Thanks.

HTML:
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>Test of PHP to Javascript transfer</div>
        <?php
        $var1=array(1,2.5,0.0098);
        var_dump($var1);
        ?>
        <script type="text/javascript">
            var jvar = <?php echo json_encode($var1) ?>;
            alert(jvar);
            </script>
                 
    </body>
</html>
 
Last edited:
Technology news on Phys.org
  • #2
The file has to be .php to be interpreted by the server (or your home computer if you run your own php interpreter - probably not). If you open the site (from the server) with your browser, how does the source code look like? If it looks like the code here, then your server is not interpreting the php code.

The last php command should get a ";".

You might need some javascript function to read in the string you get from php.
 
  • #3
Hi mfb. Like the He poem. :)

Ok, I changed the name to phptest.php and ran it through WAMP64 via:

localhost/projects/phptest.php

and it seems to be working. However, on a related item if you or others are interested in helping me:

I am so confussed about integrating HTML, Javascript, PHP, MySQL, WebGL, and Mathematica into a beautifully-integrated package that I know can be done. Perhaps if I briefly explain what I wish to accomplish:

I wish to store a large block of floating-point data (millions of 32-bit values acquired by Mathematica) in a SQL blob. Ok, then I want to set up an HTML/Javascript application to access this database, for now, just on my local PC running WAMP64 via localhost, load it into my Javascript and then illustrate a 3D plot using WebGL. And surprisingly, I can do all the pieces: load data in database, run PHP to access the blob, unpack the data into 32-bit floating point numbers, process extremely large Javascript arrays through WebGL and illustrate the plot.

But I'm just having problems integrating it into a seamless, smooth-flowing application: type in a web address, say "myapp.com" which then runs what a PHP or HTML file? This file then presents a list of functions (which is an index into the SQL database) to the user which chooses one. Then myapp.com accesses the database, retrieves the associated blob, parses it, passes it to Javascript/WebGL which creates a 3D rendering app to display the function.

Just don't understand how to set something like this up.
 
Last edited:
  • #4
Technically the starting page can be pure html, but you can always use .php files - if there is no php code on the page it is simply given to the user as html code. The starting page ("index.php") will have some html form (which can be generated by php, or be directly written in html). The user asks the server to provide index.php, the server processes php (if present) and delivers the form to the user. The user selects the function in their browser and sends a request for the display php page ("display.php" (together with POST or GET data from the form) to the server.
The php code on display.php then uses the transmitted data to query the database, does some calculations (optional) and puts the data into the html/js code which is sent to the user. The browser of the user then uses JS/WebGL to display things.

Depending on the size of the data, an indirect approach might be better: have the JS code include some third file ("data.php") where the php code there fetches the data.
 
  • Like
Likes QuantumQuest
  • #5
Say this is index.php:
PHP:
<html>
<head>
    <!-- head stuff -->
</head>
<body>
<?php
$functions = ["FunctionName1", "FunctionName2", "FunctionName3", "FunctionName4", "FunctionName5"];

if(isset($_GET['function']) && in_array($_GET['function'], $functions)){   
    showFunction($_GET['function']);
}

showIndex();

// Define PHP functions:

function showIndex(){
    echo "
    <ul>
        <li><a href='?function=FunctionName1'>FunctionName1</a></li>
        <li><a href='?function=FunctionName2'>FunctionName2</a></li>
        <li><a href='?function=FunctionName3'>FunctionName3</a></li>
        <li><a href='?function=FunctionName4'>FunctionName4</a></li>
        <li><a href='?function=FunctionName5'>FunctionName5</a></li>
    </ul>";
}

function showFunction($function){
    echo "Showing " . $function . ": <br>";
    //access the database to get the blob of $function
    //create the HTML/JS to show $function

    //(or 'include' a PHP file where those processes are defined)
}
?>
</body>
</html>
So the following will show the functions index:
  • myapp.com
  • myapp.com/index.php
  • myapp.com?function=DummyName
  • myapp.com/index.php?function=DummyName
And these will show FunctionName1 followed by the functions index:
  • myapp.com?function=FunctionName1
  • myapp.com/index.php?function=FunctionName
 
  • #6
<li><a href='?function=FunctionName3'>FunctionName3</a></li>
While that works, it is hard to extend and really bad style. Use HTML forms.

There is no need to make a function showIndex() if you just write HTML code anyway.
 
  • #7
jack action said:
Say this is index.php:

function showFunction($function){
echo "Showing " . $function . ": <br>";
//access the database to get the blob of $function
//create the HTML/JS to show $function

//(or 'include' a PHP file where those processes are defined)
}

I have a question about those comments Jack: That is a PHP file. How in the function showFunction() do I include Javascript or include a PHP file that has Javascript? I guess I really don't understand the interaction of PHP and Javascript. For example if I tried to add some Javascript in showFunction I just get a syntax error:

PHP:
function showFunction($function){
    echo "Showing " . $function . ": <br>";
    //access the database to get the blob of $function
    //create the HTML/JS to show $function
<script type="text/javascript">
     alert("test");
</script>
    //(or 'include' a PHP file where those processes are defined)
}
 
  • #8
You get an error because the PHP parser tries to read the code "<script type="text/javascript">" and doesn't understand it.

You can put everything in the echo and escape quotation marks:
PHP:
<?php
function showFunction($function){
    echo "Showing " . $function . ": <br>
<script type=\"text/javascript\">
     alert(\"test\");
</script>"; //here the string for "echo" ends
}?>
As both PHP and JS accept both " and ', this can be written more elegant:
PHP:
<?php
function showFunction($function){
    echo "Showing " . $function . ": <br>
<script type='text/javascript'>
     alert('test');
</script>";
}?>
It is also possible to tell the parser to stop PHP interpretation in between, ugly but can be used if escaping everything would be too messy:
PHP:
<?php
function showFunction($function){
    echo "Showing " . $function . ": <br>"; ?>
<script type="text/javascript">
     alert("test");
</script>
<?php } ?>
 
  • Like
Likes QuantumQuest and aheight
  • #9
aheight said:
How in the function showFunction() do I include Javascript or include a PHP file that has Javascript? I guess I really don't understand the interaction of PHP and Javascript.

PHP «writes» HTML and HTML interacts with JS.

The PHP «write» command is «echo»:
PHP:
function showFunction($function){
    echo "Showing " . $function . ": <br>";
    //access the database to get the blob of $function
    //create the HTML/JS to show $function
    echo '<script type="text/javascript">
            alert("test");
        </script>';
    //(or 'include' a PHP file where those processes are defined)
}
or you could also have an HTML or PHP file (say 'myfile.html') somewhere with the following content:
HTML:
<script type="text/javascript">
    alert("test");
</script>
and then use the following code to include it:
PHP:
function showFunction($function){
    echo "Showing " . $function . ": <br>";
    //access the database to get the blob of $function
    //create the HTML/JS to show $function
    include 'myfile.html';
    //(or 'include' a PHP file where those processes are defined)
}
 
  • Like
Likes aheight
  • #10
mfb said:
While that works, it is hard to extend and really bad style. Use HTML forms.
Since you already know what the answers should be (as opposed to, say, a user's name), I don't see what a form will add. It also helps for search engines to find your pages, if that's what you want. What is your reference for «bad style»?
mfb said:
There is no need to make a function showIndex() if you just write HTML code anyway.
This is something fast I've done and I just made sure it worked. You can obliviously clean it up and adjust it to one's need. You can even make it more dynamic, like reading the functions' name from the database and build the $functions array from that and then build the index from the $functions array as well.
 
  • #11
Wow guys, those work neat! Thanks a bunch. It's a good start. And I do plan to eventually first query the database to tabulate the functions for viewing. Lots to learn.
 
  • #12
aheight said:
Hi,

I am having problems integrating HTML, Javascript and PHP. I am using the instructions at this website to transfer data from PHP to Javascript:

Hi aheight!

As I told in a previous post, you have to learn how each component and each part participating in a web app works, in order to understand how they interact as well.

PHP is a kind of "glue" for a web application. It is a hypertext preprocessor, as it was conceived in the first place, but at the same time is a full - fledged scripting language, for quite some time now. The interaction taking place between user (browser) and server, is as mfb describes in #4. So, PHP can "spit out" - a phrase often used in web dev lingo, whatever you need: HTML, JavaScript, CSS, whatever your client can accept as code, to process and display. This is usually accomplished using
PHP:
echo
command but because in many cases this is overkill, you simply use the close tag
PHP:
?>
and write the html you want to send after that (as pure HTML). Whatever task you want to accomplish regarding database (query, fetch or store data), transformation between different formats e.g XML to HTML, calculations for data, creating special headers for HTTP, user input validation, creating sessions and cookies to name the most important, can be done using PHP. After HTML5 got in some widespread use, some computations regarding client were transferred to the client program by developers, but still it's a matter of what is the project at hand, to decide what and how.

Now, your safe bet is to understand what you need to do on the server as well as on the client and what can be done on each side of the app, in order for your web app to function correctly and smoothly.
If it is the case that you want to do some computations on the client side (usually browser) using JavaScript, then just throw your .js file(s) to the client through PHP and let it be done. A word of warning here, because some features of JavaScript are disabled by default in some browsers due to security policies and the user can also disable JavaScript altogether. So, you cannot rely only on JavaScript and a good example for that is form validation, that besides client, it has to be done also on the server. So, depending of course on what you're trying to accomplish, it is advisable to see what computations you can do on the server, taking into account every kind of rationale you have to. Of equal importance is what you can do on each side. Browser has a rendering engine that can "understand" and render some specific kinds of code and server has an added scripting engine (e.g. PHP in our discussion). So, you must be careful about what you ask to get processed on each side.

All the above apply also to this

aheight said:
I am so confussed about integrating HTML, Javascript, PHP, MySQL, WebGL, and Mathematica into a beautifully-integrated package that I know can be done. Perhaps if I briefly explain what I wish to accomplish:

I wish to store a large block of floating-point data (millions of 32-bit values acquired by Mathematica) in a SQL blob. Ok, then I want to set up an HTML/Javascript application to access this database, for now, just on my local PC running WAMP64 via localhost, load it into my Javascript and then illustrate a 3D plot using WebGL. And surprisingly, I can do all the pieces: load data in database, run PHP to access the blob, unpack the data into 32-bit floating point numbers, process extremely large Javascript arrays through WebGL and illustrate the plot.

But I'm just having problems integrating it into a seamless, smooth-flowing application: type in a web address, say "myapp.com" which then runs what a PHP or HTML file? This file then presents a list of functions (which is an index into the SQL database) to the user which chooses one. Then myapp.com accesses the database, retrieves the associated blob, parses it, passes it to Javascript/WebGL which creates a 3D rendering app to display the function.

Especially for the last paragraph, what you ask is a PHP application. So, my advice is to learn PHP to a decent level and you'll have a much deeper understanding of all this. Add some knowledge about databases and protocols (essentially HTTP - HTTPS) and you'll be ok to go further.
 
Last edited:
  • Like
Likes aheight and mfb
  • #13
Hi guys,

I implement an XMLHttpRequest method to successfully transfer a blob containing 100 32-bit floating point numbers from SQL to my Javascript and I was wondering if some here could look at my code and perhaps suggest a more efficient way as I would like to scale-up to around a 250Mb blob and I suspect that will have a long lag time the way I'm doing it now.

Recall, the blob is in 4-byte packed format (little endian) $a[0] to $a[3] has the first floating point number, then $a[4] to $a[7] the next and so on. Here is my PHP code to access the 8th record and retrieve the blob with $a['webGLData'] containing the data and I noticed the echo command appends a cr/lf to the data making it 402 bytes that are transferred so also wondering if there is a way to transfer the data without cf/lf?

PHP:
<?php
include 'Hexdump.php';
include 'algebraicFunctionBlobClass.php';

$blobObj = new algebraicFunctionBlob();

// uncomment to store blob in database
//$blobObj->insertBlob('test5.bin',"functionTrace2");

$a = $blobObj->selectBlob(8);

echo $a['webGLData'];

?>

And here is my HTML/Javascript using an XMLHttpRequest to retrieve the blob then FileReader to read it and finally I cast bytes 0 through 399 to Float32Array and then confirm in the debugger that the values in myData4 are the same floating-point values I created in Mathematica:

JavaScript:
<html>
<head>
</head>
<body onload="loadDoc()">
<script>
var theResponse;
var reader;
var myData4;
         
function loadDoc() {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.responseType = "blob";
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
  // retrieve the data in this.response  (this.response is a blob type)      
        theResponse=this.response;
        reader = new FileReader();
        reader.addEventListener("loadend", function() {
             // reader.result contains the contents of blob as a typed array
        
   // blob sent by echo has carriage return/line feed at end so chop off:
 
        myData4=new Float32Array(reader.result.slice(0,400));
   
               });
            reader.readAsArrayBuffer(theResponse);
                           
            }
        };
        xmlhttp.open("GET","saveAlgebraicBlob.php",true);
        xmlhttp.send();
   }
</script>
</body>
</html>
 
  • #14
aheight said:
I implement an XMLHttpRequest method to successfully transfer a blob containing 100 32-bit floating point numbers from SQL to my Javascript and I was wondering if some here could look at my code and perhaps suggest a more efficient way as I would like to scale-up to around a 250Mb blob and I suspect that will have a long lag time the way I'm doing it now.

For large amounts of data, use POST method instead of GET. Most servers have a limit for HTTP GET of 8192 bytes and although this is configurable on the server, it is definitely not what is needed for large amounts of data. POST has other advantages too. Take a look in w3schools if you need to, for a comparison between the two methods.

Now, for your second question about cr/lf, you can use the trim PHP string function.
 
  • Like
Likes aheight
  • #15
QuantumQuest said:
For large amounts of data, use POST method instead of GET. Most servers have a limit for HTTP GET of 8192 bytes and although this is configurable on the server, it is definitely not what is needed for large amounts of data. POST has other advantages too. Take a look in w3schools if you need to, for a comparison between the two methods.
The 250 MB is for the server response, not for the user request.

You want to transfer 250 MB for every page request? That is a huge amount. Are the full 250 MB necessary for visualization? Can you reduce the size before with SQL/PHP?
 
  • #16
mfb said:
The 250 MB is for the server response, not for the user request.

Could you explain what you mean by this mfb? Basically I eventually wish to get to the point of loading the web page, making a query to the database to obtain a list of functions, presenting the list to the user, having the user select one, then making another query to the database to get the selected (blob) function data, pass it to WebGL and render it with all the controls and menus for the user to investigate the function and being able to have the user choose another file and repeat the process indefinitely without running out of memory or memory leaks or other problems. The large data transfer occurs when the query is made to get the blob data for the function.

The files are not all 250Mb. Some are smaller and some would be larger. But that size is the size of the data file in JSON format which is character data. Take a list of six-digit 32-bit floating point numbers in ASCII. That's 8 bytes/number (decimal point and comma between them) but in packed binary, each is only 4 bytes so this is a reduction by 50% in size. Also I assume Javascript has to convert the ASCII format to 32-bit format which also takes time but if I transfer it in binary I assume this step is eliminated but not sure. And using JSON, loading that 250Mb file takes about 12 seconds. I'm hoping to reduce this by using binary format.

You want to transfer 250 MB for every page request? That is a huge amount. Are the full 250 MB necessary for visualization? Can you reduce the size before with SQL/PHP?

The 250Mb file is (string) data to render a particularly complicated algebraic function in WebGL beautifully. I can always reduce the size of the data packet by acquiring fewer data points for each branch but with a corresponding reduction in rendering quality.
 
  • #17
aheight said:
And using JSON, loading that 250Mb file takes about 12 seconds.
Only if you run it offline, or have a really fast internet connection. You won't reduce the size of a string of integers much (lossless) no matter how you compress them.
 
  • #18
mfb said:
The 250 MB is for the server response, not for the user request

Yes, I know that. I was talking in general about large amounts of data and their best method to send. Client obviously sends only its request. The problem must be handled through the way server sends its response.
 
  • #19
Hey guys,

I was able to load Mathematica-generated WebGLData into my local SQL database, retrieve it, and then render it so I think I'm at a point were I would like to think about getting a real web-site going so I was wondering if you guys could give me some suggestions about setting this up?

I'm thinking of just getting a subscription to some web-hosting site that has MySQL like eHost.com. Is that what I would need to do to set up a web-server with SQL and get this running? Would what I'm doing here transfer to that setup? I suspect things will be different with an off-site server and I would need that to begin running test to determine if what I'm doing will even work efficiently with big blobs as I can't really check that just running it locally.

Any ideas?

Thanks guys.
 
Last edited:
  • #20
WAMP is a web server, so nothing much different than what you will have with web hosting companies. The major difference will be that you will have a control panel (usually cPanel) managing all of the programs (and you have a lot more than Apache, MySQL and PHP). Web hosters should be able to help you on how to use cPanel (ex.: hostgator, siteground).

To download your files (what is in your «www» folder) to the server (often in the «public_html» folder), you will need a FTP client. I personally use https://addons.mozilla.org/en-US/firefox/addon/fireftp/, which is free and simple, but only works with Firefox. You connect to your website cPanel with the username and password given by the web hoster, transfer your files and voilà! your website is live!

You can do other things with cPanel (like setting up email accounts, cron jobs, check statistics, install wordPress, SSL certificates, etc.), but nothing that is required to have a running website. Although, in your case, you will need to export a MySQL database, but you should have phpMyAdmin within your cPanel, so it works just like in your WAMP server.

Web hoster may have limits on disc space, database size and bandwith, so make sure the plan you choose fits your website usage.
 
  • Like
Likes aheight
  • #21
jack action said:
WAMP is a web server, so nothing much different than what you will have with web hosting companies. The major difference will be that you will have a control panel (usually cPanel) managing all of the programs (and you have a lot more than Apache, MySQL and PHP). Web hosters should be able to help you on how to use cPanel (ex.: hostgator, siteground).

To download your files (what is in your «www» folder) to the server (often in the «public_html» folder), you will need a FTP client. I personally use https://addons.mozilla.org/en-US/firefox/addon/fireftp/, which is free and simple, but only works with Firefox. You connect to your website cPanel with the username and password given by the web hoster, transfer your files and voilà! your website is live!

You can do other things with cPanel (like setting up email accounts, cron jobs, check statistics, install wordPress, SSL certificates, etc.), but nothing that is required to have a running website. Although, in your case, you will need to export a MySQL database, but you should have phpMyAdmin within your cPanel, so it works just like in your WAMP server.

Web hoster may have limits on disc space, database size and bandwith, so make sure the plan you choose fits your website usage.

Ok thanks. I registered a new domain name: algebraicfunctions.com and am hosting with ehost.com. We'll see what happens. :)
 
  • #22
Simple answer is ajax.
 

1. How do I pass data from JavaScript to PHP?

In order to pass data from JavaScript to PHP, you can use AJAX (Asynchronous JavaScript and XML). This allows for a seamless transfer of data between the client-side (JavaScript) and server-side (PHP).

2. Can I call a PHP function from JavaScript?

Yes, you can call a PHP function from JavaScript using AJAX. You can make a request to a PHP file that contains the function you want to call and retrieve the response in JavaScript.

3. How do I get data from a PHP file into JavaScript?

You can use AJAX to retrieve data from a PHP file and use it in your JavaScript code. The PHP file can return data in various formats such as JSON or XML, which can then be parsed and used in JavaScript.

4. How do I send data from PHP to JavaScript?

You can use AJAX to send data from PHP to JavaScript. The PHP file can process the data and return a response, which can then be accessed and used in JavaScript.

5. Are there any security concerns when communicating between JavaScript and PHP?

Yes, there are security concerns to keep in mind when communicating between JavaScript and PHP. It is important to properly sanitize and validate any data being passed between the two languages to prevent vulnerabilities such as cross-site scripting (XSS) attacks.

Similar threads

  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
2
Views
877
  • Programming and Computer Science
Replies
9
Views
2K
  • Programming and Computer Science
Replies
14
Views
712
  • Programming and Computer Science
Replies
13
Views
1K
  • Programming and Computer Science
Replies
7
Views
6K
  • Programming and Computer Science
Replies
9
Views
4K
  • Programming and Computer Science
Replies
7
Views
5K
  • Programming and Computer Science
Replies
4
Views
6K
  • Computing and Technology
Replies
3
Views
2K
Back
Top