Pressing the send button will trigger an alert control with the value being sent as the

In my application, I had the idea to implement a straightforward panic button. The functionality of this button is as follows:

When a user clicks on the panic button, an alert will appear providing them with predefined groups that they can send a panic message to.

1) If the user selects the committee group, the panic message will only be sent to users with the role of committee.
2) If the user selects "All," the panic message will be sent to all members of the application.

I was unsure how to pass the specific value to the button click event. The groupList variable contains all the group names. Here is the code snippet:

     sendTextMessage() {

    let Groups: any = [];
    firebase.database().ref('panic_group').orderByKey().once('value', (items: any) => {

      items.forEach((item) => {
        Groups.push(item.val().Group_name);
        this.groupList = Groups;
      });

    let alertConfirm = this.alertCtrl.create();
    alertConfirm.setTitle('Choose Group');

    // Add new groups here!

    this.groupList.forEach(group => {
      alertConfirm.addInput({
            type: 'radio',
            label: group,
            value: group.toLowerCase(),
            checked: group === group.toLowerCase()
        });
    });

    // ...
    alertConfirm.addButton({
            text: 'Cancel',
            role: 'cancel',
            handler: () => {
              console.log("Cancel clicked");
            }
    });
    alertConfirm.addButton({
      text: 'Send',
          handler: () => {
            console.log("Send clicked");
           alert('cnt' + this.contacts);

            var request = new XMLHttpRequest();
            request.open("POST", "https://control.msg91.com", true);
            request.setRequestHeader("Access-Control-Allow-Origin", "*");

            var settings = {
              "async": true,
              "crossDomain": true,
              "url": "http://api.msg91.com/api/v2/sendsms",
              "method": "POST",
              "headers": {
                "authkey": "198608A17R3Rqgwdh5a87f2ae",
                "content-type": "application/json"
              },
              "processData": false,
              "data": "{ \"sender\": \"SOCKET\", \"route\": \"4\", \"country\": \"91\", \"sms\": [ { \"message\": \"Panic Alert from Flat No " + this.flatNo + "\", \"to\": [ " + this.contacts + " ] }, { \"message\": \"Test Panic Alert from Flat No " + this.flatNo + "\", \"to\": [ " + this.contacts + " ] } ] }"


            }
            alert(settings.data);
            console.log(settings.data);
            jQuery.ajax(settings).done(function (response) {
              console.log(response);
              alert('res' + response);
              alert("Sms Sent!");
            });
          }
     });

    alertConfirm.present();
    });
  }

Answer №1

I successfully resolved this issue on my own.

loadContacts(userGroup : string) {

 let contacts: any = [];

if(userGroup === 'Commitee Member'){

   var ref = firebase.database().ref("users");
   ref.orderByChild("role").equalTo(userGroup).once("value", (items: any) => {

    items.forEach((item) => {
      if (item.val().contact_no != '0') {
        contacts.push({
          cnt:item.val().contact_no,
          flatNo:item.val().flatno
        });
      }
      this.contactList = contacts;

    });

    var length = this.contactList.length;

    if (length > 0) {
      for (var i = 0; i < length; i++) {

          this.contacts.push('<SMS TEXT=\"Panic dynamic Alert for Commiittee members from Flat No '+this.contactList[i].flatNo + '\"><ADDRESS TO=\"'+this.contactList[i].cnt +'\"></ADDRESS></SMS>');
      }

      console.log("Formatted Contacts: ", this.contacts);
    }
  },
  (error) => {
    console.log("Error: ", error);
  });
}else{
  console.log(userGroup +"else");
  firebase.database().ref('users').orderByKey().once('value', (items: any) => {

    items.forEach((item) => {

      if (item.val().contact_no != '0') {
        contacts.push({
          cnt:item.val().contact_no,
          flatNo:item.val().flatno
        });
      }
      this.contactList = contacts;
    });

    var length = this.contactList.length;
    console.log(length);
    if (length > 0) {
      for (var i = 0; i < length; i++) {

         this.contacts.push('<SMS TEXT=\"Panic dynamic Alert for All members from Flat No '+this.contactList[i].flatNo + '\"><ADDRESS TO=\"'+this.contactList[i].cnt +'\"></ADDRESS></SMS>');
      }

      console.log("Formatted Contacts: ", this.contacts);
    }
  },
    (error) => {
      console.log("Error: ", error);
    });
}

}

alertConfirm.addButton({
  text: 'Send',
      handler:  data  => {
        console.log("Send clicked : "+data);
        this.loadContacts(data);
        var request = new XMLHttpRequest();
        request.open("POST", "https://control.msg91.com", true);

        var settings = {
          "async": true,
          "crossDomain": true,
          "url": "https://control.msg91.com/api/postsms.php",
          "method": "POST",
          "headers": {
            "content-type": "application/json"
          },
          "data": "<MESSAGE><AUTHKEY>******************</AUTHKEY><SENDER>SQatta</SENDER><ROUTE>4</ROUTE><CAMPAIGN>Panic Alert API</CAMPAIGN><COUNTRY>91</COUNTRY>"+ this.contacts + "</MESSAGE>"
        }

        jQuery.ajax(settings).done(function (response) {
          console.log(response);
          alert("Sms Sent!");
        });

      }
 });

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

When an AJAX request is successful in Angular, utilize the ng-hide directive

I've implemented a feature where double-clicking the name displays an input field, but I'm facing an issue with switching back after a successful put-request. Despite setting $scope.edit to false, it doesn't seem to work as expected. This is ...

The concept of an undefined property

I encountered this error in my console: index.js:70 Uncaught TypeError: Cannot read property 'searchForm' of undefined at eval (index.js:70) at Module../src/js/index.js (bundle.js:4245) at __webpack_require__ (bundle.js:20) at e ...

JavaScript shortening a string while joining it

I'm facing a challenge with string truncation in my laravel and JS(jquery) app. Initially, I suspected it was an issue with the backend (as indicated in my question here: Laravel Truncating Strings). However, after thorough debugging, I discovered tha ...

Incorporating JavaScript variables to enhance HTML attributes

Currently utilizing Backbone.js and in search of a solution to convert my data into hidden elements within a form for submission, as well as turning the data into values for textboxes. I am seeking a reliable solution that can effectively handle all speci ...

Techniques for sending PHP variables to window.location using JavaScript

How can I successfully include a PHP variable in a JavaScript window.location function? The current code snippet below does not seem to be working for me. echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.&apos ...

Receiving a console notification about a source map error

Recently, I started receiving this warning in my console: "Source map error: request failed with status 404" resource URL: map resource URL: shvl.es.js.map" Has anyone encountered this issue before? I'm unsure of what it might be? This is my webpa ...

Infinite scrolling with Jquery: Loading dynamic content seamlessly from external websites

Hey there! I recently started using this cool jQuery plugin called jquery-endless-scroll. Here's a snippet of my code: $(function() { $('#list').endlessScroll({ pagesToKeep: 10, fireOnce: false, insertBefore: "#list div:first ...

Automatically sort with Angular and PHP

Currently, I am in the process of getting a search function to work smoothly. It involves loading data from a database using PHP to Angular, and everything seems to be displaying correctly prefilled, with one exception. There is a select option where the ...

I possess a single input field and I am seeking to have the focus shifted to it upon the activation of a button

Looking to enhance user input with an icon interaction: Clicking the icon should focus on the input Considering a solution for when clicking the icon to trigger focusout A code snippet has been implemented for the first requirement, seeking suggestions ...

What is the best way to incorporate a fadeIn animation to a text in jQuery?

Looking for help with appending the fadeIn() jQuery function to a string that increments an integer within a paragraph. I attempted concatenation without success. Any recommendations on how to solve this issue? $p.text(parseInt($p.text(),10) + 1); ...

Enigmatic void appears above row upon removal of content from a single item

When I click on an item in my grid, the content of that item is moved to a modal. The modal functions properly, but I noticed that when the content is removed from the item, a space appears above it. I have found that using flexbox could solve this issue, ...

Enhance your table with custom styling by incorporating the seanmacisaac table and placing the tbody within a div

I am looking to make adjustments to a Jquery sortable, searchable table created by seanmacisaac. For more information, visit the link: Does anyone know how to set the height of the tbody to a fixed value while allowing vertical scrolling (overflow-y)? & ...

Creating an object using a string in node.js

I have a string that I am sending from AngularJS to NodeJS in the following format. "{↵obj:{↵one:string,↵two:integer↵}↵}" //request object from browser console To convert this string into an object and access its properties, I am using the serv ...

Providing static content within the generated code structure by Yeoman for the Angular Fullstack framework

I'm sticking to the code structure generated by Yeoman for an Angular fullstack application. The issue I'm facing is how to include a script called core.js in a file named app.html. <script src="core.js"></script> I can't fi ...

Raycasting intersection with a line on BufferGeometry in Three.js

After successfully implementing raycasting on lines with R59 and displaying tooltips on mouseover, I encountered performance issues due to increasing data. This led me to switch from using THREE.Geometry to THREE.BufferGeometry. While everything else seems ...

The close button within the modal is malfunctioning even with the implementation of the on() function

My "show more" button triggers the modal to pop up, but when I click on the X button in the top left corner, it doesn't close as expected. However, clicking outside of the box or pressing the "esc" key does work. I suspect that the issue lies with th ...

What is the best approach for Angular directives: utilizing a single object or separate values as attributes?

This question pertains to best practices, but I do believe there is a definitive answer. I have a directive that offers six customizable options. Should I assign each option to a separate attribute on the directive (as shown below): <my-directive my ...

Nested AJAX call yields undefined value

In my Test.vue component, I have a method that is imported into my main.js. I can call its methods like this: this.$refs.test.testMethod(). There is another method in Test.vue called ajaxMethod(), which is defined as follows: function ajaxMethod(){ t ...

Modify the value of a variable inside another {{variable}} (not sure what it's called)

I am looking to update the variable "prefs" to reflect either "easy, medium, or hard" options based on user interaction. For instance: THIS {{choice.prefs.title}} NEEDS TO BE UPDATED TO {{choice.easy.price}} or {{choice.medium.price}} or {{choice.hard. ...

Protractor Throws Element Visibility Issue

When attempting to check a checkbox in the UI, I encounter an "ElementNotVisibleError: element not visible" error. Strangely, I am able to successfully capture and click the checkbox using the console in Chrome developer tools. Has anyone else experience ...