1

I'm retrieving the data from the AJAX and creating the dynamic spans as given below in the code. In the code I'm also getting the span data on apply button click but when I load my web page then for first time it works well but I have to reload page again again for getting the correct data.

So how can I get the data without reloading on every click in the array and on every click first it will empty the array and then put all the data of the span in the array for the further use?

$(document).ready(function(){
  $( "#loadingDiv" ).fadeOut("slow");
  var firstLetter;
  var span_array = [];
  var counter = false;
  $('#apply').click(function(e){
   span_array=[];
   console.log(span_array);
   e.preventDefault();
   if (day == "Select day") {
    alert("Please Select the day")
   }
   else{
    $('#link').show();
    var array_dates = [];
    $.ajax({
     url:"/api/v1/schedule",
     type: "GET",
     dataType: 'json',
     data:{day:day, provider: "provider 1"},
     success: function(response){
      // console.log(response.response.data);
      if (response.response.data == null) {
       
      }
      else{
       for (var i = 0; i < response.response.data.length; i++) {
        $("#days_of_the_month").append("<div id='specific'><span id="+i+" class='emphasis label label-important'>"+response.response.data[i]+'</span><a class="dateEdit" id='+i+' href="#" ><i class="fa fa-edit"></i></a></div>');
       }
       $('.emphasis').html(function(i, h) {
         return h.replace(/^(\d+)/, '<span class="hidden">$1</span>');
       }).click(function() {
         var number = $(this).find('.hidden').text();
         console.log(number);
       });
      }
      $('div[id^="days_of_the_month"]').each(function () {
       var $this = $(this),
          len = $this.find('span.emphasis').length;
          for (var i = 0; i < len; i++) {
           span_array.push($('#'+i).text());
          }
      });
      console.log(span_array);
     }
    });
   }
  });   
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select class="select_day" id="select_day">
   <option>Sunday</option>
   <option>Monday</option>
   <option>Tuesday</option>
   <option>Wednesday</option>
   <option>Thursday</option>
   <option>Friday</option>
   <option>Saturday</option>
  </select>

   <button id="apply">Apply</button><br>
   <a id="link" value="apply" style ="cursor: pointer; display:none;" data-toggle="modal" data-target="#exampleModalCenter">
     Set Working Hours
   </a><br><br>
   <div id="days_of_the_month"></div>
   <!-- Modal -->
   <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
     <div class="modal-dialog modal-dialog-centered" role="document">
       <div class="modal-content">
         <div class="modal-header">
           <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
           <button type="button" class="close" data-dismiss="modal" aria-label="Close">
             <span aria-hidden="true">&times;</span>
           </button>
         </div>
         <div class="modal-body" style="margin: -1px;">
          From: <input type="text" id="txtFromDate" />
           To: <input type="text" id="txtToDate" />
           <div id="errordate"></div>
           <hr>
           <h4>Timing Schedule</h4>
           Start Time:<br>
           <select id="starthour">
            <option>00</option>
            <option>01</option>
            <option>02</option>
            <option>03</option>
            <option>04</option>
            <option>05</option>
            <option>06</option>
            <option>07</option>
            <option>08</option>
            <option>09</option>
            <option>10</option>
            <option>11</option>
            <option>12</option>
           </select>
           <select id="startminute">
            <option>00</option>
            <option>01</option>
            <option>02</option>
            <option>03</option>
            <option>04</option>
            <option>05</option>
            <option>06</option>
            <option>07</option>
            <option>08</option>
            <option>09</option>
            <option>10</option>
            <option>11</option>
            <option>12</option>
            <option>13</option>
            <option>14</option>
            <option>15</option>
            <option>16</option>
            <option>17</option>
            <option>18</option>
            <option>19</option>
            <option>20</option>
            <option>21</option>
            <option>22</option>
            <option>23</option>
            <option>24</option>
            <option>25</option>
            <option>26</option>
            <option>27</option>
            <option>28</option>
            <option>29</option>
            <option>30</option>
            <option>31</option>
            <option>32</option>
            <option>33</option>
            <option>34</option>
            <option>35</option>
            <option>36</option>
            <option>37</option>
            <option>38</option>
            <option>39</option>
            <option>40</option>
            <option>41</option>
            <option>42</option>
            <option>43</option>
            <option>44</option>
            <option>45</option>
            <option>46</option>
            <option>47</option>
            <option>48</option>
            <option>49</option>
            <option>50</option>
           </select>
           <select id="startmeridiem">
            <option>AM</option>
            <option>PM</option>
           </select>
           <!-- <input type="text" id="starthour" style="width: 74px;" value="" placeholder="Hours" /> -->
           <!-- <input type="text" id="startminute" style="width: 74px;" placeholder="Minutes" value="" /> -->
           <!-- <input type="text" id="startmeridiem" style="width: 74px;" placeholder="A.M./P.M." value="" /> -->
           <br>
           End Time(24 Format Please):<br>
           <select id="endhour">
            <option>00</option>
            <option>01</option>
            <option>02</option>
            <option>03</option>
            <option>04</option>
            <option>05</option>
            <option>06</option>
            <option>07</option>
            <option>08</option>
            <option>09</option>
            <option>10</option>
            <option>11</option>
            <option>12</option>
           </select>
           <select id="endminute">
            <option>00</option>
            <option>01</option>
            <option>02</option>
            <option>03</option>
            <option>04</option>
            <option>05</option>
            <option>06</option>
            <option>07</option>
            <option>08</option>
            <option>09</option>
            <option>10</option>
            <option>11</option>
            <option>12</option>
            <option>13</option>
            <option>14</option>
            <option>15</option>
            <option>16</option>
            <option>17</option>
            <option>18</option>
            <option>19</option>
            <option>20</option>
            <option>21</option>
            <option>22</option>
            <option>23</option>
            <option>24</option>
            <option>25</option>
            <option>26</option>
            <option>27</option>
            <option>28</option>
            <option>29</option>
            <option>30</option>
            <option>31</option>
            <option>32</option>
            <option>33</option>
            <option>34</option>
            <option>35</option>
            <option>36</option>
            <option>37</option>
            <option>38</option>
            <option>39</option>
            <option>40</option>
            <option>41</option>
            <option>42</option>
            <option>43</option>
            <option>44</option>
            <option>45</option>
            <option>46</option>
            <option>47</option>
            <option>48</option>
            <option>49</option>
            <option>50</option>
           </select>
           <select id="endmeridiem">
            <option>AM</option>
            <option>PM</option>
           </select>
           <div id="error"></div>
           <!-- <input type="text" id="endhour" style="width: 74px;" placeholder="Hours" value="" /> -->
           <!-- <input type="text" id="endminute" style="width: 74px;" placeholder="Minutes" value="" /> -->
           <!-- <input type="text" id="endmeridiem" style="width: 74px;" placeholder="A.M./P.M." value="" /> -->
           <hr>
           <h4>Frequency</h4>
           <label><input type="radio" name="modalRadioButton" id="frequency" value="every week" checked="checked"> Every Week</label>
         </div>
         <div class="modal-footer">
           <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
           <button type="button" class="btn btn-primary" id="savedata" >Save</button>
         </div>
       </div>
     </div>
   </div>
   <!-- second modal -->
   <div class="modal fade" id="secondModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
     <div class="modal-dialog modal-dialog-centered" role="document">
       <div class="modal-content">
         <div class="modal-header">
           <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
           <button type="button" class="close" data-dismiss="modal" aria-label="Close">
             <span aria-hidden="true">&times;</span>
           </button>
         </div>
         <div class="modal-body" style="margin: -1px;">
           <span id="heading"></span>
          <div id="data" style=" overflow-y: scroll; height: 250px;"></div>
         </div>
         <div class="modal-footer">
           <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
           <button class="update" id="update" type="button" class="btn btn-primary"  data-dismiss="modal">Update</button>
         </div>
       </div>
     </div>
   </div>

How can I solve this problem? Can anybody help me for solving this.

Thank you in advance.

Takit Isy
  • 9,688
  • 3
  • 23
  • 47
gourav
  • 177
  • 2
  • 20

1 Answers1

1

First, some observations on your existing code.

if (day == "Select day") {  // <- `day` is not defined anywhere. this will cause an error.
    alert("Please Select the day")
} else {

...

$("#days_of_the_month").append(
    "<div id='specific'>" + // <- this creates a non-unique ID which may make searching for it unreliable.
        "<span id=" + i + " class='emphasis label label-important'>" + // <- this span shares an ID with the `.dateEdit` span
            response.response.data[i] +
        '</span>' +
        '<a class="dateEdit" id=' + i + ' href="#" >' + // <- this span shares an ID with the `.emphasis.label.label-important` span
            '<i class="fa fa-edit"></i>' +
        '</a>' + 
    '</div>'
);

...

$('div[id^="days_of_the_month"]').each(function() { // <- there is only ever one div that matches this, so there's no need to loop.
    var $this = $(this),
        len = $this.find('span.emphasis').length;
    for (var i = 0; i < len; i++) {
        span_array.push($('#' + i).text()); // <- which span actually gets pushed here? `.dateEdit`? `.emphasis.label.label-important`? both?
    }
});

With that in mind, I've taken the liberty of restructuring your code a little bit in the hopes that the problem and solution would be a little more clear.

I strongly suspect that the reason for having to reload the page is that you are not currently clearing out the results of the previous ajax call before appending the new results.

$(document).ready(function() {
    $("#loadingDiv").fadeOut("slow");
    var firstLetter;
    var span_array = [];
    var counter = false;
    var cachedAjaxData; // top-level variable to store the results of the ajax call.

    // delegate the click handler, rather than attaching a copy to each one.
    // If you need an explanation of delegated event handlers, see the accepted answer for:
    //      https://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on
    $("#days_of_the_month").on('click', '.emphasis', function (e) {
        var number = $(this).find('.hidden').text();
        console.log('number =', number);
    });

    // turned this into a function to:
    //  1. remove this distracting bit of code from the ajax call
    //  2. showcase [what I think is] a more readable and reliable way of generating markup with jQuery
    var makeSpecificDiv = function (num) {
        var specific = $('<div />', {
            id: 'specific-' + num,  // concatenating `num` to ensure uniqueness
        });
        var spanEmphasis = $('<span />', {
            id: 'emphasis-label-' + num,  // adding text and concatenating `num` to ensure uniqueness,
            class: 'emphasis label label-important',
        });
        var spanHidden = $('<span />', {    // adding the hidden span here, rather than using a `replace` function to put it in
            class: 'hidden',
            text: num,
        });
        var spanDateEdit = $('<span />', {
            id: 'date-edit-' + num,  // adding text and concatenating `num` to ensure uniqueness,
            class: 'dateEdit',
            href: '#',
        });
        var iEdit = $('<i />', {
            class: 'fa fa-edit',
        });
        spanEmphasis.append(spanHidden);
        spanDateEdit.append(iEdit);
        specific.append(spanEmphasis);
        specific.append(spanDateEdit);
        return specific[0];
    };

    // turned this into a function to:
    //  1. separate this code to more easily find the problem (either here, or the ajax call itself)
    //  2. make the ajax call `success` code block smaller.
    var processAjaxData = function(data) {
        // cache the result of the call in a variable scoped one level up;
        cachedAjaxData = data;

        // use a document fragment for faster element insertions
        var fragment = document.createDocumentFragment();

        // loop through it
        data.forEach(function (num) {
            var divSpecific = makeSpecificDiv(num);
            fragment.appendChild(divSpecific);

            // since `num` is the `.text()` of the span, just push it into the `span_array` directly.
            // further, this is effectively just making a copy of the `cachedAjaxData`
            span_array.push(num);
        });

        $("#days_of_the_month")
            // .empty()    // uncomment to clear the old nodes before inserting the new ones.
            .append(fragment); // insert all new DOM nodes at once.

        console.log('cachedAjaxData =', cachedAjaxData);
        console.log('span_array =', span_array);
    };

    $('#apply').click(function(e) {
        span_array = [];
        console.log(span_array);
        e.preventDefault();
        var day = $('#select_day').val();   // defined `day`
        if (day == "Select day") {
            alert("Please Select the day");
            return; // exiting function, rather than an `else` clause to limit indentation levels.
        }

        $('#link').show();
        var array_dates = [];
        $.ajax({
            url: "/api/v1/schedule",
            type: "GET",
            dataType: 'json',
            data: {
                day: day,
                provider: "provider 1"
            },
            success: function(response) {
                // console.log(response.response.data);
                if (response.response.data !== null) {  // eliminated empty block
                    processAjaxData(response.response.data);
                }
            }
        });
    });
});
pete
  • 24,141
  • 4
  • 37
  • 51
  • there is an error in the code in `fragment.appendChild(divSpecific);` how to solve this. The result I want is correct I just console the `divSpecific` but how to solve this – gourav Jun 22 '18 at 03:25
  • Here in this line `var fragment = document.createDocumentFragment();` I write the span like this`"span"` between the round bractes like this `var fragment = document.createDocumentFragment("span");` but this will give me error too. – gourav Jun 22 '18 at 04:01
  • @gourav the `document.createDocumentFragment` method takes no arguments. that is why you are getting an error when you try to do `var fragment = document.createDocumentFragment("span");`. What is the error you are getting in the console with `fragment.appendChild(divSpecific);`? – pete Jun 22 '18 at 13:02
  • I figured out the problem with `fragment.appendChild(divSpecific);` (`.appendChild` expects a `Node` object and `divSpecific` is a jQuery object). Updated code in answer to correct the error. – pete Jun 22 '18 at 13:08