-1
function updateChatroom() {
    $.ajax({
        url:'../inc/chatroom_update.php',
        type:'POST',
        success:function(response)
        {
            $("#chatUpdate").html(response);
        }
    });
}

I have this ajax above, which is placed in my includes file under header.php. Now my header.php is included in all my website pages which means the url in my ajax needs to change since my web pages can be in different folders. How do I make the AJAX url dynamic?

In PHP terms, if i wanted to make a link dynamic on my header.php file links. I would set a BASE_URL then put in where the file is located. How do I do this from PHP to AJAX? Thanks in advance!

guradio
  • 15,524
  • 4
  • 36
  • 57
A Huntington
  • 1
  • 1
  • 1

4 Answers4

1

Why you not doing this?

function updateChatroom(url) {
    $.ajax({
        url:url,
        type:'POST',
        success:function(response)
        {
            $("#chatUpdate").html(response);
        }
    });
}

Now you can call it with any url.

void
  • 36,090
  • 8
  • 62
  • 107
1

Use dynamic page name:

function updateChatroom(){

var url="<?php  echo basename($_SERVER['PHP_SELF']); ?>";
$.ajax({
       url:'../inc/'+url,
       type:'POST',
       success:function(response)
       {
       $("#chatUpdate").html(response);
       }
       });

}

0

Why not just inject the url & post data as parameters.

<script>
    function updateChatRoom(url, data) {
        data = data || {};

        //I'd suggest validating this against some list. 
        if(!!url) {
            $.ajax({
                url: url,
                data: data,
                type:'POST',
                success:function(response)
                {
                    $("#chatUpdate").html(response);
                }
            });
        } else {
            //Throw
        }
    }
</script>
Matt Oaxaca
  • 196
  • 1
  • 10
0

If this function is placed inside php file you can use code similar to the one bellow to build URL based on where this page is requested:

<%
   $url = $_SERVER['REQUEST_URI']; //returns the current URL
   $parts = explode('/',$url);
   $dir = $_SERVER['SERVER_NAME'];

   for ($i = 0; $i < count($parts) - 1; $i++) {
    $dir .= $parts[$i] . "/";
  }
%>
function updateChatroom() {
    $.ajax({
        url: $dir . '../inc/chatroom_update.php',
        type:'POST',
        success:function(response)
        {
            $("#chatUpdate").html(response);
        }
    });
}