Make a javascript work within a URL

Asked

Viewed 112 times

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 user IP.

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

What I’m trying to do and I can’t get it to work inside a link that I want to be generated according to the person’s city. Like:

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

I tried to make it work the way below but the answer at 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 little layy on this subject so any solution be it in PHP or javascript would be welcome. Thanks in advance!

  • You can explain better what you want to do, or better: what should happen when the user clicks the link? Is this detection being made in PHP? , you can put that geo-target code here?

1 answer

1

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

    <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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.