Skip to content
Advertisement

How to execute different functions in same script by clicking different buttons

I have a button inside my form as below,

<form method="POST">
        <div class="mb-3">
              <button  type='button'  id ="btnnew" class="btn btn-info">submit</button>
              <p></p>
        </div>
</form>

So my script as below, from that I will run me testme.php.

 $("#btnnew").confirm({
      
      title: "Confirmation",
      text: "Do you really need?",
      confirm: function(button) {        
        console.log('AJAX request in progress...');
        
        $('#loading').show();
        $.ajax({
          type: 'POST',
          url: 'testme.php',
          success: function(data) {
            $("p").text(data);
          },
          complete: function() {      
            $('#loading').hide();
          }
        });
        
      },
      cancel: function(button) {
        console.log("You aborted the operation.");
      },
      confirmButton: "Yes I Need",
      cancelButton: "No"
    });

My testme.php as follows,

<?php
sleep(5);
echo 'Hi Done';

?>

This works fine..Now I need to do this same approach to many buttons..only different is the button id and the runnning script only… As an example,

<form method="POST">
        <div class="mb-3">
              <button  type='button'  id ="btnnew" class="btn btn-info">submit</button>
              <p></p>
        </div>
         <div class="mb-3">
              <button  type='button'  id ="btnnew2" class="btn btn-info">submit</button>
              <p></p>
         </div>
         <div class="mb-3">
              <button  type='button'  id ="btnnew3" class="btn btn-info">submit</button>
              <p></p>
         </div>
</form>

But I need to change the function from my testme.php as well as below,

if btnnew clicks
    sleep(5);
    echo 'Hi Done button1';

if btnnew2 clicks
    sleep(10);
    echo 'Hi Done button2';

if btnnew3 clicks
    sleep(15);
    echo 'Hi Done button3';
    

Can I do this task by using only one script?

Advertisement

Answer

As a basic example of how you might accomplish the stated objective of triggering different pieces of PHP code dependent upon which button is clicked in the browser perhaps the following might be of help.

The javascript binds a click event handler to each button which sends the ID if the event.target (button ) within an ajax request.

The PHP script processes the $_POST['bttn'] variable and uses a simple switch to fork the program logic

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['bttn'] ) ){
        switch( $_POST['bttn'] ){
            case 'btnnew':
                sleep(5);
                exit( 'Hi Done button1' );
            break;
            case 'btnnew2':
                sleep(10);
                exit( 'Hi Done button2' );
            break;
            case 'btnnew3':
                sleep(15);
                exit( 'Hi Done button3' );
            break;
            default:
                exit('Bad Foo!');
            break;
        }
        
    }
?>



<form method="POST">
    <div class="mb-3">
          <button  type='button' id="btnnew" class="btn btn-info">submit</button>
          <p></p>
    </div>
     <div class="mb-3">
          <button  type='button' id="btnnew2" class="btn btn-info">submit</button>
          <p></p>
     </div>
     <div class="mb-3">
          <button  type='button' id="btnnew3" class="btn btn-info">submit</button>
          <p></p>
     </div>
</form>

<script>
    document.querySelectorAll('button').forEach(bttn=>bttn.addEventListener('click',function(e){
        let fd=new FormData();
            fd.set('bttn', this.id );
        
        fetch( location.href, { method:'post', body:fd })
            .then(r=>r.text())
            .then(text=>alert(text))            
    }))
</script>

As I do not use jQuery at all and cannot find reference to the .confirm method I can offer no advice on it. However using vanilla Javascript and some additional code it is possible to popup a dialog to serve your needs as I understand them.

The following snippet uses a class I wrote a while ago to interact with a HTML dialog element. The callbacks are assigned to the buttons and if the Accept button is clicked the callback will fire an ajax request with the button ID that invoked the dialog. ( use the console to inspect the network traffic )

const url = 'testme.php';

let modal;
let fd = new FormData();

document.querySelectorAll('button').forEach(bttn => bttn.addEventListener('click', function(e) {

  fd.set('bttn', this.id);

  let dialog = document.querySelector('dialog');
  let content = document.querySelector('template').content.cloneNode(true);
  content.querySelector('h4').textContent = `You clicked: ${fd.get('bttn')}`;

  let attr = {
    width: '200px',
    height: '250px'
  };

  let callbacks = {
    'accept': {
      type: 'click',
      callback: acceptcallback
    },
    'reject': {
      type: 'click',
      callback: rejectcallback
    }
  };

  modal = new Modal(dialog, content, attr, callbacks).open();
}));

const acceptcallback = (e) => {
  fetch(url, {
      method: 'post',
      body: fd
    })
    .then(r => r.text())
    .then(text => alert(text))
};
const rejectcallback = (e) => {
  alert("I'm sorry, Dave. I'm afraid I can't do that.nnLook Dave, I can see you're really upset about this. I honestly think you ought to sit down calmly, take a stress pill, and think things over.");
  modal.close();
};











class Modal {
  constructor(dialog = false, content = false, attr = {}, callbacks = {}) {
    this.dialog = dialog;
    this.callbacks = callbacks;
    this.content = content;
    this.attr = attr;
    return this.create();
  };

  create() {
    this.dialog.innerHTML = '';

    if (this.content.nodeType == 1 || this.content.nodeType == 11) this.dialog.append(this.content);
    else this.dialog.insertAdjacentHTML('beforeend', this.content)

    this.setattributes();
    this.bindEvents();

    return this;
  };

  setattributes() {
    let exceptions = ['innerHTML', 'innerText', 'html', 'text', 'textContent', 'width', 'height'];
    Object.keys(this.attr).forEach(k => {
      if (!exceptions.includes(k)) this.dialog.setAttribute(k, this.attr[k]);
    });
    if (this.attr.hasOwnProperty('innerHTML') || this.attr.hasOwnProperty('html')) this.dialog.innerHTML = this.attr.innerHTML || this.attr.html;
    if (this.attr.hasOwnProperty('innerText') || this.attr.hasOwnProperty('text') || this.attr.hasOwnProperty('textContent')) this.dialog.textContent = this.attr.innerText || this.attr.text || this.attr.textContent;
    if (this.attr.hasOwnProperty('width')) this.dialog.style.width = this.attr.width;
    if (this.attr.hasOwnProperty('height')) this.dialog.style.height = this.attr.height;
  };

  checkstyle(n, p) {
    return window.getComputedStyle(n).getPropertyValue(p)
  };
  setstyle(n, p, v) {
    n.style[p] = v
  };

  setposition() {
    if (!this.dialog.showModal) {
      let r = 10;
      let dw = parseInt(this.checkstyle(this.dialog, 'width'), r);
      let dh = parseInt(this.checkstyle(this.dialog, 'height'), r);
      let sw = screen.availWidth;
      let sh = screen.availHeight;

      let px = (sw - dw) / 2;
      let py = (sh - dh) / 2;

      this.setstyle(this.dialog, 'position.top', py + 'px');
      this.setstyle(this.dialog, 'position.left', px + 'px');
      this.setstyle(this.dialog, 'z-index', 100);
    }
  };

  bindEvents() {
    if (this.callbacks && Object.keys(this.callbacks).length > 0) {
      Object.keys(this.callbacks).forEach(key => {

        let node = this.dialog.querySelector('[data-handler="' + key + '"]');
        let type = this.callbacks[key].hasOwnProperty('type') ? this.callbacks[key].type : 'click';
        if (node && node.nodeType == 1) {
          node.addEventListener(type, this.callbacks[key].callback);
        }
      })
    }
  };

  open() {
    if (this.dialog.showModal) this.dialog.showModal();
    else this.dialog.setAttribute('open', true);

    this.setposition();

    return this;
  };
  close() {
    this.dialog.innerHTML = '';
    [...this.dialog.attributes].forEach(attr => {
      if (attr.name != 'open') this.dialog.removeAttribute(attr.name);
    });

    if (this.dialog.close) this.dialog.close();
    else this.dialog.removeAttribute('open');

    return this;
  };
};
::backdrop{
  background:black;
  background-image:url(https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX17560307.jpg);
  background-repeat: repeat;
}
<form method="POST">
  <div class="mb-3">
    <button type='button' id="btnnew" class="btn btn-info">submit</button>
    <p></p>
  </div>
  <div class="mb-3">
    <button type='button' id="btnnew2" class="btn btn-info">submit</button>
    <p></p>
  </div>
  <div class="mb-3">
    <button type='button' id="btnnew3" class="btn btn-info">submit</button>
    <p></p>
  </div>
</form>


<dialog></dialog>

<template>
  <h4></h4>
  <p>Are you really sure you want to do that Dave?</p>
  <p>This mission is too important for me to allow you to jeopardize it.</p>
  <input type='button' name='accept' value='Accept' data-handler='accept' />
  <input type='button' name='reject' value='Reject' data-handler='reject' />
</template>
Advertisement