Laura Morris
Laura Morris

Reputation: 222

Ajax not being called by select

Hi I have a select box that when it is changed I want the value in a database to be updated via Ajax. Using the console I can see that my saveedit2.php file is not being called.

Select Box

    <form><select id="workingpattern">
    <?php
              if(isset($workingpatterns) && !empty($workingpatterns)){
              foreach($workingpatterns as $k4=>$v4) {
              ?> 

    <option value="<?php echo $workingpatterns[$k4]["workingpatternid"]; ?>"> 
<?php echo $workingpatterns[$k4]["text"]; ?></option>
    <?php }}?>
    </select></form>

Ajax:

 <script>

$(document).ready(function(){

 $('#workingpattern').change(function(){
    var e = document.getElementById("workingpattern");
    var value = e.options[e.selectedIndex].value;

    $.ajax({
        url: "saveedit2.php",
        type: "post",
        data: value,
        success: function(data) {

           console.log(data);
        }});

});

</script> 

SaveEdit2.php

<?php
require_once("connect_db.php");

$value=$_POST['value'];

$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
?> 

Upvotes: 0

Views: 49

Answers (2)

Mint
Mint

Reputation: 189

Try

Ajax

$('#workingpattern').change(function(){
    var value = $("#workingpattern").val();

            $.ajax({
              dataType: "json",
              url: "./saveedit2.php",
              data: {'value':value},
              success: function(data){
                  if(data['result']=="ok")       
                       alert("Done");
                  else
                      alert("Error");
              }
            });

SaveEdit2.php

<?php
require_once("connect_db.php");
$ajax_result = "error";
$value=$_POST['value'];

$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
if($result)
$ajax_result = "ok";

echo json_encode(array('result'=>$ajax_result));

?> 

Upvotes: 0

fanfavorite
fanfavorite

Reputation: 5199

There are a few issues that I see. First, I would use 'this' to get the element and use jQuery to get the value since you are using it already. Secondly, you need a name for the value in the data set:

$('#workingpattern').change(function(){
    var value = $(this).val();
    $.ajax({
        url: "saveedit2.php",
        type: "post",
        data: 'value='+value,
        success: function(data) {
           console.log(data);
        }
    });
});

Upvotes: 1

Related Questions