HTML Javascript forms, and a php script - Simple question, help! what does this code do?
So I have this simple form:
<form action="includes/process.php" method="post" name="standard_use" id="standard_use" enctype="multipart/form-data">
<button onclick="dofunction(); return false;">Do it!</button>
<input type="file" id="upload_file" name="filename" style="float:left;width:70%;" size="42"/>
</form>
So what happens really when the button is clicked ? Is it that the php file is called ? does it not ? the javas开发者_开发知识库cript is called before ? Anyone can shed some light on this ? Thanks !
Well, when you hit the button the following events occurs:
- You send a REQUEST to the server
- The php codes evaluates the request and runs some codes
- Finally it returns back a RESPONSE which you see as a web page
Javascript is a client-side script which means that whenever you make an action on the page, the code runs. For instance, when you click the button, before sending the request javascript will work. You may, for instance, place a function that will be triggered when you hit the button which checks the form and either approves the form or shows the error messages
EDIT
As far as your comment is concerned:
Yes, javascript runs first when you hit the submit button. Php runs only when you submit the form and make a request to the server.
Consider this example: (I am better at explaining things with examples:)
<form action="somepage.php" onsubmit="return checkMe()" method="POST">
<input name="firstname" id="fn" value="" type="text" />
<input type="submit" value="Submit" />
<script type="text/javascript">
function checkMe(){
var tb = document.getElementById("fn")
if(tb.value == "Alex") return true;
else return false;
}
</script>
</form>
So basically, when you hit the button and try to submit the form, the javascript will first check whether the name provided in the textbox is Alex or not, if it is not then it will not submit the form. If it is Alex then it will submit the form and then the form will redirect the user to somepage.php. Finally, the php codes will work in somepage.php and the page will be rendered again.
What happens is that only doFunction() javascript function is invoked and nothing more. However, it might be possible that this javascript function invokes "submit" event on the form and the request is sent (what you described as "php file is called").
Your code just trigger javascript event and your function. To submit a form you need an
<input type="submit" value="Submit" />
or a button, which default type is submit (thx davin)
<button value="Submit" />
However as far as you return false
in your javascript code your form won't be submitted even with the submit button.
精彩评论