Zuckerberg Zuckerberg - 1 month ago 6
Ajax Question

Ajax not sending request to php when url directory changes

Now it is true that this query has not been asked and finally i giveup cos i cant find a switable answer to my query.

On my apache2 server i have enabled rewrite rules in .htaccess file in the root dir to persistently keep pointing everything but directories and files to a certain php file, this works perfectly but the problem the ajax script fails when the url changes it directory.

here is the php script [testing...]

<?php

//now if run the test using the root directory, i get clear response,
//but as i have told u, i have enabled apache2 module and added rewrite rules to .htaccess,
//meaning that no matter hat the url is, the url will keep pointing to the same file but the problem
// is that the ajax script does not fire p the request / send.
//i dont jnow what i am doing wrong...

if(isset($_GET['test_changes'])){
echo 'the request has now reached the server';
exit;
}

?>


And here is the ajax script

<script>

//my ajax script is like this
//the url seen below is in the root directory.
//So briefly,how would i keep this url pointing to the same php file even if the directory changes

$.ajax({

url:'test.php?test_changes=123456789',
cache:false,
async:true,
method:'GET',
success:function(response){
console.log(response)
},
error:function(error){
console.log(error)
}

})
</script>

Answer

please use absolute urls to accomplish the job... see code below

<?php


//it would still received the request
if(isset($_GET['test_changes'])){
    echo 'the request has now reached the server';
    exit;
}

?>






<script>
    //i had a little trouble thinking this through but i got it working after sometime
    //Now You need you ajax script url to be absolute to achieve something like that
    //by prepending a forward slash character to your URL

    $.ajax({
        url:'/test.php?test_changes=123456789',
        cache:false,
        async:true,
        method:'GET',
        success:function(response){
            console.log(response)
        },
        error:function(error){
            console.log(error)
        }
    })
</script>
Comments