The objective of task is to insert data into postgresql using ajax in PhP, The page should not refresh, It just insert the data and display the message to user that operation successful.
I followed Insert Data mysql using Ajax and PHP, to do my coding for insert data into postgresql database. But there is some unknown issue. The control even don't go to page on server where I am inserting inputs to database. I put both client and sever side code in the same folder to avoid any issue because of path. My client side code is: alta_usuari.php
<!DOCTYPE html>
<html>
<head>
<style> <?php include './../css/alta_usuari.css'; ?> </style>
<script src='http://code.jquery.com/jquery-3.1.1.min.js'></script>
<script>
$(document).ready(function() {
$('#button_alta').click(function(event) {
event.preventDefault();
console.log("about to start AJAX call");
var bracalet = $('#textbox_bracalet').val();
var tag = $('#textbox_tag').val();
$.ajax({
type: "POST",
url: 'pages/alta_usuari_server.php',
data: {
bracalet: bracalet,
tag: tag
},
success: function(data) {
console.log(tag);
console.log(result);
alert(result);
$("#message").html(data);
alert('data has been storeds to database');
}
});
});
});
</script>
</head>
<body>
<div id="mainDiv_alta_usuari">
<form id="form_alta_usuari" class="form_alta_usuari">
<p><input type="text" name="bracalet" id="textbox_bracalet" placeholder="Escaneja el bracalet...." /></p>
<p><input type="text" name="tag" id="textbox_tag" placeholder="Escaneja el tag...." /></p>
<p><input type="submit" id="button_alta" value="Donar d'alta" /></p>
</form>
<div id="message"> </div>
</div>
</body>
</html>
alta_usuari_server.php code
<html>
<body>
Bracalet: <?php echo $_POST["bracalet"]; ?><br>
Tag: <?php echo $_POST["tag"]; ?>
<?php
header("Content-Type: application/json; charset=UTF-8");
$mac=$POST['tag'];
$bracalet=$POST['bracalet'];
$ini = parse_ini_file('config.ini');
$host=$ini['host'];
$port =$ini['port'];
$user =$ini['user'];
$pass =$ini['password'];
$db = $ini['db'];
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "INSERT INTO beacon VALUES($mac)";
$result = pg_execute($con, $query) or die("Cannot execute query: $query\n");
if($result)
{
$data="Insert successfully";
}
else{
$data="Error";
}
echo json_encode($data);
pg_free_result($data);
pg_close($con);
?>
</body>
</html>
simplest alta_usuari_server.php
<?php
$mac=$_POST['tag'];
$bracalet=$_POST['bracalet'];
echo $mac;
echo $bracalet;
$data="tahir";
echo json_encode($data);
?>