index.php →
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Build an API</title>
<style>
.btn {
border: 1px solid black;
padding: 10px;
display: inline-block;
}
</style>
</head>
<body>
ID:<input type="number" name="xid" id="xid" value="12"><br>
Name:<input type="text" name="name" id="name" value="tester"><br>
Company:<input type="text" name="company" id="company" value="company"><br>
Cost:<input type="text" name="cost" id="cost" value="cost"><br><br>
<button class='btn' id="btn1">Send Data</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
// $( document ).ready(function() {
$(function () {
$('#btn1').on('click', function () {
var vars = {
xid: $('#xid').val(),
name: $('#name').val(),
company: $('#company').val(),
cost: $('#cost').val(),
}
// var val1 = $('#name').val();
$.ajax({
url: "api.php",
data: vars,
type: "POST",
// dataType: "json"
}).done(function (data) {
console.log(data);
}).fail(function (xhr, textstatus) {
console.log(xhr);
console.log(textstatus);
})
})
})
</script>
</body>
</html>
api.php →
<?php
$con = mysqli("localhost","toolcula_apps","123456##","toolcula_apps");
$arr = [];
if ($con->ping()) { $arr['connected']=true;}else {$arr['connected']=false;}
$sql = $con->prepare("INSERT INTO `ajaxjsonapi` ('xid','cost','name','company') VALUES ('55','55','555', '5555')");
$sql->execute();
$arr['status'] = 'READY';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$arr['id'] = $_POST['xid'];
$arr['name'] = $_POST['name'];
$arr['company'] = $_POST['company'];
$arr['cost'] = $_POST['cost'];
}else {
$arr['name'] = 'No Data Posted!';
}
echo json_encode($arr);
?>
this is giving an error →
That I am unable to correct.
The ready state 4 means that the operation is complete → https://stackoverflow.com/questions/30522565/what-is-meaning-of-xhr-readystate-4#:~:text=State%204%20means%20that%20the,the%20AJAX%20call%20has%20completed.&text=Yes%2C%20it%20is%20correct.,xhr.