Inside a given php script, I have the following:
<script>
function showMember() {
return $.ajax({ //Perform an asynchronous HTTP (Ajax) request.
type: 'get',
//A string containing the URL to which the request is sent.
url: '<?php echo $this->createUrl('member'); ?>',
...
This works, if I place this inside the php file.
But this seems not to be a good way for organizing things, and I would wish to place all this code, on a separate .js file.
What is the proper way for dealing with those scenarios ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With