skip to Main Content

I’m trying to do something with PHP when a text box changes. I can do this with JavaScript with onchange but that doesn’t work with PHP.

I already have a PHP function in my already existing PHP code. When a text box value changes, I want it to run the function.

2

Answers


  1. The reason you can do it in JavaScript is because you’re in the same scope…the client side. PHP is a server-side language, so it has no notion of what is happening on the client-side, unless you explicitly tell it.

    To tell PHP to evaluate, and possible return the response of a function call, you have to pass it the value of the input using a network call, such as a fetch or ajax request.

    Your question shows that you really don’t understand PHP, and you need to learn the fundamentals of it. PHP does not run client-side, and JavaScript does not run server-side (again, unless you’re using Node, in which case you wouldn’t be using PHP).

    Login or Signup to reply.
  2. Your PHP runs on your server-side. In your browser it is Javascript that runs. If you want to trigger PHP code to be executed upon some browser event, then you need to create a Javascript event-handler that will send a request to the server. Options:

    • redirect/reload page: very simple to be programmed, but not very user-friendly. You can simply pass some request parameters to communicate the tasks to the server to be executed and then the server responds. Not recommended for handling textbox changes
    • form post: you create a form which is submitted when appropriate, you can trigger the submit of the form programmatically as well as there is automatically supported form submit event handling by browsers. Not really recommended for handling textbox changes
    • sending an AJAX (Asynchronous Javascript And XML) request to the server via JS and handling the response inside a function that is to be executed when the request is responded by the server, also called the callback function
    • creation of duplex channels with WebSocket

    But, before you start doing one of the above-mentioned possibilities, rethink what you actually need and whether your scenario really needs PHP code to be executed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search