I took a code from stackoverflow and created a "index.htm" page where it will also send a json data from html page to php here it is "test.php"
When I am trying to submit the data and seeing in web develop tool I am always getting this error:
jquery.min.js:4 Access to XMLHttpRequest at 'file:///C:/Users/1701053/Desktop/ClientServer%20demo/test.php' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Here is my code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Test.php
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
?>
Note: this is not my own work I am using it as a reference to understand how to actually send a Json object to server using javascript only