What Is the Safest Way of Passing Arguments from Server-Side PHP to Client-Side JavaScript

What is the safest way of passing arguments from server-side PHP to client-side JavaScript

My favorite way is :

<?php

$var = array(
'prop1' => 'value1',
'prop2' => 'value2',
// ...
);

?>
<script type="text/javascript">
var varNameSpace = <?php echo json_encode($var); ?>;

alert( varNameSpace.prop1 ); // -> 'value1'
</script>

Using json_encode() ensures that the values passed to Javascript are escaped and well formatted. Using a common variable container also prevents from over using the global space (window).

How do I pass variables and data from PHP to JavaScript?

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

In no particular order:

  1. Use AJAX to get the data you need from the server.
  2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
  3. Echo the data directly to JavaScript.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

1. Use AJAX to get the data you need from the server

This method is considered the best, because your server side and client side scripts are completely separate.

Pros

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for asynchronous data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.

Cons

  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g., if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

Implementation Example

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

get-data.php

/* Do some operation here, like talk to the database, the file-session
* The world beyond, limbo, the city of shimmers, and Canada.
*
* AJAX generally uses strings, but you can output JSON, HTML and XML as well.
* It all depends on the Content-type header that you send with your AJAX
* request. */

echo json_encode(42); // In the end, you need to `echo` the result.
// All data should be `json_encode`-d.

// You can `json_encode` any value in PHP, arrays, strings,
// even objects.

index.php (or whatever the actual page is named like)

<!-- snip -->
<script>
fetch("get-data.php")
.then((response) => {
if(!response.ok){ // Before parsing (i.e. decoding) the JSON data,
// check for any errors.
// In case of an error, throw.
throw new Error("Something went wrong!");
}

return response.json(); // Parse the JSON data.
})
.then((data) => {
// This is where you handle what to do with the response.
alert(data); // Will alert: 42
})
.catch((error) => {
// This is where you handle errors.
});
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

Some more reading material

  • Using the Fetch API
  • How do I return the response from an asynchronous call?

2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

Pros

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.

Cons

  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JavaScript that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

index.php

<!-- snip -->
<div id="dom-target" style="display: none;">
<?php
$output = "42"; // Again, do some operation, get the output.
echo htmlspecialchars($output); /* You have to escape because the result
will not be valid HTML otherwise. */
?>
</div>
<script>
var div = document.getElementById("dom-target");
var myData = div.textContent;
</script>
<!-- snip -->

3. Echo the data directly to JavaScript

This is probably the easiest to understand.

Pros

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.

Cons

  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

Implementation is relatively straightforward:

<!-- snip -->
<script>
var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>
<!-- snip -->

Good luck!

What is the best way to pass server side variables to JavaScript on the client side?

Return the server data in JSON format. You could do this through AJAX by returning a JSON header, or simple page outup and JSON.parse().

You can assign the JSON data directly to an element's data.

$('#elementid').data('serverdata', data);

Update

After better understanding your situation I would suggest you use the data- attributes for three reasons.

  1. You will have standards compliant markup.
  2. The recent version of jQuery relies on these for the .data function.
  3. The change will require little modification to your current application (changing the way custom attributes are output from customAtt="value" to data-customAtt="value"

Here is some more information on the data attributes.

What is the best practice to pass many server side information to JavaScript?

A very popular pattern is the use of the JSON format. There are libraries to produce it, and Javascript directly consumes it.

Securely passing variable from client side javascript to nodejs server

You have something backwards here.

PHP is a backend language as well and Node is your backend language.

Now to communicate within them why do you pass the parameter to the javascript via HTML and then expect it to be secure

Best way to handle it is that you should either create some API on the node so the PHP can send the values directly to that.. by talking to this API instead of waiting for javascript to do it.

OR

You should create a token authentication system and use it so everytime php page is generated for this client, it creates a token with some random chars and then pass this token to the JS.. JS then requests Node with this token.. Node sees the token table and identifies the Client ID and that would do the necessary job.

Some kind of token/ auth should be used on the Node side else your server is not secure regardless.

server side code mixed with client side code - best practices

We use two approaches to make data created at server-side accessible to the client-side:

1) 'data transfer' object, filled by server-side scripts. For example:

PHP:

<?php
$data = [
'urls' => [
'createSomething' => $this->createUrl($from, $something),
// ...
],
'labels' => [
'createSomething' => $this->cms($labelName),
// ..
],
]
?>
<script>
var dto = <?= json_encode($data) ?>;
</script>

JS:

$.ajax(dto.urls.createSomething, {}, function() { 
alert(dto.labels.createSomethingSuccess);
}

2) dataset attributes, again, filled by the server. For example:

PHP:

<button data-target-url="<?= $this->createUrl($from, $something) ?>"
>Something</button>

JS:

$('button[data-target-url]').click(function() {
var targetUrl = $(this).data('targetUrl');
$.post(targetUrl...);
}

The second approach, to me, appears to be most useful when there's some UI-related set of attributes still calculated at server-side - for example, plugin settings.

How to pass arguments from JS function to PHP code

It's important to know the difference between client side code and server side code. PHP is server side, which means it will run on the server before it's sent to the client. Javascript is client side, which means it will run when the client receives the code. Because of this, javascript can never write anything directly to PHP because the PHP script has already been run before the client even receives the webpage.

In order to send something client side back to the server, you will need to send a Request. The most common way to do this is with a form element with a method=POST and an action pointed to a php file you want to receive. Here is a simple example: https://www.w3schools.com/tags/att_form_method.asp

If you want it to run in the background, I would recommend looking up AJAX requests and how to perform those instead. It's the same concept, but there is a little more to them.



Related Topics



Leave a reply



Submit