How to pass variables and data from PHP to JavaScript? -
i have variable in php, , need value in javascript code. how can variable php javascript?
i have code looks this:
<?php ... $val = $myservice->getvalue(); // makes api , db call ?>
i have javascript code needs val
, looks along lines of:
<script> myplugin.start($val); // tried this, didn't work <?php myplugin.start($val); ?> // didn't work either myplugin.start(<?=$val?> // works sometimes, fails </script>
there several approaches this. require more overhead others, , considered better others.
in no particular order:
- use ajax data need server.
- echo data page somewhere, , use javascript information dom.
- echo data directly javascript.
in post, we'll examine each of above methods, , see pros , cons of each, how implement them.
1. use ajax data need server
this method considered best, because your server side , client side scripts separate.
pros
- better separation between layers - if tomorrow stop using php, , want move servlet, rest api, or other service, don't have change of javascript code.
- more readable - javascript javascript, php php. without mixing two, more readable code on both languages.
- allows async data transfer - getting information php might time/resources expensive. don't want wait information, load page, , have information reach whenever.
- data not directly found on markup - means markup kept clean of additional data, , javascript sees it.
cons
- latency - ajax creates http request, , http requests carried on network , have network latencies.
- state - data fetched via separate http request won't include information http request fetched html document. may need information (e.g. if html document generated in response form submission) and, if do, have transfer across somehow. if have ruled out embedding data in page (which have if using technique) limits cookies/sessions may subject race conditions.
implementation example
with ajax, need 2 pages, 1 php generates output, , second javascript gets output:
get-data.php
/* operation here, talk database, file-session * world beyond, limbo, city of shimmers, , canada. * * ajax uses strings, can output json, html , xml well. * depends on content-type header send ajax * request. */ echo json_encode(42); //in end, need echo result. //all data should json_encode()d. //you can json_encode() value in php, arrays, strings, //even objects.
index.php (or whatever actual page named like)
<!-- snip --> <script> function reqlistener () { console.log(this.responsetext); } var oreq = new xmlhttprequest(); //new request object oreq.onload = function() { //this handle response. //the actual data found on this.responsetext alert(this.responsetext); //will alert: 42 }; oreq.open("get", "get-data.php", true); // ^ don't block rest of execution. // don't wait until request finishes // continue. oreq.send(); </script> <!-- snip -->
the above combination of 2 files alert 42
when file finishes loading.
some more reading material
- using xmlhttprequest - mdn
- xmlhttprequest object reference - mdn
- how return response asynchronous call?
2. echo data page somewhere, , use javascript information dom
this method less preferable ajax, still has advantages. it's still relatively separated between php , javascript in sense there no php directly in javascript.
pros
- fast - dom operations quick, , can store , access lot of data relatively quickly.
cons
- potentially unsemantic markup - usually, happens use sort of
<input type=hidden>
store information, because it's easier information out ofinputnode.value
, doing means have meaningless element in html. html has<meta>
element data document, , html 5 introducesdata-*
attributes data reading js can associated particular elements. - dirties source - data php generates outputted directly html source, meaning bigger , less focused html source.
- harder structured data - structured data have valid html, otherwise you'll have escape , convert strings yourself.
- tightly couples php data logic - because php used in presentation, can't separate 2 cleanly.
implementation example
with this, idea create sort of element not displayed user, visible javascript.
index.php
<!-- snip --> <div id="dom-target" style="display: none;"> <?php $output = "42"; //again, operation, output. echo htmlspecialchars($output); /* have escape because result not valid html otherwise. */ ?> </div> <script> var div = document.getelementbyid("dom-target"); var mydata = div.textcontent; </script> <!-- snip -->
3. echo data directly javascript
this easiest understand, , horrible use. don't unless know you're doing.
pros
- very implemented - takes little implement this, , understand.
- does not dirty source - variables outputted directly javascript, dom not affected.
cons
- insecure - php has no trivial javascript escape functions, , aren't trivial implement. when using user inputs, extremely vulnerable second tier injections. disputed see comments
- tightly couples php data logic - because php used in presentation, can't separate 2 cleanly.
- structured data hard - can json... kinda. xml , html require special attention.
implementation example
implementation relatively straightforward:
<!-- snip --> <script> var data = <?php echo json_encode("42", json_hex_tag); ?>; //don't forget semicolon! </script> <!-- snip -->
good luck!
Comments
Post a Comment