How can I execute a PHP function in a form action?

后端 未结 7 1057
死守一世寂寞
死守一世寂寞 2020-12-25 11:29

I am trying to run a function from a PHP script in the form action.

My code:



        
7条回答
  •  囚心锁ツ
    2020-12-25 12:17

    I'm not sure I understand what you are trying to achieve as we don't have what username() is supposed to return but you might want to try something like that. I would also recommend you don't echo whole page and rather use something like that, it's much easier to read and maintain:

    
    
    

    Your username is:

    This will post the results in the same page. So first time you display the page, only the empty form is shown, if you press on submit, the textfield field will be in the $textfield variable and you can display it again as you want.

    I don't know if the username() function was supposed to return you the URL of where you should send the results but that's what you'd want in the action attribute of your form. I've put the result down in a sample paragraph so you see how you can display the result. See the "Your username is..." part.


    // Edit:

    If you want to send the value without leaving the page, you want to use AJAX. Do a search on jQuery on StackOverflow or on Google.

    You would probably want to have your function return the username instead of echo it though. But if you absolutely want to echo it from the function, just call it like that in your HTML form.

    I think you will need to understand the flow of the client-server process of your pages before going further. Let's say that the sample code above is called form.php.

    1. Your form.php is called.
    2. The form.php generates the HTML and is sent to the client's browser.
    3. The client only sees the resulting HTML form.
    4. When the user presses the button, you have two choices: a) let the browser do its usual thing so send the values in the form fields to the page specified in action (in this case, the URL is defined by PHP_SELF which is the current page.php). Or b) use javascript to push this data to a page without refreshing the page, this is commonly called AJAX.
    5. A page, in your case, it could be changed to username.php, will then verify against the database if the username exists and then you want to regenerate HTML that contains the values you need, back to step 1.

提交回复
热议问题