0

My code was working great, but I didnt like the input event I was using since it happens every time a key is pushed. This Ajax is to update the database so I was searching for a way to delay a few seconds before submitting which another awesome member here showed me. The issue I am now having though is that POST variables are no longer making it through Ajax for some reason and I cant figure out why.

My Question Is: Why is this happening and how can I tweak this to fix it.

Below is first the code that was working great but using the input event, second is the code I want to use now, but Ajax isnt passing variables through.

Old Code:

            $('td').on('input',function() {
            $.ajax({
                method: "POST",
                url: "updatedatabase.php",
                data: { 
                    content: $(this).text(), 
                    date: $(this).siblings().first().text(),
                    prod: $('tr:first-child th:nth-child(' + ($(this).index() + 1) + ')').text(),
                    old: old
                }
            })
                .done(function( msg ) {
                alert( msg );
            });

            toastr.options = {
              "positionClass": "toast-top-center",
              "onclick": null,
              "timeOut": "2500",
            }

            toastr.info(old,'Your Previous Amount Was:');

        });

New Code not working correctly:

            var saveTimeout = false;

        $('td').on('input', function() {

            if(saveTimeout) clearTimeout(saveTimeout);

            saveTimeout = setTimeout(function() {
                console.log($(this));
                $.ajax({
                method: "POST",
                url: "updatedatabase.php",
                data: { 
                    content: $(this).text(), 
                    date: $(this).siblings().first().text(),
                    prod: $('tr:first-child th:nth-child(' + ($(this).index() + 1) + ')').text(),
                    old: old
                }
            })
                .done(function( msg ) {
                alert( msg );
            });

            toastr.options = {
              "positionClass": "toast-top-center",
              "onclick": null,
              "timeOut": "2500",
            }

            toastr.info(old,'Your Previous Amount Was:');

            }, 2500);
        });

Snippet:

            var old;
            
            $('td').click(function(){
                
                old=$(this).text();
                
                editclick="yes;"
                
                $(this).prop('contenteditable', true);
                
               // var days = 7;
               // var result = $(this).siblings().first().text();
               // result.setDate(result.getDate() + days);
               // alert( result );
                
            });
            
            var saveTimeout = false;
            
            $('td').on('input', function() {
            
                if(saveTimeout) clearTimeout(saveTimeout);
                saveTimeout = setTimeout(function() {
                    console.log($(this))
                    $.ajax({
                        method: "POST",
                        url: "updatedatabase.php",
                        data: { 
                            content: $(this).text(), 
                            date: $(this).siblings().first().text(),
                            prod: $('tr:first-child th:nth-child(' + ($(this).index() + 1) + ')').text(),
                            old: old
                    }
                })
                    .done(function( msg ) {
                    alert( msg );
                });
                
                toastr.options = {
                  "positionClass": "toast-top-center",
                  "onclick": null,
                  "timeOut": "2500",
                }
                
                toastr.info(old,'Your Previous Amount Was:');
                
                }, 2500);
            });
            
            
            $("td").hover(function(){
                                
                
                    
                $(this).addClass('highlight').siblings().first().addClass('highlight');

                $('tr:eq(1) th:eq('+$(this).index()+')').addClass('highlight');
                
                
            },function(){
                
                
                    
                $(this).removeClass("highlight").siblings().first().removeClass('highlight');

                $('tr:eq(1) th:eq('+$(this).index()+')').removeClass('highlight');
                
                
            });
table,th, td {
  
    border: 1px solid black;
    border-collapse: collapse;
        
}

.highlight {
    
    background-color:#E0E0E0;
    color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" rel="stylesheet"/> 
        <script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>
<table>
  <tr>
    <th>Item #</th>
    <th>1234567</th>
    <th>7654321</th>
    <th>5678945</th>
  </tr>
  <tr>
    <th>Product</th>
    <th><u>22 ounce Dark</u></th>
    <th><u>12count 4oz Dark</u></th>
    <th><u>24count 6oz TJ</u></th>
  </tr>
  <tr>
    <th>2016-01-03</th>
    <td>13587</td>
    <td>2203</td>
    <td>4111</td>
  </tr>
  <tr>
    <th>2016-01-04</th>
    <td>14111</td>
    <td>3247</td>
    <td>4332</td>
  </tr>
  <tr>
    <th>2016-01-05</th>
    <td>13212</td>
    <td>3101</td>
    <td>3911</td>
  </tr>
  <tr>
    <th>2016-01-06</th>
    <td>16335</td>
    <td>3299</td>
    <td>4001</td>
  </tr>
  <tr>
    <th>2016-01-07</th>
    <td>15421</td>
    <td>3100</td>
    <td>4078</td>
  </tr>
</table>
Brandon
  • 465
  • 3
  • 10
  • 19
  • 1
    Most likely `$(this)` is not what you think it is. – CBroe Nov 23 '16 at 12:06
  • $(this) works perfectly in the first set of code though – Brandon Nov 23 '16 at 12:18
  • 1
    Yes, but you changed that code in significant ways - so it should be obvious that this isn’t a valid point. Start by logging `$(this)` to console just before your $.ajax call, and compare the results. – CBroe Nov 23 '16 at 12:21
  • @CBroe Sorry, but im still learning a lot. I tried console.log($this); right above the $.ajax line and didnt get anything at all returned in the inspect > Console window. – Brandon Nov 23 '16 at 13:11
  • `console.log($(this))` – CBroe Nov 23 '16 at 13:17
  • @CBroe sorry typo in my last post, what you just posted was what I tried, except with a semi-colon at the end. I removed it and tried also still nothing. – Brandon Nov 23 '16 at 13:21
  • 1
    So you get “nothing” in both cases? That doesn’t sound right. Please update your above code to show where exactly you placed in in each instance. – CBroe Nov 23 '16 at 13:25
  • @CBroe I am using the bottom piece of code. I copy and pasted the console.log line in. I tried it both with and without the semi-colon. I could give the link of the actual webpage its sitting on if that helps, im just not a huge fan of throwing links out like that – Brandon Nov 23 '16 at 13:29
  • Well you should at least get _some_ output in console, if your function inside setTimeout was actually executed ... have you checked the browser console for errors? – CBroe Nov 23 '16 at 13:36
  • @CBroe no errors. I can tell you that the setTimeout seems to be working because 2.5 secs after the last keystroke we do go into ajax, its just that the values arent being carried through right. I know this because the message window I have on done, I have it return my query line on fail and my query line is missing the variables it needs. toastr is also working after ajax. – Brandon Nov 23 '16 at 13:51
  • @CBroe I just added the snippet to the very bottom of the original post. Obviously Ajax woulnt work in this but at least you can see what is going on a little better. – Brandon Nov 23 '16 at 14:05
  • The very first thing that outputs into console is `[Window]` - and that is what `$(this)` refers to in your function inside the setTimeout. – CBroe Nov 23 '16 at 14:10
  • @CBroe that is? I thought that went to the Toastr window? When I run it in my browser it shows line 126 with that which is the timeout line in the Toastr options. – Brandon Nov 23 '16 at 14:14

1 Answers1

1

So, that $(this) does not refer to the input field but to the window object is the problem here. This happens because you wrapped the function inside the event handler in setTimeout, which changes the execution context of the function.

But this should be fixable, if you just store the reference to the input field into a local variable first, and then use that inside the timeout-ed (that a word?) function, like this:

$('td').on('input', function() {

    var _this = $(this); // preserve reference to the input field here

    if(saveTimeout) clearTimeout(saveTimeout);

    // replace $(this) with _this everywhere inside this function
    saveTimeout = setTimeout(function() {
            $.ajax({
            method: "POST",
            url: "updatedatabase.php",
            data: { 
                content: _this.text(), 
                date: _this.siblings().first().text(),
                prod: $('tr:first-child th:nth-child(' + (_this.index() + 1) + ')').text(),
                old: old
            }
        })
CBroe
  • 91,630
  • 14
  • 92
  • 150
  • This definitely did the trick!! I am struggling to understand what is actually going on with $(this) though, maybe I am misunderstanding what it does? My understanding was that $(this) would be what was currently selected? Clicked on a `` and was typing inside of that `` so I thought $(this) would still refer to that ``. Im obviously wrong because my code didnt work, just trying to totally grasp why so I understand for the future. Are you saying that $(this) now pertains to the timer because we are actually in the timer so the focus is no longer on the `` ? – Brandon Nov 23 '16 at 14:31
  • What `this` refers to, depends on the context. Try http://stackoverflow.com/q/4195970/1427878 for a more detailed explanation. – CBroe Nov 23 '16 at 14:35