Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the current page URL from a PHP script envoked via AJAX?

Tags:

ajax

url

php

get

Erm... what the title says really; I have a PHP script executed by an AJAX call on page1. Can I access page1's current URL/URI from inside the PHP called by AJAX using standard $_GET, or do I need to pass the parameter I want along with the rest of the data to the AJAX page?

Thanks,

James

like image 921
Bojangles Avatar asked Dec 19 '10 21:12

Bojangles


People also ask

How do you get the current page URL?

Answer: Use the window. location. href Property location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc.

How call AJAX URL in PHP?

click(function(e) { $. ajax({ type: "GET", url: "action. php?", data: "me=" + me, success: function (data) { alert(data); } }); return false; e. preventDefault(); });

Can you use AJAX with PHP?

Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.

What is URL in AJAX?

The url parameter is a string containing the URL you want to reach with the Ajax call, while settings is an object literal containing the configuration for the Ajax request. In its first form, this function performs an Ajax request using the url parameter and the options specified in settings .


1 Answers

Referrer should do the trick

echo $_SERVER['HTTP_REFERER']

from within your php script

Just to get more specific: Page1 makes a call to Page2. You'd then output the variable above to find the url of page1. If you need the url of page2, then you would use:

$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

You should check if these exist before trying to access them. I sometimes do this:

$server = array_merge(array('HTTP_HOST'=>null, 'REQUEST_URI'=>null, 'HTTP_REFERER'=>null), $_SERVER);

I would then access the variable "$server" instead of $_SERVER. Alternatively, you could use @$_SERVER[] too which will generally supress errors.

like image 101
Jason Avatar answered Sep 22 '22 10:09

Jason