0

I want to create one page site by change div content with out load new page. So, I've implemented my code like this:

HTML:

<title>Post title</title>
<body>
    <a class="js-post-bt" href="/post/1" data-id="1"></a>
    <a class="js-post-bt" href="/post/2" data-id="2"></a>
    <a class="js-post-bt" href="/post/3" data-id="4"></a> 

    <div id="post-container"></div>
</body>

Script

$(function() {
    $(".js-post-bt").on("click", function(e) {
         var post_id = $(this).attr("data-id");
         $.ajax({
            url: "post_title.php?id="+post_id,
            success: function(data) {
                var title = data;
                $.ajax({
                    url: "post.php?id="+post_id,
                    success: function(data2) {
                        // how to change url to post/post_id?
                        document.title = title;
                        $("#post-container").html(data2);
                    }
                });
            }
        });

        e.preventDefault();
    });
});

Is it possible to create only one ajax call and get returned data either title and post data. ANd how to change browser address to post/post_id after anchor link clicked.

Gaël Barbin
  • 3,769
  • 3
  • 25
  • 52
Marcus
  • 617
  • 2
  • 13
  • 19
  • This is the answer you need. http://stackoverflow.com/questions/3338642/updating-address-bar-with-new-url-without-hash-or-reloading-the-page – codyogden Apr 22 '15 at 04:50

2 Answers2

1

You can use history api in HTML5

Demo -> http://html5demos.com/history

Howto ->

http://diveintohtml5.info/history.html

http://html5doctor.com/history-api/

dbucki
  • 454
  • 3
  • 7
0

If you want to make just one ajax call, which is a good idea, you will also need to change the code on your server.

It should respond a json object:

json_encode( array( "title" => $title, "post_data" => $post_data ) );

And you ajax call becomes:

$(function() {
    $(".js-post-bt").on("click", function(e) {
         var post_id = $(this).attr("data-id");
         $.ajax({
            url: "post_title.php?id="+post_id,
            dataType: "json",
            success: function(json_data){
                document.title = json_data["title"];
                $("#post-container").html(json_data["post_data"]);
            }
        });

        e.preventDefault();
    });
});
Gaël Barbin
  • 3,769
  • 3
  • 25
  • 52