简体   繁体   中英

How to call a PHP function when “onchange” event is fired?

I have three identical drop down lists that I'm populating using MySQL data. If one of them changes index (onchange is fired), I want the other two to re-populate, so that they exclude the item that has been chosen with the other drop down list.

In ASP.NET, I would simply have called a function (passing through the chosen items' value) in the code behind to re-populate the other two.

I've been poking around for a while now and I just can't get it done with PHP. Does PHP allow function calling from this event? I've also tried using AJAX, but nothing.

OnChange() is a js function , in order to use it to call a php function you'll have to use AJAX . Using ajax you'll be able to get the php's code returned value , display it in the page , or doing whatever manipulation you'd like.

Good luck

You can't (directly) call server side functions from the client side.

You can make an HTTP request to a URL that runs a server side script that calls the function.

ASP.NET has (I believe, I've never used it) some stuff that will set up a URL and generate some JavaScript that will call that URL for you.

There is nothing in the PHP core to do that.

A very rough, quick and dirty outline (that makes no attempt to be RESTful) of how you might go about doing something like that would be:

 callFunction.php:
 <?php
     include("myFunctions.php");
     if ($_GET['call'] == "functionA") {
         functionA();
     }
 ?>

Then your JS would make an ajax request to callFunction.php?call=functionA .

ASP.NET would have been doing a Postback when the dropdown was changed, although you'd not have had to write it explicitly.

If you want to do a round trip to the server in PHP, you'll have to implememnt the same logic (eg post the form with JavaScript in the onchange event).

This is a good situation for using AJAX as well, but you haven't provided any details of what you tried or what went wrong so it's hard to help further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM