1

i am sending data to a url using jquery ajax. i want to place the absolute url using php $_SERVER. what is the syntax to do this?

this is the file path that goes in the URL

$_SERVER['DOCUMENT_ROOT']."/folder/file_name.php"

this is the function that the file path goes in

$.ajax({
            type: "GET",
            url: "",
            data: 'time='+ visitortimezone,
            success: function(){
                location.reload();
            }
        });

what is the syntax for this?

1
  • If the target php file is in the same domain as the page you're running the ajax from, you can simply use a relative path in the url I guess. Commented May 13, 2012 at 5:59

1 Answer 1

3

If you really want to get document root from PHP, you can try something like this:

HTML: (Place your document root in hidden text field)

<input type='hidden' name='baseurl' id='baseurl' value='<?php echo  $_SERVER['DOCUMENT_ROOT'];?>'>

jQuery: (Get document root in jQuery from hidden text field)

       $.ajax({
            type: "GET",
            url:  $('#baseurl').text() + "/folder/file_name.php",
            data: 'time='+ visitortimezone,
            success: function(){
                location.reload();
            }
        });

If you are writing your JavaScript in PHP files, you can also try this:

       $.ajax({
            type: "GET",
            url:  "<?php echo $_SERVER['DOCUMENT_ROOT'] . '/folder/file_name.php';?>",
            data: 'time='+ visitortimezone,
            success: function(){
                location.reload();
            }
        });

You can also get hostname in JavaScript too:

document.location.hostname
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for listing basically all possible answers. Instead of using a hidden input field, you can also just echo a global var in the document: echo '<script type="text/javascript">var url=' . $_SERVER['DOCUMENT_ROOT'] . ';</script>'; to store the PHP's $_SERVER['DOCUMENT_ROOT'], but there isn't much point to that if you can just use document.location.hostname as well.
I also echoed the whole script tag inside the php, I guess it'd be easier to put it in the html and just echo the var's value itself but yes, I'm sure you already knew that. :P No problem.
@Fabrício Matté: Yes. Thanks to StackOverflow :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.