i try to alert something but undefined?

Discussion in 'JavaScript' started by freddie.aziz, Aug 18, 2011.

  1. #1
    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?
     
    freddie.aziz, Aug 18, 2011 IP
  2. rajmv

    rajmv Peon

    Messages:
    34
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    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 ;)
     
    rajmv, Aug 20, 2011 IP
  3. TomKDickinson

    TomKDickinson Peon

    Messages:
    26
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    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 =)
     
    TomKDickinson, Aug 21, 2011 IP
  4. hdewantara

    hdewantara Well-Known Member

    Messages:
    540
    Likes Received:
    47
    Best Answers:
    25
    Trophy Points:
    155
    #4
    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):
     
    hdewantara, Aug 21, 2011 IP
  5. JohnnySchultz

    JohnnySchultz Peon

    Messages:
    277
    Likes Received:
    4
    Best Answers:
    7
    Trophy Points:
    0
    #5
    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..
     
    JohnnySchultz, Aug 22, 2011 IP