Make a javascript work inside a URL

1

The javascript code below works perfectly in the HTML of my site. It is a geo-target server that shows the city based on the user's IP.

<script src='http://promos.fling.com/geo/txt/location.php?testip='></script>

What I'm trying to do and can not do is to make it work within a link that I want it to be generated according to the person's city. Type:

<a href="http://www.example.net/?q=Belo Horizonte">Belo Horizonte</a>

I tried to make it work in the manner below but the response to the end of the URL, after ?q= is the code itself. I tried this way:

<a href="http://www.example.net/?q=<script src='http://promos.fling.com/geo/txt/location.php?testip='></script>">Belo Horizonte</a>

I'm a bit lazy on this subject so any solution be it in PHP or javascript would be welcome. Thank you!

    
asked by anonymous 08.03.2015 / 21:37

1 answer

1

If I see what you want to do, you have to do something like this:

    <a id="link" href="http://www.example.net/?q="></a>

    <script type="text/javascript">
        getContent("http://promos.fling.com/geo/txt/location.php?testip=", function(code) {
            // code = 'document.write("lisbon")'; -> selecionar só a cidade
            code = code.substring(code.indexOf("\"")+1, code.lastIndexOf("\""));
            var lnk = document.getElementById('link');
            lnk.href += code;
            lnk.text = code;
        });

        function getContent( url, callBackFunction )
        {
             // attempt to create the XMLHttpRequest and make the request
             try
             {
                var asyncRequest; // variable to hold XMLHttpRequest object
                asyncRequest = new XMLHttpRequest(); // create request object

                // register event handler
                asyncRequest.onreadystatechange = function(){
                    stateChange(asyncRequest, callBackFunction);
                } 
                asyncRequest.open( 'GET', url, true );  // prepare the request
                asyncRequest.send( null );              // send the request
             } // end try
             catch ( exception )
             {
                alert( 'Request failed.' );
             } // end catch
        } // end function getContent
    </script>
    
09.03.2015 / 12:31