0

I want to set the data that is returned from the success callback in an AJAX request as an input value. This is not working. I have the feeling this is because I am using an AJAX request within an (.on) event function. I need to use the event function within the AJAX request ($this) to find the input I want to update.

$(function () {
        $("table").on('change', '.master', function () {
            $.ajax({ type: "POST", async: false, url: '<?php echo site_url('wordsuggestion'); ?>/hoi/nederlands/frans', success: function(data) { 
                $(this).parents('tr').find(".slave").val(data);
            }});
        });
    });

This is the form I'm using.

<tr>
                <td>
                    <div class="form-group"><input type="text" class="master" name="or[0]"></div>
                </td>
                <td>&nbsp;</td>
                <td>
                    <div class="form-group"><input type="text" class="slave" name="tr[0]"></div>
                </td>
            </tr>

It is a mystery for me why this is not working. I think that within the AJAX call, the $(this) operator can't be used any more which causes the input not to be updated.

P.Yntema
  • 576
  • 2
  • 9
  • 29
  • 1
    In what way does this actually fail? Is the AJAX request made? What is the server's response? Are there any errors? – David Jan 04 '17 at 18:22
  • @David The AJAX request is definitely made now. The server responds with the content on that page, which is in this case a 7-letter word. No errors. – P.Yntema Jan 04 '17 at 18:23

2 Answers2

2

this doesn't refer to what you think in the AJAX callback. The context of that callback is outside of the context of the original change event handler, which has already completed.

You can set the context in the $.ajax() call, something like this:

$.ajax({
    context: this,
    type: "POST",
    // etc...

Or even just set the value to a variable and capture that variable for the callback:

var element = this;
$.ajax({
    success: function (data) {
        $(element).parents('tr')....
    },
    // etc...
David
  • 208,112
  • 36
  • 198
  • 279
1

Try

$(this).parents('tr').find(".slave").eq(0)