Jeancarlo C. Jeancarlo C. - 3 months ago 16
Ajax Question

Ajax success but I can't insert data into MySQL database

SETUP ENVIROMENT : 000webhost

I'm using chrome's developer tool to track my ajax request through a simple button ("Turn on") and It seems working fine from javascript side.

(My webpage currently: here)

My problem is that even though ajax make a success call to 'ajax.php', once is called It doesn't insert anything to my table 'dogcare' mysql database.
click here to see my table

This is index.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Estacionamiento</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="viewport" content="width=device-width">
</head>
<body>
<h1 class="title"> Dog Care </h1>
<script src="https://meet.jit.si/external_api.js"></script>
<div class="chart">
<div class="video">
<script>
var domain = "meet.jit.si";
var room = "dogcare";
var width = 700;
var height = 700;
var api = new JitsiMeetExternalAPI(domain, room, width, height);
</script>
</div>
<div class="buttons">
<input type = "submit" name ="on" id="on" value = "Turn On">
<input type = "submit" name ="off" id="off" value = "Turn Off">
</div>
</div>

<script src="js/jQuery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert("jquery is working");
$("#on").click(function(){
var accion = "feed";
var flagtime = "no";
var lunchtime = "13:00";
$.ajax({
url: "ajax.php",
type: "POST",
async: false,
data: {
"done": 1,
"accion": accion,
"flagtime": flagtime,
"lunchtime": lunchtime
},
success: function(data){
alert("ajax successfull");
}
})
})

})


</script>
</body>
</html>


This ajax.php

<?php

if (isset($_POST['done'])) {
$link = new mysqli("localhost", "myuser", "mypassword", "my_db");

if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$accion = $_POST['accion'];
$flagtime = $_POST['flagtime'];
$lunchtime = $_POST['lunchtime'];

mysqli_query($link, "INSERT INTO 'dogcare' ('accion', 'flagtime','lunchtime') VALUES ('{$accion}', '{$flagtime}','{$lunchtime}')");
exit();
}
?>




I would appreciate any help and if anyone can tell me how to check if there's a connection to my database ( I'm quite sure It is but I'd like to see "server connection: OK" or something like that ). Also I'm quite new to php language.

P.S: BTW Button turn off doesn't do anything yet.

I let 2 alerts to see if jQuery is working and if there's an ajax call.

Answer

Check your code, don't use ' for column or for table names, use " " it, like below. P.S I don't understand why you are using{braces}` )

mysqli_query($link, "INSERT INTO `dogcare` (`accion`, `flagtime`,`lunchtime`) VALUES ('{$accion}', '{$flagtime}','{$lunchtime}')");