Chris Yates
Chris Yates

Reputation: 243

Updating Database on Input change - jQuery

I have tried answers from various questions here and also from examples on google, however, none seem to be workings not sure what I am doing wrong.

I have the following code

<form>
<input type="text" id="regoffice_1" value="<?php echo $result['regoffice_1'];?>">
<input type="hidden" name="companyid" value="1">
</form>
<script>
$("#regoffice_1").on("change", function() {
  var itemVal = $("#regoffice_1").val();
  var dataObj = {companyid: $("#companyid").val(), regoffice_1: $("#regoffice_1").val()};

  processChange(dataObj);
});

function processChange(dataObj){

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

In the PHP file just a simple query

<?php
include('../config.php');
mysqli_query($dbc,"UPDATE `comp_companies`  SET `regoffice_1` = '$_POST[regoffice_1]' WHERE `company_id` = '$_POST[companyid]'");
?>

Nice and simple .. however I'm getting no errors shown or anything shown in the console and no data being updated

What am I missing ??

Upvotes: 2

Views: 1347

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

You must add an id to your input :

<input id="companyid" type="hidden" name="companyid" value="1">
_______^^^^^^^^^^^^^^

Since you're selecting by id in :

{companyid: $("#companyid").val(), regoffice_1: $("#regoffice_1").val()};
_____________^^^^^^^^^^^^^^

Else you could use name selector instead like :

{companyid:  $('input[name="companyid"]').val(), regoffice_1: $("#regoffice_1").val()};

NOTE : You need to add quotes to your $_POST[]:

mysqli_query($dbc,"UPDATE comp_companies  SET regoffice_1 = '".$_POST["regoffice_1"]."' WHERE company_id = '".$_POST["companyid"]."'");

Upvotes: 3

MathRak
MathRak

Reputation: 46

Following @Zakaria's answer you also using

...'$_POST[regoffice_1]' and '$_POST[companyid]' 

in your UPDATE. You missed the quotes on $_POST['key'] as it's an associative array

"UPDATE `comp_companies`  SET `regoffice_1` = ' . $_POST['regoffice_1'] . ' WHERE `company_id` = '" . $_POST[companyid] . "'"

Upvotes: 0

Related Questions