I have writtent this script to send notification from my HTML page.
When i try to send the request, i get both messages "Success" and "Fail" and the notification is not sent. I call the function get_data_for_notification() on button click.
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function get_data_for_notification(){
var title = document.getElementById('news_title').value;
var subtitle = document.getElementById('news_small_description').value;
$.ajax({
type : 'POST',
url : "https://fcm.googleapis.com/fcm/send",
headers : {
Authorization : 'key=mykey'
},
contentType : 'application/json',
dataType: 'json',
data: JSON.stringify({"to": "/topics/android", "priority" : "high", "notification": {"title":title,"body":subtitle}}),
success : alert("Success") ,
error : alert("Fail")
}) ;
}
</script>
Your script executes, before sending the request, alert("Success") and alert("Fail") and assigns their return value as the event handlers.
You have to wrap them in an anonymous function:
$.ajax({
type: 'POST',
url: "https://fcm.googleapis.com/fcm/send",
headers: {
Authorization: 'key=mykey'
},
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
"to": "/topics/android",
"priority": "high",
"notification": {
"title": title,
"body": subtitle
}
}),
success: function(responseData) {
alert("Success");
}
error: function(jqXhr, textStatus, errorThrown) {
/*alert("Fail");*/ // alerting "Fail" isn't useful in case of an error...
alert("Status: " + textStatus + "\nError: " + errorThrown);
}
});
The problem was on the button type, i needed to use type="button" and not type="submit".
Related
I am a beginner to programming and for a challenge I need to get the status (Streaming live/Off-line) for a given number of channels.
I wrote an ajax request but I am still getting 401 as a response. Below my code and a screen shot of the response.
I have even made the token request as async: falseto make sure the token is back before triggering the API call
$("document").ready(function() {
var aoathToken = $.ajax({
type: "POST",
url: "https://id.twitch.tv/oauth2/token?client_id=MYCLIENTID&client_secret=MYSECRET&grant_type=client_credentials",
error: function() {
console.log("Check your request!!")
},
success: function(token) {
console.log(token);
}
})
$.ajax({
type: "GET",
url: "https://api.twitch.tv/helix/streams?user_id=freecodecamp",
contentType: ('application/x-www-form-urlencoded; charset=UTF-8'),
crossDomain: true,
header: {
"Access-Control-Allow-Origin": "*",
"Client-ID": "MY CLIENT ID",
"Authorization": "Bearer " + aoathToken,
},
data: {"user_login": "myUserID"},
dataType: "json",
success: function(json) {
console.log(JSON.stringify(json, null, 2));
},
error: function(json) {
window.alert(json.status + " " + json.message);
},
})
When i open using the Google chrome browser this url http://www.site.nl/a/b/c/d/e?niss=f, it first ask for username password:
Manually when i put the username password i get some data.
Now, using jQuery how can i submit that username password? following is not working, always after submit its failing with "401 unauthorized"
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.site.nl/a/b/c/d/e?niss=f",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic Username1:password1234"
},
data: '{ "test" }',
success: function (data, textStatus, jqXHR){
console.log(data, textStatus, jqXHR);
}
});
});
Please try following code
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.site.nl/a/b/c/d/e?niss=f",
dataType: 'json',
async: false,
data: '{ "test" }',
beforeSend: function(xhr)
{
xhr.setRequestHeader('Authorization', make_base_auth("Username1", "password1234"));
},
success: function (data, textStatus, jqXHR){
console.log(data, textStatus, jqXHR);
}
});
});
function make_base_auth(user,password)
{
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
} // ends
I'm sending this request, and it is perfectly fine as long as it's successful. However, if I try to create a user with existing username or email, I should get 400 bad request and response detailing what's the problem.
Thing is, when I send this request and get 400, nothing gets written to console/console (not even the 'fail!' string), but I can see that response is correct in console/network tab so the problem is probably not in the backend.
$("#registerForm").submit(function(e){
e.preventDefault()
$.ajax({
type: "POST",
url: "./register",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
"username": formcontent['username'],
"email": formcontent['email'],
"password": formcontent['password'],
}),
success: function(e) {
window.location.href = './login'
return false
},
fail: function(e) {
console.log('fail!')
console.log(e)
//react to error
return false
},
})
})
I think 'fail' is a invalid function, Please try with below structure
$.ajax({
type : "POST",
url : "/register",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : JSON.stringify({
"username" : formcontent['username'],
"email" : formcontent['email'],
"password" : formcontent['password'],
}),
success : function(response) {
console.log(response);
},
error : function(response, status, err) {
console.log(response);
console.log(status);
console.log(err);
}
});
$.ajax({
type: 'POST',
url: 'http://apius.faceplusplus.com/detection/detect',
crossDomain: true,
cache: false,
async: true,
data: '{ "comment" }',
dataType: 'jsonp',
success: function(responseData) {
alert(JSON.stringify(responseData));
},
error: function (responseData, textStatus, errorThrown) {
alert(JSON.stringify(responseData));
}
});
I am sending a post request to above which requires api_key and api_secret parameters for authentication. I tried sending value of this 2 paramenters like this in above request:
headers:
{
"Authorization": "Basic " + Base64.encode('value of api key here' + ":" + 'value of api secret here')
},
But when I execute the request it says 400 BAD REQUEST and when I hit the url in browser it shows
{
"error": "MISSING_ARGUMENTS: api_key",
"error_code": 1004
}
Please suggest me a solution. I am stuck for long time.
Pass the key/value pairs in the data object of the ajax request, like this:
data: '{ "api_key": "thekeyhere", "api_secret": "thesecrethere" }'
I'm trying to make an ajax request to the google contacts API with the following setup:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/#me/#all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
headers: {
'Authorization': 'Bearer ' + token
},
success: function(data, status) {
return console.log("The returned data", data);
}
});
But the Authentication header doesn't seem to get set. Any ideas?
I had the same problem recently. Try this:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/#me/#all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
success: function(data, status) {
return console.log("The returned data", data);
},
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer ' + token); }
});
EDIT: Looks like it can't be done with JSONP. Modify HTTP Headers for a JSONP request
When authentication is needed in a cross domain request, you must use a proxy server of some sort.
Since using dataType: jsonp results in the HTTP request actually being made from the script that gets added to the DOM, the headers set in the $.ajax will not be used.
Is seems that most of the OAUTH2 REST resources accept the access_token parameter as part of the request url
http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#query-param
please, try the following code instead:
$.ajax({
dataType: 'jsonp',
url: url,
data: {
'access_token':token.access_token
},
jsonpCallback: 'thecallback',
success: function(data){
_cb(data);
},
error: function(d){
_cb(d);
}
});
Just do this (jquery 2.0, but should work in previous versions)
$.ajax({
url: "/test",
headers: {"Authorization": "Bearer " + $('#myToken').val()}
})
.done(function (data) {
console.log(data);
})
.fail(function (jqXHR, textStatus) {
alert("error: " + textStatus);
});