Alex Rivera | Logout

How to call a PHP function in JavaScript?

Asked 2011-05-12T21:13:34.120
14

I have

index.php

<select id="year_list" name="year_list" onchange="check_year_event('year_list', 'event_list');" > . . .  </select>

<select id="event_list" name="event_list" onchange="check_year_event('year_list', 'event_list');" > . . . </select>
.
.
.
<?php 
 function checkYearandEvent($year, $event) {
  $year_event = mysql_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")

  if (mysql_num_rows($year_event) > 0) {
   // do this
  }

 }
?>

myscripts.js

function check_year_event(year_id, event_id) {
 var year = document.getElementById(year_id).value;
 var event = document.getElementById(event_id).value;

 // call PHP function (but I don't know how): checkYearandEvent(year, event);

}

My question is how do I call the PHP function every time the user changes the value of any of the select element.

Edit
Report

1 Answer

1

Basically, you are mixing server-side (PHP) and client-side (JS) scripting.

It is however possible - thanks eg. to AJAX. Because you was not specific about what do you exactly need to be done after the select box changes, I can only point you to some resources and propose following:

  • learn and start using jQuery (jquery.com) - it will help you get started and maintain cross-browser compatibility,
  • learn how to make AJAX requests (eg. in the function you just were firing when onchange event was fired) - eg. using .post() jQuery function,
  • learn how to return data from PHP (eg. using json_encode() in PHP, but raw HTML is also ok) and use it in JS,
answered 2011-05-12T21:20:12.037

Your Answer