I want to store values of name, selectedDay and selectedMovie into reservationData. Then, I want reservationData to pass in ajax as a data so I can get it in my Controller, read from them and insert them into my database
This is my code:
var reservationData = {"name": name, "selectedMovie": selectedMovie, "selectedDay": selectedDay};
console.log(reservationData);
var confirmReservation = $('.confirm-reservation');
confirmReservation.on('click', function(){
$.ajax({
url: '/drupal/movie-reservation',
type: 'GET',
cache: false,
data:{result: JSON.stringify(reservationData)},
success: function(data){
alert(data);
}
});
Everytime my name, selectedMovie and selectedDay gain their value I want that value to be stored in reservationData as well. How can I do that? Thanks in advance!
CodePudding user response:
Your current reservationData variable is an object, not an array. You will keep updating/overwriting the same properties. So you will need an array to push these reservationData onto.
CodePudding user response:
You can achieve that by defining reservationData
as an array containing objects.
Within the callback function of your ajax's success
, each successful ajax request will create a new newReservationData
object.
This will be pushed to that array afterwards.
var reservationData = [],
confirmReservation = $('.confirm-reservation');
confirmReservation.on('click', function(){
$.ajax({
url: '/drupal/movie-reservation',
type: 'GET',
cache: false,
data:{result: JSON.stringify(reservationData)},
success: function(data){
let newReservationData = {
"name": data.name,
"selectedMovie": data.selectedMovie,
"selectedDay": data.selectedDay
};
reservationData.push(newReservationData);
}
});