Chris Yates
Chris Yates

Reputation: 243

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)
        });

Upvotes: 0

Views: 30

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

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>

Upvotes: 1

Related Questions