Maharshi Rawal
Maharshi Rawal

Reputation: 252

How to pass parameter to an onclick function

I have a li item that I am passing through to my server to retrieve data from the database, but I am unable to do so:

<li name="Physics" value="Physics" id="physics" onclick="drawChart(id)">Physics</li>

This drawChart function use google chart API .

function drawChart(value) {
      var jsonData = $.ajax({
          url: "getData.php?subject=value",
          dataType: "json",
          async: false
          }).responseText;
...

The getData.php is working fine but I am unable to pass parameter and use it.

Upvotes: 0

Views: 497

Answers (2)

adeneo
adeneo

Reputation: 318162

Stop using inline javascript, and the issue solves it self

$('#physics').on('click', function() {
    drawChart(this.id);
});

function drawChart(value) {
      var jsonData = $.ajax({
          url      : "getData.php",
          data     : {subject : value},
          dataType : "json",
      }).done(function(response) {
          // use response here
      });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li name="Physics" value="Physics" id="physics" >Physics</li>

Assuming $.ajax in your code is jQuery, why not use more of it ...

Upvotes: 2

Olian04
Olian04

Reputation: 6862

You could pass in this as an argument to the onclick function.

function clickHandler(el) {
  console.log(el.id);
}
<button id="clickMe" onclick="clickHandler(this)">Click me</button>

Upvotes: 1

Related Questions