Miguel
Miguel

Reputation: 1897

PHP/AJAX generating URL

I have an input that the user can type something and an ajax request fetch these results in the database via php, works fine, then each result, when clicked, has a more detailed page about it, that works fine too, except that i would like it to have a unique url that i can link to someone instead of being the same. For instance: i want this 'www.mysite.com/allItems.php?=detailedItem' and at the moment it's just www.mysite.com/allItems.php even when i'm in detailed page. I already tried with 'a' tag but didn't work.

var handleSearch = function(id, isStateBack) {
        var popID = typeof id != 'undefined' ? id : $(this).attr('id');

        if (!isStateBack) {
            window.history.pushState({popID: popID}, 'Search: ' + popID, 'work.php?=' + encodeURIComponent(popID));
        }
        $.get('AjaxSpecifics.php', {"details": popID}, function(data) {
            $('html').stop().html(data).hide().fadeIn(500);
        });
        return false;
    };
    $(document).on('click', '.imageSearchAjax', handleSearch);

    // popstate event
    window.addEventListener("popstate", function() {
        var currentState = history.state;
        if (typeof currentState.popID != 'undefined') {
            // this state has 'popID' property, handle it
            handleSearch(currentState.popID, true);
        }
    });

Upvotes: 0

Views: 169

Answers (1)

Senorsen
Senorsen

Reputation: 64

Easy. Just take a step in PJAX (Ajax + pushState)

And you can even handle with popstate event to handle the browser's history back.

Adapt to your code here:

var handleSearch = function(id, item, isStateBack) {
    var popID = typeof id != 'undefined' ? id : $(this).attr('id'),
        detailedItem = typeof item != 'undefined' ? item : 'your_current_detailed_item_here';
    // TODO: replace your_current_detailed_item_here with the proper thing
    if (!isStateBack) {
        window.history.pushState({popID: popID, detailedItem: detailedItem}, 'Search: ' + detailedItem, 'http://example.com/allItems.php?=' + encodeURIComponent(detailedItem));
    }
    $.get('AjaxSpecifics.php', {"details": popID}, function(data) {
        $('html').stop().html(data).hide().fadeIn(500);
    });
    return false;
};
$(document).on('click', '.imageSearchAjax', handleSearch);

// popstate event
window.addEventListener("popstate", function() {
    var currentState = history.state;
    if (typeof currentState.popID != 'undefined') {
        // this state has 'popID' property, handle it
        handleSearch(currentState.popID, currentState.detailedItem, true);
    }
});

Upvotes: 1

Related Questions