
Context
For a website, I developed a calendar and a schedule. So I have an AJAX request that is sent to the server when I click on a date in my calendar, in order to update my schedule accordingly.
Also, for my project, when the user performs an action on the page, their choice has to be saved so that they don’t have to redo everything if they change pages. So I made a second AJAX request to save the information in the user’s session.
Problem
It seems that sending two AJAX requests at the same time isn’t a good idea… My schedule is updated correctly but the server doesn’t properly save the information in my user’s session.
$.ajax({
type: 'GET',
url: '/sessiondata',
data: { 'date': newDate },
});
$.ajax({
type: 'GET',
url: pageURL,
data: { 'date': newDate, 'page': page },
success: function(data) {
var container_planning = $(data).find('.container-planning').html();
$('.container-planning').html(container_planning);
}
})
Solution
I needed a way for my requests to be sent one after the other, in order. So setting “async:true” is not a solution.
I simply did it like this:
$.ajax({
type: 'GET',
url: '/sessiondata',
data: { 'date': newDate },
success: function(data) {
updatePlanning();
}
});
function updatePlanning() {
$.ajax({
type: 'GET',
url: pageURL,
data: { 'date': newDate, 'page': page },
success: function(data) {
var container_planning = $(data).find('.container-planning').html();
$('.container-planning').html(container_planning);
}
})
}
This way, updatePlanning() only runs after the date has been saved in the user’s session.