Step-by-Step Guide to Sending Push Notifications via GCM with XHR (Ajax)

I have successfully used this curl command to send notifications through the terminal. However, I am now looking for a way to trigger the notification on a button click by using an XHR request instead.

curl --header "Authorization: key=AIzaSyCjrU5SqotSg2ybDLK0dMusvY" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"f5xzshqcfDE2qiKGJu858nFhqGCuk0uuUC6vm\"]}"

Answer №1

If you need to achieve a specific task, consider creating a PHP script and then sending an XHR request using client-side technologies like JavaScript. Below is an example of a PHP script that I wrote a few months ago and verified its functionality:

    <?php
    $message = "\": 3,\"title\": \"High score alert!\",\"\": true,\"custom_field\": { \"score\": 51,\"headlines\": \"And now for something completely different...\" }}";
    $apiKey = "Your Key";
    $registrationIDs = array("Registration id");
    $url = 'https://android.googleapis.com/gcm/send';
    
    // Define POST variables
    $notify = array(
       "alert"=> "great match!",
      "title"=> "Portugal vs. Denmark",
      "icon" => "myicon",
      "badge"=>3,
      "vibrate"=>true,
    "notification"=>"message"
    );

    $fields = array(
    'registration_ids' => $registrationIDs,
    'data' => array( "payload"  => $notify,
    "notification"=>json_encode($notify)));
    $headers = array(
    'Authorization: key=' . $apiKey,
    'Content-Type: application/json'
    );
    $ch = curl_init(); // Initialize connection
    curl_setopt($ch, CURLOPT_URL, $url );
    // Set the URL, number of POST vars, and POST data
    curl_setopt($ch, CURLOPT_POST, true );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields ));
    var_dump( $url );
    var_dump($headers);
    var_dump(json_encode( $fields ));
    $result = curl_exec($ch);   // Execute POST
    if($result === false)
    die('Curl failed ' . curl_error());
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $response = json_decode($result);
    print_r($response);
    ?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for incorporating your personal touch while utilizing Snipcart

I have created an ecommerce platform with GatsbyJS and Snipcart, but I am struggling to override the default theme provided by Snipcart. When I try to change the main default CSS through gatsby-config.js, it does not seem to work. Does anyone have a soluti ...

AngularJS dynamic resources allow for web applications to access and

I have created a directive for a search form that provides a template with a <form> tag, automated messages such as "No results found," and an optional suggestion message like "You can search by name or id." However, I am facing an issue where I nee ...

Guide to seamlessly navigating to an element using a hash in NuxtJS

My aim is to create a smooth scrolling anchor link menu using Nuxt.js, where the user can click on a link and be directed to the corresponding page section. However, I'm facing a dilemma as there are multiple approaches to achieve this functionality, ...

Why does Javascript in Angular throw an exception when using value, match, and replace functions together?

I have a small JavaScript function that I would like to implement in an Angular service or controller. function cprCheck(frm) { var cpr = frm.cpr.value; if (cpr.match(/[0-9]{6}\-[0-9]{4}/)) { cpr = cpr.replace(/\-/g, ""); var chk = 0; ...

Filling form fields with array data (AngularJS)

Although I'm new to AngularJS, I'm struggling to figure out how to handle a list of arrays returned from the searchAll function. console 0: {mobile: "12345678", lastname: "last01", firstname: "first01"} 1: {mobile: "87654321", lastname: ...

What are some ways to divide drop targets with React DnD?

In my React Dnd v16.0.1 project, I am dynamically rendering containers and images from JSON data using map function. The issue I'm facing is with two droppable containers where only one should accept dropped images. However, when I drop an image on th ...

Dynamic display of images using AJAX and ASP.NET web service

I'm currently facing an issue while trying to generate and retrieve an image of a chart using AJAX to call a Webservice. Despite successfully creating the chart and converting it into an image, I am unable to receive the image back in my AJAX call. H ...

I would like to inquire about the process of accessing profile information on a website through the LinkedIn API

Do you know how I can use the latest LinkedIn JavaScript API with OAuth 2.0 to retrieve my own profile details for a website? The goal is to automatically update the website using my linked profile information. I have attempted the following: api_key: ...

Getting the value of a Datatables column is simple- just follow these steps

I am trying to extract the value of a Datatable column. Below is the script I am using: $(function () { $('#kategoriTable').DataTable({ "paging": true, "lengthChange": true, "searching": true, ...

The tubular.js Youtube video background is overlapping my other components on the site, instead of displaying behind them as intended

I recently implemented the tubular.js script on my webpage to display a YouTube video as the background. On the tubular page, there is a statement that reads: First, it assumes you have a single wrapper element under the body tag that envelops all of ...

The media query appears to be ineffective on the footer section when accessed from a mobile device, yet it functions properly when adjusting the browser's screen size

I'm facing an issue with the footer section of my website. It appears very responsive when viewed from a desktop or tablet, but when I open the site on my mobile phone, the footer looks unstyled. Here is how it appears on desktop at 360px: enter ima ...

Performing date comparison in JavaScript with varying date formats

My system includes a table that retrieves dates from an FTP location. On the user interface page, there is a form that gathers all details related to a specific FTP date. However, I am facing difficulties in comparing the FTP dates with those specified in ...

Exploring Next JS v13: Implementing font-weight variation from Google Fonts with the help of @next/font

Since the release of Next JS v13, utilizing @next/font has been crucial for optimizing performance. Previously, I would include Google fonts using the CDN @import in my global CSS file. /* path: ./styles/global.css */ @import url("https://fonts.google ...

When the boolean in RxJS skipWhile remains true

My current scenario involves a specific use-case: There is a service that queues calculation tasks assigned with a certain ID. I have set up an observable to monitor the status of the service. When the ID is still in the queue, the query result is true (i ...

What are the steps to generate an HTML table using the DOM model with JavaScript?

Can you guide me on how to use the DOM model in Javascript to create an HTML table? For example: <table width="100%" border="0" cellspacing="0" cellpadding="0" id="tblMCNRoles"> </table> I have the table above and I would like to render ...

Tips for inserting a row component into a table using Angular 7

I am currently using the latest version of Angular (7.2.0). I have created a custom tr component as follows: import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-table-row', templateUrl: './table- ...

Comparing XDomainRequest and XMLHttpRequest for IE8 and IE9: A detailed analysis

I am feeling pretty lost when it comes to understanding the XMLHttpRequest and XDomainRequest renaissance, and I could really use some guidance. Here are my thoughts so far: It seems like the XDomainRequest in IE8 and IE9 is some sort of subclass of XMLH ...

Sending information with JSON using POST request through AJAX with PHP

Hello everyone! I have encountered a problem with my JavaScript/jQuery code and the way PHP is handling JSON input as an array. In my rate.php file, I am using print_r($_POST) to display the data, but it seems like PHP is not recognizing the JSON input cor ...

Trouble with ES6 Arrow Functions, Syntax Error

I am encountering an issue with my JS class structure: class Tree { constructor(rootNode) { this._rootNode = rootNode; rootNode.makeRoot(); } getRoot() { return this._rootNode; } findNodeWithID(id) ...

Embedding HTML code within JavaScript

At certain times, I find myself needing to assign an HTML snippet to a JavaScript variable. For example: var homePage = '<div>' + '<div class="header"><h1>Page Slider</h1></div>' + &apo ...