I have a php foreach loop running through records in a database. The foreach adds a new table row showing contacts in the database, e.g. name, address, etc. I'm using a href link to fire an ajax/jquery script which will add that entry to a crew list table. The script is situated in the foreach loop so I have access to the data to send.
My problem is that the first row works fine and then any other records don't fire the script. I'm thinking it may be because the script can't fire with the same ID? so I added the contacts ID to the href.
<a id="addCrewLink'.$contact->person_id.'" href="/pages/voyages/crewlists/add.php?item='.$contact->person_id.'&type=crew" class="btn btn-sm btn-outline-primary">crew</a>
This didn't work. I think I need to move the script out of the foreach loop, both because it is above the table I want to update, and because it probably bad practice to have a table full of scripts!
Can I use the link to pass parameters and then one script to pick up the link???
$(document).ready(function() {
$("#addCrewLink<?php echo $contact->person_id;?>").click(function(e) {
e.preventDefault();
var personID = '<?php echo $contact->person_id;?>';
var voyageID = '<?php echo Input::get('voyage'); ?>';
var passageID = '<?php echo Input::get('passage'); ?>';
var role = '<?php echo $contact->role;?>';
$.ajax({
type: "POST",
url: "/pages/voyages/crewlists/add.php",
dataType: 'json',
data:{ person: personID, embarkingAs: role, voyage: voyageID, passage: passageID },
'success': function(data) {
if(data['success']) {
//refresh the tables
$("#crewTable").load(location.href + " #crewTable");
//$("#passengerTable").load(location.href + " #passengerTable");
//send the user a success message
resetToastPosition();
$.toast({
heading: 'Success',
text: 'Waypoint added successfully',
textColor: 'white',
showHideTransition: 'slide',
hideAfter : 7000,
icon: 'success',
loaderBg: '#f96868',
position: 'top-center'
})
} else {
var i;
for (i = 0; i < data['message'].length; i++) {
//scroll to the top
window.scrollTo({ top: 0, behavior: 'smooth' });
this.error(this.xhr, data['message'][i]);
}
}
},
'error': function(jqXHR, textStatus, errorThrown) {
//send the user a fail message
resetToastPosition();
$.toast({
heading: 'Error',
text: textStatus,
textColor: 'white',
showHideTransition: 'slide',
hideAfter : 7000,
icon: 'error',
bgColor: '#f96868',
position: 'top-center',
loaderBg: '#405189'
})
}
})
});
});
Thanks so much for all the help!
Regards
Matt