Reputation: 161
I'm trying to make an ajax call from within a page with a rewritten URL.
request = $.ajax({
url: "myajaxcode.php",
type: "post",
data: formData
});
The resulting request is .../Folder/Rewritten_Name/myajaxcode.php
For this to work the url should be .../Folder/myajaxcode.php
I also tried using a backslash in the url: "/myajaxcode.php", this resolves to
/myajaxcode.php
The ajax works when I provide the absolute URL or if I use a function that calculates and base URL and prefixes it the php file name. However, ideally I wanted to avoid using absolute urls or additional functions.
Is there a better way of handling the ajax call?
My htaccess is
RewriteEngine on
RewriteBase /Folder/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^Rewritten_Name/([^/]+) Rewritten_Name.php?r=$1
Upvotes: 0
Views: 1495
Reputation: 34135
If you are making a request from example.com/Folder/foo.php
to example.com/Folder/myajaxcode.php
you can use relative URl, like this:
request = $.ajax({
url: "./myajaxcode.php",
type: "post",
data: formData
});
Assuming that rewrite rules defined are correct, working exactly you want them to be & base url meta tag is set correctly in html.
further another approch, I have been people taking is: setting a global js variable from PHP in some function & the call the function in <head>
where ever they want to ajax. like this
<?php
function set_ajax_url($script_path){
$ajax = "<script type='text/javascript'>";
$ajax .= "window.MY_AJAX_URL = ";
$ajax .= $_SERVER['HTTP_HOST'] . $script_path;
$ajax .= "</script>";
echo $ajax;
}
add this in your template/layout
<html>
<head>
<?php set_ajax_url('Folder/myajaxcode.php'); ?>
</head>
you use can this like this:
request = $.ajax({
url: MY_AJAX_URL,
type: "post",
data: formData
});
so, you will have to change the url at one place :)
Upvotes: 1