Crazy Horse
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.
When I try to console.log() the request I get a console error that says the id is an undefined index.
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?
$.ajax({
url: 'functions/selected-cat.php',
type: 'GET',
dataType: 'json',
data: {}
})
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);
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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']; ?>
ASKER
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');
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.
ASKER
Thanks Chris. It does have a .php extension. Perhaps something wrong with my php configuration on localhost but everything else works just fine.
Open in new window
And in php file:
Open in new window