Calling a PHP function from an HTML form in the same file

后端 未结 10 1441
无人共我
无人共我 2020-12-05 05:48

I\'m trying to execute a PHP function in the same page after the user enters a text and presses a submit button.

The first I think of is using forms. When the user s

10条回答
  •  抹茶落季
    2020-12-05 06:34

    You have a big misunderstanding of how the web works.

    Basically, things happen this way:

    • User (well, the browser) requests test.php from your server
    • On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
    • The browser displays the form, the user can interact with it.
    • The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.

    You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.

    If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).

提交回复
热议问题