How do I setup simple firebase ajax request? - javascript

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
}
}

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");
}
);

Related

AJAX callback does not see jQuery plugin's method

I'm receiving a data from AJAX response and I'm trying to update a jQuery plugin with that value in the success callback:
$.ajax({
url: '/some/url',
type: 'GET',
dataType: 'json',
success: (data) => {
$(".my-rating").starRating('setRating', data.rating);
}
});
I'm using the star-rating-svg plugin to show ratigns (http://nashio.github.io/star-rating-svg/demo/). The problem is that I'm having an error:
Uncaught TypeError: $(...).starRating is not a function
However, this function works perfectly when is called outside AJAX callback. Do you know how to deal with this?
EDIT:
Larger piece of my code:
show.ejs
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/star-svg/src/jquery.star-rating-svg.js"></script>
<link rel="stylesheet" type="text/css" href="/star-svg/src/css/star-rating-svg.css">
</head>
<body>
<div class="my-rating mb-1"></div>
<script>
function getUserRating() {
$.ajax({
url: '/some/url/rating',
type: 'GET',
dataType: 'json',
success: () => {
$(".my-rating").starRating('setRating', data.rating);
}
});
}
function webpageReady() {
if($(".my-rating").is(':visible')) {
$(".my-rating").starRating({
starSize: 20,
disableAfterRate: false,
callback: function(currentRating, $el){
$.ajax({
url: '/some/url/setRating',
type: 'POST',
data: {'rating' : currentRating}
});
}
});
getUserRating();
}
}
</script>
<script type="text/javascript">webpageReady();</script>
</body>
</html>
rating.js
router.get("/some/url/rating", function (req, res) {
Rating.findOne({'author.id': req.user._id}).populate("ratings").exec(function(err, rating){
if(err){
console.log(err);
}
else{
res.send({userRating : rating});
}
});
});
I had the same question, and I figured it out like this - I use jQuery StarRatingSvg v1.2.0:
callback: function(rating, $el){
$.post(
URL,
{ rating: rating, _token : "csrf_token" }
).done(function (resp) {
$el.starRating('setRating', parseFloat(resp.rating), false);
});
}
The callback function has two parameters: rating - the value set by a user when they click the stars, and $el - the rating element.
I hope it helps someone.
Here is simple demo for this plugin
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/star-rating-svg#3.5.0/src/jquery.star-rating-svg.js"></script>
</head>
<body>
<div class="my-rating"></div>
<script>
$(document).ready(function(){
$(".my-rating").starRating({
starSize: 25,
callback: function(currentRating, $el){
// make a server call here
}
});
});
</script>
</body>
</html>
Problem solved: In a footer there was another link to a jquery.

jquery easy autocomplete url function

I'm hoping I can get some help on working with jquery easy autocomplete. I am trying to create a url function that calls an html page that has a javascript xmlrpc function, and returns a list of name in json format. All I get in the web console is:WARNING: Fail to load response data.
Query Page:
<html>
<script src="./js/jquery-3.1.1.min.js" type="text/javascript" ></script>
<script src="./js/jquery.xmlrpc.js" type="text/javascript" ></script>
<body>
<p id="display"></p>
</body>
<script>
$(document).ready(function() {
var url = "https://url.to.my.api/nameapi";
$.xmlrpc({
url: url,
methodName: 'API.FullNameQuery',
success: function(response, status, jqXHR) {
var resp = response + '';
document.getElementById('display').innerHTML = resp;
},
error: function(jqXHR, status, error) { console.log("Error getting information:" + error) }
});
});
</script>
</html>
Easy Autocomplete page:
<html>
<script src="./js/jquery-3.1.1.min.js" type="text/javascript" ></script>
<script src="./js/jquery.easy-autocomplete.min.js"></script>
<link rel="stylesheet" href="css/easy-autocomplete.min.css">
<link rel="stylesheet" href="css/easy-autocomplete.themes.min.css">
<body>
<input id="inputOne" placeholder="Full Name" />
<input id="inputTwo" placeholder="netID" />
</body>
<script>
$(document).ready(function() {
var resp;
var options = {
url: function(phrase) {
return phrase !== "" ?
"https://url.to.my.api/get-people.html" :
"https://url.to.my.api/get-people.html";
},
getValue: "fullName",
ajaxSettings: {
dataType: "json"
},
requestDelay: 300,
theme: "blue-light",
list: {
maxNumberOfElements: 200,
match: {
enabled: true
}
}
};
$("#inputOne").easyAutocomplete(options);
});
</script>
</html>
This is hosted on an IIS server, and I can't use php like the examples show for easy autocomplete. The page returns proper json as I have validated it, so I'm a little confused what it doesn't like it.
I had kind of the same problem if I understand correctly.
I wanted to load an array of data only once, which is not how easy autocomplete works. If you use the URL it will do requests once you type letters.
1) : Create an Easy AutoComplete function that load the settings (re-usable is dope) :
function autoComplete(data_src) {
return {
data: loadManufacturer(data_src),
getValue: "name",
theme: "bootstrap",
list: {
match: {
enabled: true
},
showAnimation: {
type: "fade", //normal|slide|fade
time: 200,
callback: function () {}
},
hideAnimation: {
type: "slide", //normal|slide|fade
time: 200,
callback: function () {}
}
}
};
}
2) : Store the datas in a var
function loadManufacturer(url) {
var tmp = null;
$.ajax({
'async': false,
'type': "GET",
'global': false,
'dataType': 'json',
'url': url,
'success': function (data) {
tmp = data;
}
});
return tmp;
}
3) Call your function in an input :
$("#search_product_manufacturer").easyAutocomplete(
autoComplete(
$("#search_product_manufacturer").attr('data-src')
)
);
You are using Duckduckgo search of easyAutocomplete.
Change your code as follows:
var options = {
.....
ajaxSettings: {
data: {
dataType: "jsonp"
}
},
.....
}
for other Ajax setting, read Ajax settings guide

Computer Vision API for javascript not working[Beginner's error]

I am new to Microsoft Cognitive services and this problem seems to have an easy fix but it has spoiled my two days. I have just copied the Computer vision for javascript code and replaced my the subscription key with mine and opened the .html file in my browser it says error.
DO I have to add something in the code
Also, I have nowt provided any image in this code what's he doing without an image?
The script code is here
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"details": "{string}",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{6e07223403d94848be20af6f126fsssd}");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
code and preview of error
While it's not very obvious, in any code snippet from the Cognitive Service API reference page such as this one that I suspect you were using, you must provide a value (or remove) wherever it shows {something}. Here's code with suitable values:
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var myKey = "6e07223‌​403d94848be20af6f126‌​fsssd";
var myBody = {url:"http://www.gannett-cdn.com/-mm-/2d2a8e29485ced74b7537554043aeae2e0bba202/c=0-104-5177-3029&r=x1683&c=3200x1680/local/-/media/2015/07/18/USATODAY/USATODAY/635728260394906410-AP-GOP-Trump-2016.jpg"}
$(function() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
},
type: "POST",
// Request body
data: JSON.stringify(myBody),
})
.done(function(data) {
alert("success");
debugger;
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>

My Jstree dont show any folder

I'm trying to create a jstree that is connected to my Dropbox API. I want to show all my folders in my Dropbox to jstree but there's no output and there's no error to it just said that:
XHR finished loading: POST "https://api.dropboxapi.com/1/delta".
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax JS Tree</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.3/themes/default/style.min.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.3/jstree.min.js"></script>
</head>
<body>
<div id="container"></div>
<script>
$(function() {
var fullTree;
var url = 'https://api.dropboxapi.com/2/files/alpha/get_metadata';
var access_token = 'I-pZSjTC4tAAAAAAAAAAl1Wpza91KvV_17XKarAsyEMpC78Ereo9-uO2QVE-Sx0a';
$.ajax({
url: url,
data: fullTree,
method: "POST",
dataType: "json",
beforeSend: function(request) {
request.setRequestHeader("Authorization", 'Bearer ' + access_token);
},
success: function(fullTree) {
$('#container').jstree({
'core': {
"data": fullTree,
"check_callback": true,
},
"plugins": ["themes", "contextmenu", "ui"]
});
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
</script>
</body>
</html>
I tried everything including AJAX and jQuery on it but nothing happens.
It seems you put your url variable as data. I think this is a mistake. Isn't it the retrieved json variable you want as data ?
"json_data" : {
"data" :json,
'data' : function (node) {
return { 'id' : node.id };
}

Adding Microsoft's Emotion API to HTML website

I'm trying to simply create a HTML webpage that gives me emotions from images input by the user.
Using Microsoft's documentation I created a HTML file below:
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","my-key");
},
type: "POST",
// Request body
data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("fail");
});
});
</script>
</body>
</html>
My understanding is that this should work without the need of a server, however, I am always getting 'fail' message on loading the website.
Any help would work, thank you!
Use the API testing tool we (Microsoft) have on over here:
https://dev.projectoxford.ai/docs/services/5639d931ca73072154c1ce89/operations/563b31ea778daf121cc3a5fa/console
Ensure you can make a correct request and you are actually setting your api key and not sending my-key on over.
If your key is invalid you'll get an error in the javascript console: 'Access-Control-Allow-Origin' header is present on the requested resource.
If your key is valid but your data is not escaped, you'll get a 400 bad request error. Update your data field to wrap with ''. See my example here (fill in your key) http://jsfiddle.net/w3npr1ue
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","SetYourKey");
},
type: "POST",
// Request body
data: '{"url": "http://1.bp.blogspot.com/-dWka6rPeHZI/UL7newH9TnI/AAAAAAAAAQI/OfU3TW0dDBE/s220/Asa%2Band%2BDada%2Bin%2Bst.%2Bpetersburg%2BSmall.jpg"}',
})
.done(function(data) {
alert("success");
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});

Categories