9

On a webpage that has a list of categories, and each category title is linked in this format: http://localhost/admin/category/unpublish/2

I wrote the following js code, trying to capture the url and the segments 'unpublish' (action) and '2' (id), and need to send the request to http://localhost/admin/category

$('#statusChanges a').click(function(evt) { // use the click event of hyperlinks
  evt.preventDefault();
  var url = $(location).attr('href');
  // var action = url.segment(3);  /*JS console complains that url.segment() method undefined! */
  // var id = url.segment(4);
  $.ajax({
    type: "GET",
    url: $(location).attr('href'),
    dat: '',
    /* do I need to fill the data with json data: {"action": "unpublish, "id": 2 } ? but I don't know how to get the segments */
    success: function(data) {
      $('.statusSuccess').text('success!');
    },
    error: function(data) {
      $('.statusSuccess').text('error!');
    }
  });
}); // end of status change
1

3 Answers 3

13

Try this

var url = $(location).attr('href').split("/").splice(0, 5).join("/");

Update Answer:

User this object to get current anchor link see below

$(this).attr('href')
Sign up to request clarification or add additional context in comments.

5 Comments

I found $(location).attr('href') gives me the current url, but I would like to get the url on the <a href></a> tag. thanks
@TonyGW , try this for current url $(this).attr("href");
all right, so this gives me the right url on the hyerlink: var url = $(this).attr('href'); thanks for help!
@TonyGW this is refer to current target... you have attached event on <a> tag so this provides you current <a> element reference.
$(this).attr('href') I got undefined on firefox 37
9

Split the URL into segments first:

var segments = url.split( '/' );
var action = segments[3];
var id = segments[4];

2 Comments

This is simple, but note that it should be var segments = window.location.href.split( '/' );. See: Get the current URL with JavaScript?
This was assuming url is already defined, i.e. var url = $(location).attr('href');
1

I think you can use split. Then you can have an array to work with from which you can get the action and id.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.