in index.php <script type="text/javascript" src="test.js?country=japan"></script> PHP: in test.js var url = document.location.href; url = url.split("?country="); alert(url[1]); document.write(url[1]); Code (markup): when I visit index.php, undefined come out.. not japan.. can someone help me fix this?
index.php: <html> <head> <script type="text/javascript" src="test.js.php?country=japan"></script> </head> <body> </body> </html> Code (markup): test.js.php: document.write("<?php echo $_REQUEST['country'] ?>"); Code (markup): test.js.php is more accurate than your original javascript, too
If you're trying to split the search string query, it might also be best for you use "document.location.search" as opposed to "document.location.href". That will return only the URL query part of the string =)
It is giving you undefined result, because document.location.href returns request parameter of your browser, not the src value of <script>. But if it is the latter you want, then try something like below: var scripts = document.getElementsByTagName("script"); for (var i=0; i<scripts.length; i++){ if (scripts[i].src.search("test.js") != -1){ alert(scripts[i].src.split("=")[1]); break; } } Code (markup):
the document.location.href's value is the url of index.php not the url of your js file.. this might help you extract parameters in your js file..