Retrieving the initial array element within a foreach loop

I am just starting with ajax concepts...

When I post data using ajax, only the first array from the foreach loop gets posted.

Here is the code snippet:

<tbody id="presentor">
<?php if(!empty($data)):?>
<?php $counter = '0'; foreach ($data as $lead):?>
   <?php $prospect_type = $this->admin_model->getData('prospect_type',$lead->prospect_type);?>
   <?php $language = $this->admin_model->getData('language',$lead->language);?>
   <?php $source = $this->admin_model->getData('source',$lead->source);?>
   <?php $location = $this->admin_model->getData('location',$lead->location);?>
   <?php $requirement = $this->admin_model->getData('requirement',$lead->requirement);?>
   <?php $lead_type = $this->admin_model->getData('lead_type',$lead->lead_type);?>
   <?php $lead_status = $this->admin_model->getData('status',$lead->lead_status);?>

      <tr role="row" class="odd">
      <td tabindex="0" class="sorting_1" style="text-transform: uppercase; text-align: center;"><?php echo ++$counter;?></td>
      <td id="lead_date"><?php echo $lead->leadDate;?></td>
      <td id="first_name"><?php echo $lead->first_name;?></td>
      <td id="last_name"><?php echo $lead->last_name;?></td>
      <td id="prospect_type"><?php echo $prospect_type[0]->prospect_type;?></td>
      <td id="number"><?php echo $lead->number;?></td>
      <td id="email_id"><?php echo $lead->email_id;?></td>
      <td id="language"><?php echo $language[0]->language_name;?></td>
      <td id="source"><?php echo $source[0]->source_name;?></td>
      <td id="location"><?php echo $location[0]->location_name;?></td>
      <td id="requirement"><?php echo $requirement[0]->requirement;?></td>
      <td id="lead_type"><?php echo $lead_type[0]->lead_type;?></td>
      <td><?php echo $lead->executive_comment;?></td>
      <td><?php echo $lead->admin_remark;?></td>
      <td><?php echo $lead_status[0]->status;?></td>
      <td style="display: none;text-align: center;">
      <a href="<?php echo $base_url;?>dashboard/edit_Data/<?php echo $lead->id;?>/add_lead/"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
      | <a href="javascript:void(0);" onmousedown="deleteLead('<?php echo $base_url;?>dashboard/delete_Data/<?php echo $lead->id;?>/lead/');"><i class="fa fa-trash-o" aria-hidden="true"></i></a>
      | <a data-toggle="modal" href="#myModal" id="lead_id" data-custom-value="<?php echo $lead->id;?>"><i class="fa fa-paper-plane" aria-hidden="true"></i></a>
        </td>
       </tr>
<?php endforeach;?>
<?php endif;?>
</tbody>

<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content" id="leadId">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Select Employee</h4>
        </div>
        <div class="modal-body">
            <div class="item form-group">
                <div for="name">
                    <span class="required">Assigned To</span>
                </div>
                <div>
                    <?php $user = $this->admin_model->getData('user');?>
                    <select class="form-control" name="user" id="assign_user">
                        <option value="">Select User to Assign</option>
                        <?php foreach ($user as $row): ?>
                            <option value="<?php echo $row->id; ?>"><?php echo $row->first_name . " " . $row->last_name; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <a id="assignResult" class="btn btn-primary modal-toggle" style="background-color: #000;border-color: #000;">Assign</a>
        </div>
    </div>
</div>

I am also using a HTML model to call user ID and names with the following code:

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
 <div class="modal-dialog">
  <!-- Modal content-->
  <div class="modal-content" id="leadId">
   <div class="modal-header">
   <button type="button" class="close" data-dismiss="modal">&times;</button>
      <h4 class="modal-title">Select Employee</h4>
   </div>
   <div class="modal-body">
    <div class="item form-group">
     <div for="name">
      <span class="required">Assigned To</span>
     </div>
    <div>
    <?php $user = $this->admin_model->getData('user');?>
      <select class="form-control" name="user" id="assign_user">
        <option value="">Select User to Assign</option>
          <?php foreach ($user as $row): ?>
           <option value="<?php echo $row->id; ?>"><?php echo $row->first_name . " " . $row->last_name; ?></option>
          <?php endforeach; ?>
      </select>
     </div>
    </div>
   </div>
   <div class="modal-footer">
    <a id="assignResult" class="btn btn-primary modal-toggle"style="background-color: #000;border-color: #000;">Assign</a>
   </div>
  </div>

Below are the jquery and AJAX file contents:

<script>
$(document).ready(function() {
    $("#assignResult").click(function () {

        var lead_date = $( '#lead_date' ).text();
        var lead_id = $( '#lead_id' ).data("custom-value");
        var assign_userId =  $( "#assign_user option:selected" ).val();
        var first_name =  $( "#first_name" ).text();
        var last_name =  $( "#last_name" ).text();
        var prospect_type =  $( "#prospect_type" ).text();
        var number =  $( "#number" ).text();
        var email_id =  $( "#email_id" ).text();
        var language =  $( "#language" ).text();
        var source =  $( "#source" ).text();
        var location =  $( "#location" ).text();
        var requirement =  $( "#requirement" ).text();
        var lead_type =  $( "#lead_type" ).text();      

        $.ajax({
            url: '<?php echo $base_url?>dashboard/send_leads',
            type: 'POST',
            data: {
                lead_date : lead_date,
                lead_id : JSON.stringify(lead_id),
                assign_user: assign_userId,
                first_name : first_name,
                last_name : last_name,
                prospect_type : prospect_type,
                number : number,
                email_id : email_id,
                language : language,
                source : source,
                location : location,
                requirement : requirement,
                lead_type : lead_type,
            },
            success: function (data) {
                alert(data);
                $('#myModal').modal('hide');
            },
            error: function(errorThrown){
                alert(errorThrown);
                alert("There is an error with AJAX!");
            }
        });

    });
});
</script>

This is how my array looks like:

 Array
(
[0] => stdClass Object
    (
        [id] => 2
        [leadDate] => 2018-08-01
        [first_name] => Rishab
        [last_name] => Patel
        [prospect_type] => 1
        [number] => 9988665523
        [email_id] => [email protected]
        [language] => 2
        [source] => 1
        [location] => 2
        [requirement] => 1
        [lead_type] => 3
        [executive_comment] => Call him
        [admin_remark] => good
        [lead_status] => 1
    )

[1] => stdClass Object
    (
        [id] => 3
        [leadDate] => 2018-08-09
        [first_name] => Ajay
        [last_name] => Patel
        [prospect_type] => 4
        [number] => 1232426225
        [email_id] => [email protected]
        [language] => 2
        [source] => 2
        [location] => 1
        [requirement] => 1
        [lead_type] => 3
        [executive_comment] => Call him
        [admin_remark] => good
        [lead_status] => 1
    )

[2] => stdClass Object
    (
        [id] => 4
        [leadDate] => 2018-08-13
        [first_name] => praney
        [last_name] => panday
        [prospect_type] => 3
        [number] => 7845123265
        [email_id] => [email protected]
        [language] => 2
        [source] => 1
        [location] => 2
        [requirement] => 1
        [lead_type] => 2
        [executive_comment] => Call him
        [admin_remark] => good
        [lead_status] => 1
    )
)

However, when I use AJAX to post this data, it only posts the [0] array. Even after alerting every variable, it still shows the values of the [0] array.

Can someone please provide assistance or point out where I might be doing something wrong?

Thank you in advance....

Answer №1

It seems that the issue lies in assigning the same HTML id to multiple rows of the same "type" within your table.

Here's a breakdown: If you have a

<tr role="row" class="odd"></tr>

inside a loop, each cell

<td id="lead_date"></td>

will end up with the same id #lead_date.

Since IDs should be unique across the entire document, this results in invalid HTML.

The jQuery script is trying to retrieve the value from #lead_date into an internal variable

var lead_date = $( '#lead_date' ).text();

However, if there are multiple fields with id #lead_date, only the first one will be targeted.

This problem currently affects all fields in your html table, causing only the first array to be submitted.

To resolve this issue, make sure to avoid duplicating HTML ids.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

utilizing session variables in php that are generated during an Ajax request

Hey there! I am facing an issue with accessing session variables after making an Ajax call in JavaScript to a PHP file. I am able to create a session and store values within it during the Ajax call, but when trying to access those session variables afterwa ...

Reloading the React/Laravel application causes the app to crash and display a blank page

My current setup involves a react application running on the Laravel 5.4 framework. The problem I'm facing is that whenever I refresh a page with a URL structure like {url}/{slug}, it causes issues within the application. Within my App.js file, here ...

What could be causing my JavaScript alert to not appear on the screen?

Essentially, I've been attempting to trigger a Javascript alert using PHP. However, the alert isn't functioning at all. This is my echo statement that dynamically generates the alert echo "<script>alert('Uploaded file was not in the ...

Transforming the typical click search into an instantaneous search experience with the power of Partial

I am working on a form that, when the user clicks a button, will display search results based on the entered searchString. @using (Html.BeginForm("Index", "Search")) { <div id="search" class="input-group"> @Html.TextBox("searchString", n ...

Issues with fullcalendar refetchEvents and rerenderEvents in Safari and Opera browsers

After saving a dialog when creating a new event by clicking the day, I use the following code: addEvent(calEvent); // save to database when creating an event $dialogContent.dialog("close"); $('#calendar').fullCalen ...

What is the process for removing the body of a table?

My goal is to reset the table body, which has been filled with JavaScript loaded data previously. https://i.stack.imgur.com/7774K.png ` getTableData = function (clicked_id) { if (clicked_id != '') { $.ajax({ async : f ...

You can only access mypage.php from the /mypage directory, not from /mypage.php

Currently, I am in the process of developing a PHP website and utilizing htaccess to conceal php extensions using the following script: Options +FollowSymlinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILEN ...

The Dropdown Button Functions Once and Then Stops

I am facing a challenge in implementing a button within an HTML table that triggers a dropdown menu when clicked, and closes upon another click or when the user clicks outside the menu. Oddly, the button only seems to work once before completely losing fun ...

Linking to a Different Tab without Tab Mutation with Bootstrap 3.3.5

I am facing a similar issue to the mentioned questions. I am trying to use a link to change tabs, but the problem is that the link only changes the tab content and not the active tab. The most similar question can be found at: Bootstrap linking to a tab w ...

Guide to extracting specific elements from JSON using PHP

After retrieving a JSON from a URL, I am attempting to extract information using PHP. Here is what I have so far: $url = 'https://www.anwb.nl/feeds/gethf'; $result = file_get_contents($url); $array = json_decode($result, TRUE); echo $array[1][ ...

Exploring ways to compare data from two different tables in separate databases using the mysqli extension in PHP

How can I compare data after connecting to different MySQL databases using mysqli? Database name garden_fruit1, password 123456, database username garden_fruit1. $link1 = mysqli_connect("localhost", "garden_fruit1", "123456" ...

Having trouble with CSRF when trying to implement AJAX post in Django?

I am currently facing an issue with the ajax vote implementation on my article model: @csrf_exempt @login_required def like(request): args = {} if request.method == 'POST': user = request.POST.get('user') lu= re ...

I want to use the enter key for posting, but also have the ability to use the shift and enter key to create a

$("#post_text").keydown(function(e){ // Checking if Enter key was pressed without shift key if (e.keyCode == 13) { // Prevent default behavior e.preventDefault(); } if (e.keyCode == 13 && !e.shiftKey) { alert('test'); } }); I a ...

redirecting from an AJAX request

Seeking a way to perform a redirect following an ajax `put` request. My intention is to implement client-side validation using pure JS. Client: $(document).ready(function() { login = () => { var username = $("[name='username']"). ...

Mac users may experience lag when using Javascript parallax effects

I created a parallax page where the background image changes using JavaScript translateY(- ... px)' similar to what you see on the firewatch website. On Windows, the parallax effect works smoothly. However, on macOS it is smooth only in Safari. All ...

Ways to extract the value from a jQuery object

How can I retrieve the selected time value using a jQuery plugin and save it on a specific input element within the page? Refer to the plugin and code provided below: http://jsfiddle.net/weareoutman/YkvK9/ var input = $('#input-a'); input.cloc ...

What is the best way to design distinct buttons for various devices?

For my current responsive web design project, I have utilized Bootstrap extensively. Recently, I encountered a new issue that I'm uncertain of how to tackle. The problem arises with the following HTML code snippet: <!-- button color depending on d ...

Updating Rails Partial with JSON Data

Updating a partial by appending fetched Facebook posts using the koala gem requires some code adjustments. Here is an example of how to achieve this: # feed_controller.rb def index end def fb_feed @fb_feed = .. respond_to do |format| format.js { ...

Tips for creating a horizontally scrolling div

Here is the CSS for the div that needs to be able to scroll horizontally: .form-holder{ padding-left: 20px; width: auto; background: ; overflow-x: auto; max-height: 300px; padding-bottom: 30px; } Every ...

Automatically refreshing a partial view on Razor Pages in .NET Core at specific intervals

Currently, I am grappling with mastering Razor Pages for Net Core and encountering a bit of a roadblock. My Index.cshtml file looks like this: @page @model IndexModel <input type="hidden" name="hdnPageSelector" id="hdnIndexPage ...