How to send push notifications in Chrome(Progressive Web Apps) - ajax

Please explain how to do push notifications with XHR and Javascript. or is there any other way to send push notifications in progressive web apps. I have created curl command and when i execute it in my terminal push notification sent but how to do it on button click?
Here is my cURL command:-
curl --header "Authorization: key=AIzaSxUdg" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"cxA-dUj8BTs:APAvGlCYW\"]}"
This is what i have tried :-
function send()
{
navigator.serviceWorker.ready
.then(function(registration) {
registration.pushManager.getSubscription()
.then(function (subscription) {
curlCommand(subscription);
$.ajax({
url: "https://android.googleapis.com/gcm/send",
headers: {
Authorization: "key=AIzaSxUdg",
},
contentType: "application/json",
data: JSON.stringify({
"registration_ids": [endpoint]
}),
xhrFields: {
withCredentials: true
},
crossDomain: true,
type:"push",
dataType: 'json'
})
.done(function() {
alert('done');
})
.fail(function() {
alert('err');// Error
});
})
})
}
But it shows error -----
XMLHttpRequest cannot load https://android.googleapis.com/gcm/send. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8880' is therefore not allowed access..

Google API is intended to be used from a server so it is not including CORS headers.
As you are performing a cross origin XHR (from your domain to Google's domain), the User Agent makes a preflight request in search of the CORS headers that tell your client is authorized to perform operations.
To do this you need to make a request to your server (i.e. a POST on /notifications/send) and your server should then execute the cURL request to GCM.

This will work:
function send()
{
navigator.serviceWorker.ready
.then(function(registration) {
registration.pushManager.getSubscription()
.then(function (subscription) {
curlCommand(subscription);
$.ajax({
url: "https://cors-anywhere.herokuapp.com/https://android.googleapis.com/gcm/send",
headers: {
Authorization: "key=AIzaSxUdg",
},
contentType: "application/json",
data: JSON.stringify({
"registration_ids": [endpoint]
}),
xhrFields: {
withCredentials: true
},
crossDomain: true,
type:"push",
dataType: 'json'
})
.done(function() {
alert('done');
})
.fail(function() {
alert('err');// Error
});
})
})
}

Related

How to submit Salesforce's Web to Lead Forms with AJAX instead of the default submission?

I am trying to submit my webtolead form, somethinf that is so simple and basic jQuery, But I am getting CORS origin error :
<script>
// https://www.domainName.my.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8
function postFormAjax(formData) {
$.ajax({
method: "POST",
type: "POST",
url: "https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8",
headers: {
'Access-Control-Allow-Origin': '*'
},
data: formData,
processData: false,
contentType: false,
crossOrigin: true,
crossDomain: true,
error: function (jqXHR, textStatus, errorMessage) {
if (textStatus == "error") {
console.log(jqXHR);
console.log(textStatus);
console.log(errorMessage);
}
},
success: function (data, textStatus, xhr) {
console.log(data);
}
});
}
postFormAjax({ first_name: "test", email: "test#gmail.com" })
</script>
This is the error :
Access to XMLHttpRequest at
'https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8'
from origin 'null' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
I allowed localhost on my Salesforce SETUP :
Also I feel like there is something important about this field :
I don't find many clear guides on how to submit webtolead forms via XMLHTTPSREQUEST !!
Any help or indication here would be much appreciated.

How i can send delete request for to delete video in AJAX, its returning 204 status

I'm trying to delete my vimeo video by using AJAX request but its always returning 204 status code, and video is not deleting from account. Here is code example.
$(".js-delete").click(function(){
var videoID = $(this).data("target");// /videos/2332
$.ajax({
type: "post",
url: "https://api.vimeo.com/me/videos",
headers: {
"Authorization": "bearer xxxxxxxxxxxxxxx"
},
data: {
url: "https://api.vimeo.com/me"+videoID,
method: "DELETE"
},
dataType: "json"
success: function(response){
console.log(response); //will print the whole JSON
},
error: function(){
console.log('Request Failed.');
}
});
});
Can anyone please suggest some changes required for this?
Thanks in advance
You are sending
a HTTP POST
to the URL https://api.vimeo.com/me/videos
with the Bearer token as a header
Note that it should be Bearer <token> (uppercase B), not bearer <token>.
with a data packet that contains another URL and HTTP method.
But according to the Vimeo API docs to Delete a Video, the request should be
DELETE https://api.vimeo.com/videos/{video_id}
with a note:
This method requires a token with the "delete" scope.
A jQuery ajax request should look something like this if the bearer token is correct:
$(".js-delete").click(function(){
var videoID = $(this).data("target");// /videos/2332
$.ajax({
type: 'DELETE',
url: 'https://api.vimeo.com/videos/' + videoID,
headers: {
"Authorization": "Bearer xxxxxxxxxxxxxxx"
},
success: function(response){
console.log(response); //will print the whole JSON
},
error: function(){
console.log('Request Failed.');
}
});
});
You should be able to test this request using https://www.getpostman.com/ to verify the request and bearer token works outside of your CF app.

Laravel Authentication with Passport,how send token Bearer in ajax header inside laravel project

I can get response from RESTful api when using Postman with Authorization Bearer + token.
But How can I send request with token in ajax (i made it inside my laravel project).
$.ajax({
url: "url",
headers: {
'Authorization': authorizationToken,
},
type: "post",
data: data,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (data) {
},
error: function (data, status, error) {
}
});
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN":$('meta[name="csrf-token"]').attractive('content')
"Authorization":"Bearer"+localStorage.getItem('token')
}
});

Request headers not passed when proxying with Apache HTTPD server

I have set up a proxy on Apache HTTP server for making the cross domain Ajax call. The call is happening but is returning a response indicating that the API key passed as a request header is invalid.
Can you make cross domain Ajax calls using Apache web server proxy? If so what am I doing wrong. ?
The proxy setting is as follows:
ProxyPass /api-temp/* http://api.temp.com/
The code to make the Ajax call is as follows:
var imageNamespace = {
imageUrls: [ ],
url: '/api-temp/v1/data/cat/42736286',
test: function() {
alert(234);
},
getImages: function() {
$.ajax({
type: 'GET',
dataType: 'json',
cache: true,
headers: {'API_KEY': 'xxxxxxxxxxxxxxxxxxxxxxxxx'},
url: imageNamespace.url,
success: function () {
alert('success:', success);
},
error: function (error) {
alert('ERROR:', error);
},
complete: function () {
alert('complete');
}
});
},
}
Here is the response in the browser:
The URL it is invoking is as follows: http://api.temp.com/v1/data/cat/42736286
Please enter valid API Key
I am passing the key in the request header but it is not being picked up. Any insight on how to resolve this will be helpful.

jQuery Ajax POST Failing

I can't get my AJAX request to complete successfully. It's for the bearere token on Twitter's API. I have done successfully in a HTTP request client as shown below:
But I can't replicate this in code:
$.ajax({
type: 'POST',
url: 'https://api.twitter.com/oauth2/token',
headers: {
'Authorization':'Basic ' + base64EncodedBearerTokenCredentials,
},
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: {
'grant_type': 'client_credentials'
},
error: function(xhr, status, error) {
},
success: function(response){
},
});
I'm getting a 405, but because I have the Authorization header in I can't see the response in Firebug.
What is it?
Thanks.

Resources