1

I am outputting multiple dynamic links which use the same <a>. My AJAX call loads the content of all the links fine but URL always displays the id of the first link. How can I get it to change the id in the url as the different links are clicked?

$string .= '<a class="hrefid" data-id="'.$name["id"].'" href="#link">'.$name["name"].'</a>'.
<div id="content"></div>
$('.hrefid').on('click', function (e) {
    var load = $(e.target).attr("href");
    if(load == "#link") {
        $.ajax({
            type: 'post',
            url: "/page/test/"+$(this).parents("[data-id]").attr("data-id"),
            complete: function (event) {
                $("#content").contents().remove();
                $("#content").append(event.responseText);
                history.replaceState({}, "", "link"+$('[data-id]').first().attr('data-id'));

            }
        });
    }
});
DN0300
  • 864
  • 2
  • 12
  • 27
  • The problem might be your use of history.replaceState: http://stackoverflow.com/questions/12832317/history-replacestate-example – awl19 Jul 07 '16 at 14:58

3 Answers3

1

Here is the solution...

$('.hrefid').on('click', function (e) {
var $this = $(this);
var load = $(e.target).attr("href");
if(load == "#link") {
    $.ajax({
        type: 'post',
        url: "/page/test/"+id,
        complete: function (event) {
            $("#content").contents().remove();
            $("#content").append(event.responseText);
            history.replaceState({}, "", "link" + $this.attr('data-id'));
        }
    });
}
});
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
Wilmer
  • 138
  • 1
  • 8
0

You have to pass the id value to jquery. After passing the value to jquery you need to tell the url the file that will tranfser the data.

$('.hrefid').on('click', function (e) {
    var load = $(e.target).attr("href");
    var id = $('#your input id').val();
    if(load == "#link") {
        $.ajax({
            type: 'post',
            url: "/page/test.php?action=update&id="+id,
            complete: function (event) {
                $("#content").contents().remove();
                $("#content").append(event.responseText);
                history.replaceState({}, "", "link"+$('[data-id]').first().attr('data-id'));

            }
        });
    }
});

on test.php

if($_GET[action] == "update"){
     $id = $_GET['id'];
     echo $id;
}
Rafael Shkembi
  • 786
  • 6
  • 16
0

I think, you cannot change url link in address bar by programmatically, cause this violates security rules. Imagine, you open bad site which shows you absolutely identical page as your favourite's bank page for account operations, and moreover url link in the address bar is the same as bank's... So you will not have any doubts that this is not real bank page. Your actions on this page may lead into giving up your credentials to bad hands.

You can change hash part of the url link by programmatically. Here wiki about hash fragment of url

Yan Pak
  • 1,767
  • 2
  • 19
  • 15