Reputation: 3054
I know I can use set to hit Firebase, but I want to use AJAX instead so I tried the below code. When I load test.html in my browser, the console says -
XMLHttpRequest cannot load https://jleiphonebook.firebaseio.com/json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
//text.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Firebase Test</title>
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
</head>
<body>
<div id="hi"></div>
<script src="https://code.jquery.com/jquery-1.12.2.min.js" integrity="sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=" crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
var param = {lastName: "Doe", firstName: "John"};
$.ajax({
url: 'https://jleiphonebook.firebaseio.com/json',
type: "POST",
data: param,
success: function () {
alert("success");
}
});
});
</script>
</body>
</html>
//firebase rules
{
"rules": {
".read": true,
".write": true
}
}
Upvotes: 2
Views: 12540
Reputation: 599041
Firebase expects the body to be a JSON string, so you'll need to stringify it:
$(document).ready(function () {
var param = {lastName: "Doe", firstName: "John"};
$.ajax({
url: 'https://jleiphonebook.firebaseio.com/.json',
type: "POST",
data: JSON.stringify(param),
success: function () {
alert("success");
},
error: function(error) {
alert("error: "+error);
}
});
});
This will accomplish the same by the way:
$.post('https://jleiphonebook.firebaseio.com/.json',
JSON.stringify(param),
function () {
alert("success");
}
);
Upvotes: 3