Click to See Complete Forum and Search --> : Scripts


Javajoob
06-09-2007, 03:05 PM
Hello. Can you use javascript in a PHP script or does it have to be solely PHP?

NogDog
06-09-2007, 04:32 PM
Your PHP script can output JavaScript (just as it ouputs HTML) which will then be executed by the browser once it loads the page; but remember that PHP is running on the server while JS is run on the client (browser), so all of the PHP will run first.

Javajoob
06-09-2007, 04:55 PM
It's just I would rather validate a form with Javascript rather than PHP so it doesn't keep getting sent to the server and then being corrected.

felgall
06-09-2007, 05:01 PM
You should validate in both places - in the browser to be friendly to visitors with JavaScript enabled, and on the server to make sure that your visitors can't bypass the validation by disabling JavaScript.

Javajoob
06-09-2007, 05:10 PM
Good Idea. But can you put validations in a php script containing a form?

NogDog
06-09-2007, 06:03 PM
A common pattern is to have both the form and the form processing in the same file (the form action's value is therefore the current page). The basic flow would be:

IF post data was received
validate the post data
IF the post data is valid
process the form data
IF the processing was successful
header() redirect to "success" page
EXIT
ELSE
set error message
ENDIF
ELSE
set error message
ENDIF
ENDIF
begin display of HTML page (which may include JavaScript)
IF error message is set
display error message(s)
ENDIF
display form (setting values to corresponding $_POST values if they are set
display rest of page