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!
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.
You can achieve that by defining arrReservationData as an array containing objects.
Each click on .confirm-reservation will send a new objNewReservationData object via ajax to your controller.
The returned result object will be pushed to arrReservationData.
var arrReservationData = [],
var objNewReservationData = {
"name": name,
"selectedMovie": selectedMovie,
"selectedDay": selectedDay
},
confirmReservation = $('.confirm-reservation');
confirmReservation.on('click', function(){
$.ajax({
url: '/drupal/movie-reservation',
type: 'GET',
cache: false,
data: {result: JSON.stringify(objNewReservationData)},
success: function(data){
let objResponse = {
"name": data.name,
"selectedMovie": data.selectedMovie,
"selectedDay": data.selectedDay
};
arrReservationData.push(objResponse);
// do stuff with arrReservationData, like storing in a database
}
});