0

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

1
  • 3
    Using an individual click handler for each link doesn’t make much sense. You should write one function, that works for all those links. Start by selecting them via a class instead of id. The individual data you need to send in each case could for example be placed in custom data attributes on those links themselves, so that your click handler can read them from there. Commented Mar 18, 2019 at 13:21

1 Answer 1

1

Almost there. My suggestion would be to make the following changes:

  • Change anchors so that they all have a class of add-crew-link
  • Add data attributes for the data you want, on each anchor

Ending up with something like:

<a class="add-crew-link" data-id="1" href="..." class="btn btn-sm btn-outline-primary">crew</a>
<a class="add-crew-link" data-id="2" href="..." class="btn btn-sm btn-outline-primary">crew</a>
<a class="add-crew-link" data-id="3" href="..." class="btn btn-sm btn-outline-primary">crew</a>
<a class="add-crew-link" data-id="4" href="..." class="btn btn-sm btn-outline-primary">crew</a>

Note: Add extra data- attributes as you wish. Such as data-name or data-age, or whatever.

  • Change the click handler to target all the add-crew-link anchors:

    $('.add-crew-link').click(function(e) {

  • Grab the id and other data attributes you need at the start of the click handler function:

    var personID = $(this).data('id');

And of course make sure the function is no longer inside the PHP loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.