Post Input OnChange with AJAX


Post Input OnChange with AJAX

只是一些AJAX故障排除。

Context:构建一个大的表,其中的输入应该在填写完后立即发布。我觉得onchange触发器效果最好。

问题:我似乎无法让javascript将输入的值传递给.php表。


header。php

$(document).ready(function(){
  $(".matchedit").onchange(function postinput(){ // Problem 1: change(
    var matchvalue = $(this).value; // Problem 2: $(this).val();
    $.ajax
        ({ 
            url: 'matchedit-data.php',
            data: {matchvalue: matchvalue},
            type: 'post'
        });
  });
}); 

page.php

<tr>
  <td>
    <input name="grp1" type="text" class="matchedit" onchange="postinput()">
  </td>
</tr>

matchedit-data.php

$entry = $_POST['matchvalue'];
$conn->query("UPDATE matches SET grp = '$entry' WHERE mid = 'm1'");

提前感谢!

对于jQuery包装输入的值应该使用.val()方法,这里的value返回一个undefined值。另外,你应该使用.on('change')change()方法,jQuery对象没有onchange方法。

$(document).ready(function(){
    $(".matchedit").on('change', function postinput(){
        var matchvalue = $(this).val(); // this.value
        $.ajax({ 
            url: 'matchedit-data.php',
            data: { matchvalue: matchvalue },
            type: 'post'
        }).done(function(responseData) {
            console.log('Done: ', responseData);
        }).fail(function() {
            console.log('Failed');
        });
    });
});