Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

GET url parameter using ajax

I am trying to get the id value in the url via ajax like this but don't know how to get the url parameter (id value in this case) via jquery.

$.ajax({
		url: 'functions/selected-cat.php',
		type: 'GET',
		dataType: 'json',
                data: {}
	})

Open in new window


When I try to console.log() the request I get a console error that says the id is an undefined index.


$safe_url = filter_var($_GET['id'], FILTER_SANITIZE_URL);

Open in new window


I put that into an array and json_encode it so that part is right. Is it not possible to get a url value in this way? Does it have to be done using javascript/jquery as opposed to php?
ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Leonidas Dosas
Try with post eg:
$.ajax({
		url: 'functions/selected-cat.php',
		type: POST',
		dataType: 'json',
                data: data,
                done:   function( response ) {
               console.log(response);
               });
	      })

Open in new window


And in php file:
if(isset($_POST['data'])){
$safe_url = filter_var($_GET['id'], FILTER_SANITIZE_URL);
echo json_encode($safe_url);
}

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Crazy Horse

ASKER

@ Chris, I actually tried what you suggested already but when I alerted the data instead of showing the id in the url, it just alerted the actual code i.e.: <?php echo $_GET['id']; ?>
I found this before answers were posted here but I think HainKurt's is probably the closest to what I used.

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;
 
    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');
 
        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};
	
	var id = getUrlParameter('id');

Open in new window

If you're only seeing the php code instead of the value, then your page isn't parsing PHP. You'd need to make sure your page has the PHP extension and not an HTML one.
Thanks Chris. It does have a .php extension. Perhaps something wrong with my php configuration on localhost but everything else works just fine.