Nick Nick - 7 months ago 21
PHP Question

No feedback if sql insert succeeded

I'm performing following scenario :

When I press a button I insert this into the database and that's working. But i don't get feedback if it succeeded or not (the alerts wont pop up). But if I look in my database it is inserted

if(isset($_POST['action']) && $_POST['action'] > 3)
{
$message = 'success';
$message1 = 'failed';
$conn = new mysqli($servername, $username, $password, $dbname);
$values = $_POST['action'];
$status = 'pending';
$sql = "INSERT INTO queue (value, status) VALUES ('".$values."', '".$status."')";
if ($conn->query($sql) === TRUE) {
?>
<script type='text/javascript'>alert("<?php echo $message; ?>");</script>
<?php } else { ?>
<script type='text/javascript'>alert("<?php echo $message1; ?>");</script>
<?php }
}
}
?>


This is the button and inputfield I use to insert the value in the database:

<input type="text" id="number"><br>
<button type="button" class="btn btn-success" id="test" onclick="myAjax(number.value);">test</button>


and this is the ajax call:

function myAjax(value) {


$.ajax({
type: "POST",
url: 'test.php',
data:{action:value},
dataType: 'text',
success: function(data) {

}

});
}

Answer

Ok so I did it with a workaround, not really how I wanted it but its working now so. Basically I handled it in the Ajax success function instead of in the php file.

instead of this

if(isset($_POST['action']) && $_POST['action'] > 3) 
    {
    $message = 'success';
    $message1 = 'failed';
        $conn = new mysqli($servername, $username, $password, $dbname);
        $values = $_POST['action'];
        $status = 'pending';
        $sql = "INSERT INTO queue (value, status) VALUES ('".$values."', '".$status."')";
        if ($conn->query($sql) === TRUE) {
echo $message; 
} else { 
echo $message1;
}                                    
    }       
    }
?>

And this

function myAjax(value) {


  $.ajax({
       type: "POST",
       url: 'test.php',
       data:{action:value},
       dataType: 'text',
       success: function(data) {

       }

  });
}

I now have this :

if(isset($_POST['action']) && $_POST['action'] > 3) 
    {
    $message = 'success';
    $message1 = 'failed';
        $conn = new mysqli($servername, $username, $password, $dbname);
        $values = $_POST['action'];
        $status = 'pending';
        $sql = "INSERT INTO queue (value, status) VALUES ('".$values."', '".$status."')";
        if ($conn->query($sql) === TRUE) {}                                    

    }
?>

and this :

function myAjax(value) {




    $.ajax({
           type: "POST",
           url: 'test.php',
           data:{action:value},
           dataType: 'text',
           success: function(data) {
           if(value > 3 && value != undefined && value != "")
           {
            alert("working");
           }
            else
           {
            alert("not working");
           }
               }

      });
    }
Comments