How to pass different arguments to a function based on which element was clicked?

I'm new to this, so if I'm not too explicit please don't be too harsh to me.

I made an HTML file with two test buttons.

I created a function called test() in JavaScript which includes an Ajax POST method to the file test.php.

The PHP file writes 1 and 0 to a text file named test.txt.

All this for one button.

Everything works fine, but I have this problem:

I want my test() function to be called in the second button which has different data like test2.php and other 4 variables like tag_test2, phptag_test2 , On_test2, toggle_test2.

So would need to write a function test(testphp, tag, phptag, toggle, On) to call it for those two buttons with different parameters.

I've tried this function.

function test(testphp, tag, phptag, On, toggle) {

    if (toggle_test == 0) {
        toggle = 1;
        On = 1;
        tag = On;
        document.getElementById("result").innerHTML = On;

        $.ajax({
            type: "POST",
            url: testphp,
            data: {
                phptag: tag
            }
        });

        return test;
    }

    if (toggle == 1) {
        toggle = 0;
        On = 0;
    }
    tag = On;
    document.getElementById("result").innerHTML = On;

    $.ajax({
        type: "POST",
        url: testphp,
        data: {
            phptag: tag
        }
    });
}
}

And called it in my first button to see if it works, but no success so far.

I replaced test() with test('test.php', tag_test, phptag_test, On_test, toggle_test).

This is my code that works for the first button:

test.html

<html>
   <head>
      <title>Tests</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <script type="text/javascript" src="jquery-3.4.1.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
   </head>
   <div>
   </div>
   <div class="Header2"> Cornel - Tests</div>
   <div class="space"></div>
   <body>
      <div class="container">
         <button type="button" class="btn btn-success" 
            onclick="test()">Test</button>
         <button type="button" class="btn btn-success">Test2</button>
         <div id="result"></div>
         <script>
var toggle_test = 0;
var On_test = 0;
var tag_test;

function test() {

    if (toggle_test == 0) {
        toggle_test = 1;
        On_test = 1;
        tag_test = On_test;
        document.getElementById("result").innerHTML = On_test;

        $.ajax({
            type: "POST",
            url: "test.php",
            data: {
                phptag_test: tag_test
            }
        });

        return test;
    }

    if (toggle_test == 1) {
        toggle_test = 0;
        On_test = 0;
    }
    tag_test = On_test;
    document.getElementById("result").innerHTML = On_test;

    $.ajax({
        type: "POST",
        url: "test.php",
        data: {
            phptag_test: tag_test
        }
    });
}
         </script>
         <style>
.btn-success {
    background-color: #2E64FE;
    border: none;
    color: white;
    padding: 10px 20px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 20px;
}

.btn-success:hover {
    background-color: blue;
}

.btn-success:active:focus {
    background-color: blue;
}

.btn-success:focus {
    background-color: #2E64FE;
}

.btn-success:hover {
    background-color: blue;
}

.Header2 {
    padding: 50px;
    font-size: 50px;
    text-align: center;
    color: white;
    background-image: linear-gradient(#0033cc, #58FAF4);
    border: solid;
}

.space {
    padding: 25px;
}

.container {
    padding-left: 80px
}
         </style>
      </div>
   </body>

test.php

<?php
$tag_test = $_POST['phptag_test'];



$file=fopen('test.txt', 'w');
fwrite($file, $tag_test . "\n");
fclose($file);
?>

This writes in the test.txt file.

Also I have a jquery-3.4.1.js file in my folder.

Upvotes: 0

Views: 989

Answers (4)

After a pause from this miniproject, I came up with a solution.

<button type="button" class="btn btn-success" onclick="test(iluminat1);iluminat1()">Iluminat1</button>
<button type="button" class="btn btn-success" onclick="test(iluminat2);iluminat2()">Iluminat2</button>

<script type="text/javascript">
        var toggle_test=0;
        var On_test=0;
        var php_iluminat1;
        var php_iluminat2;


        function test(tag_test) {


                if(toggle_test==0)
                {
                toggle_test=1;
                On_test=1;
                return test;
                }


                if(toggle_test==1)
                {
                toggle_test=0;
                On_test=0;
                }

        }

        function iluminat1()
        {
        $.ajax({
        type: "POST",
        url: "test.php",
        data: {php_iluminat1: On_test}
        });
        }


        function iluminat2()
        {
        $.ajax({
        type: "POST",
        url: "test.php",
        data: {php_iluminat2: On_test}
        });
        }

    </script>

I didn't need all those parameters and I realized I need to write an individual function for each button to be able to write their On_test value.

Upvotes: 0

user1063287
user1063287

Reputation: 10879

Here is some code that I think resolves your primary issue, ie passing dynamic values to a function.

Basically, the approach is to:

  • add a unique id attribute to each button
  • add an on click handler
  • define different function parameters depending on which button was clicked

You will then be able to handle your different scenarios via conditional handling of the values passed through to your server side code.

jsFiddle link

note: the jsFiddle uses mockjax to emulate a delay when retrieving results from the server, and logs several values to the console so you can better understand what is happening in the code, but you can remove all that code when implementing

HTML

<!-- added unique id's to your buttons -->
<div class="container">
  <button id="button1" type="button" class="btn btn-success">Test1</button>
  <button id="button2" type="button" class="btn btn-success">Test2</button>

  <div id="result"></div>
</div>

JS

// added on click handler
$(document).on("click", "#button1, #button2", function() {

  // get reference to the instance of the button  
  var instance = $(this).attr("id");

  // sanity check  
  console.log("the instance is: " + instance);

  // create an object to store function parameters
  var parameters = {};

  // assign different values based on the instance  
  if (instance === "button1") {

    parameters.php_file = "my_file_1.php";
    parameters.tag = "tag 1";
    parameters.phptag = "php tag 1";
    parameters.is_toggled = true;
    parameters.is_on = false;

  } else if (instance === "button2") {

    parameters.php_file = "my_file_2.php";
    parameters.tag = "tag 2";
    parameters.phptag = "php tag 2";
    parameters.is_toggled = false;
    parameters.is_on = true;

  }

  // call the function
  my_function(parameters);

});


const my_function = (parameters) => {

  var php_file = parameters.php_file;

  $.ajax({
    url: `/path/to/your/file/${php_file}`,
    data: parameters, // send the parameters to your server side file
    type: "POST", 
    success: function(response) {

      // handle the response here  
      $("#result").text(response);

    }
  });

}

CSS

.btn-success {
  background-color: #2E64FE;
  border: none;
  color: white;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
}

.btn-success:hover {
  background-color: blue;
}

.btn-success:focus {
  background-color: #2E64FE;
}

.btn-success:active:focus {
  background-color: blue;
}

.Header2 {
  padding: 50px;
  font-size: 50px;
  text-align: center;
  color: white;
  background-image: linear-gradient(#0033cc, #58FAF4);
  border: solid;
}

.space {
  padding: 25px;
}

.container {
  padding-left: 80px;
}

#instance {
  font-size: 18px;
  color: black;
  font-weight: bold;
  margin-top: 20px;
  font-family: arial;
}

#result {
  font-size: 38px;
  color: deeppink;
  font-weight: bold;
  margin-top: 20px;
  font-family: arial;
}

Upvotes: 1

akaBase
akaBase

Reputation: 2250

The simplest way would be to just pass the Data in the onClick events.

Example

Pass the urls file name and the data string like so.

<button id="test" name="test" onClick="Test('test1', 'test_string_1');">Click Me </button>
<button id="test" name="test" onClick="Test('test2', 'test_string_2');">Click Me </button>

And then if your Test function use them like this.

function Test (filename, data){

    document.getElementById("result").innerHTML = data;

    $.ajax({
        type: "POST",
        url: filename + ".php",
        data: {
            phptag_test: data
        }
    });
}

This is just a psuedo example, you will need to write your own version for your desired functionality.

Upvotes: 0

Carljul
Carljul

Reputation: 111

Just my idea. How about you will detect the button which is been clicked and throw a condition that if the button2 is been clicked then do your ajax call and the same thing with button1.

   <button type="button" class="btn btn-success" id="button1" onclick="test(this.id)">Test</button>
   <button type="button" class="btn btn-success" id="button2" onclick="test(this.id)">Test2</button>
   <script>
     function test(button_id) {
          if(button_id == "button1"){
            // do your ajax here
          }else if(button_id == "button2"){
            // do your ajax here
          }
      }
   </script>

Upvotes: 0

Related Questions