0

I want to get the id element from the url without '?' in php
Like :
In php get the url will be

http://exp.com/dir/index.php?id=123 

So i tried to use javascript to get this

http://exp.com/dir/123 

My code in javascript was

var url = document.URL;
var id = url.substring(url.lastIndexOf('/') + 1);
alert(id); 

But when i go idon't get an alret box say the 123
It says not found because the server think that i want a directory
Can someone help with my javascript code ?

Màh Di
  • 13
  • 3
  • You must the server tell how to behave when `http://exp.com/dir/123` is requested. In your case, you want `http://exp.com/dir/123` to behave as `http://exp.com/dir/index.php?id=123`. If you are using Apache, have a look at [mod_rewrite](http://httpd.apache.org/docs/current/mod/mod_rewrite.html). – ComFreek Apr 25 '14 at 13:42
  • It's fairly easy to retrieve those variables using PHP. However, while JavaScript can give you the page's current URL with window.location, it doesn't have automatic retrieval methods I know of to parse the end of the string like the serverside languages do. However, please be consistent about which language you're trying to do this in! Your first line says PHP. Your last line says JS. – Katana314 Apr 25 '14 at 13:43
  • Do you want to be able to surf to the url: `http://exp.com/dir/123`...or do you want to alert the id value once you're on that page? – Niklas Apr 25 '14 at 13:46
  • @Niklas i want to be able to surf to the url: http://exp.com/dir/123 – Màh Di Apr 25 '14 at 13:50

2 Answers2

2

This isn't a problem that can be solved through JavaScript.

Your server needs to serve up content for the URL you're trying to access before JavaScript can even run. You need to look into mod_rewrite.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • Thank you but can you help more explain just more ? – Màh Di Apr 25 '14 at 13:41
  • There are a *ton* of questions on Stack Overflow covering the use of mod_rewrite. You need to do a little research for yourself. – user229044 Apr 25 '14 at 13:42
  • Note, [mod_rewrite](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) is a module for an Apache HTTP server — bugged, 19 years old web server only. There is no word about what web server (if) uses author. –  Apr 25 '14 at 13:47
  • @Benio It's a reasonable assumption when talking about PHP. – user229044 Apr 25 '14 at 14:09
0

You need to use htacces. That way you can reshape the url for php to understand

For example:/page/id would be

RewriteRule   ^(.*)/([0-9]+)?$   index.php?page=$2&id=$1  [NC,L]
user3232725
  • 218
  • 1
  • 6