Tiaw Tiaw - 4 months ago 17
Ajax Question

ajax inside an ajax success

i made an ajax website that call php pages from a

/pages
folder inside my index.php, inside my page
painting.php
i have a link that call
painting-slider.php
page.

so how can i open this
painting-slider.php
in ajax when i already called my painting.php page?


this is my index.php request page:

<div id="ajax-container">
<?php
$d = "pages/";
if (isset($_GET['p'])) {
$p = strtolower($_GET['p']);
if (preg_match("/^[a-z0-9\-]+$/", $p) && file_exists($d . $p . ".php")) {
include $d . $p . ".php";
} else {
include $d . "404.php";
}
} else {
include $d . "home.php";
}
?>
</div>


and this is my ajax function:

var afficher = function(data, page) {

$('#ajax-container').fadeOut(250, function() {
$('#ajax-container').empty();
$('#ajax-container').append(data);
$('#ajax-container').fadeIn(100, function() {});

});
};

var lastRequest = null;
if (lastRequest !== null) {
lastRequest.abort();
}

var loadPage = function(page, storeHistory) {
if (typeof storeHistory === 'undefined') {
storeHistory = true;
}


lastRequest = $.ajax({
url: "pages/" + page,
cache: false,
success: function(html) {
afficher(html, page);
if (storeHistory === true) {
history.pushState({
'key': 'value',
'url': page
}, '', page);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
afficher('erreur lors du chagement de la page');
}
});

return false;
};

window.addEventListener('load', function() {
setTimeout(function() {
window.addEventListener('popstate', function(e) {
if (e.state === null) {
loadPage('home.php');
} else {
loadPage(e['state']['url'], false);
}
});
}, 0);
});


$('.link').bind('click', function(e) {
e.preventDefault();
var page = $(this).attr('href');
loadPage(page);
return false;
});

Answer

a simple example of "ajax after ajax":

$.ajax({
    url: "pages/" + page,
    cache: false,
    success: function(html) {
        afficher(html, page);
        if (storeHistory === true) {
            history.pushState({
                'key': 'value',
                'url': page
            }, '', page);
        }
        $.ajax({
          url: otherUrl,
          cache: false,
          success: function(result) {
            alert("i am the second result");
            alert(result);
          }
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        afficher('erreur lors du chagement de la page');
    }
});

On the serverside (your PHP files) it is not important to do anything. Your ajax will just get the return value of the script found at the given Urls. I hope it helps