简体   繁体   中英

Updating database table with AJAX on change

I'm trying to update a database column once an input field has changed. however the code below just isn't doing it and am puzzled.

<script>
$("#addline1").change(function() {
                var itemVal = $("#addline1").val();
                var dataString = "companyid=" + companyid + "&addline1=" + itemVal;
                processChange(dataString);
                });
        function processChange(dataString){
                    $.ajax({
                                type: "POST",
                                url: "../inc/dataforms/test.php",
                                data: dataString,
                                complete: function(data) {
                                    var Resp = data.responseText;
                                    console.log(Resp);
                                    }
                    });
    };
</script>

companyid is already defined elsewhere on the page. I've tried change, onchange...

My PHP code is:

mysqli_query($dbc,"UPDATE `comp_companies`  SET `regoffice1` = '$_POST[addline1]' 
WHERE `company_id` = '$_POST[companyid]'");

Saying unexpected token ( somewhere in here

    $("#addline1").change(function() {
        var itemVal = $.("#addline1").val();
        var dataString = "companyid=" + companyid + "&addline1=" + itemVal;
        processChange(dataString)
        });

I suggest you to use an object instead of a string... To pass the data, as the method used is POST.

(Assuming companyid is defined...)

<script>
$("#addline1").change(function() {
  var itemVal = $("#addline1").val();  // Remove the extra dot that was here

  // var dataString = "companyid=" + companyid + "&addline1=" + itemVal;
  // I suggest the following:
  var dataObj = {companyid:companyid, addline1:itemVal};

  processChange(dataObj);
});

function processChange(dataObj){

  $.ajax({
    type: "POST",
    url: "../inc/dataforms/test.php",
    data: dataObj,
    dataType: "json", // If you expect a json as a response
    complete: function(data) {
      var Resp = data.responseText;
      console.log(Resp);
    });
  });
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM