Currently I have an HTML page that has many textboxes that need to be validated via Javascript. Once they are all validated, I am wanting to create a user account via a controller.php
My question is this: How can I POST to a PHP file from within a Javascript function. I gather that I can use AJax, however I would like to use it without this if possible.
thanks
-
You don't have to you AJAX. You can also use simple javascript and send a request to your page.Aurelio De Rosa– Aurelio De Rosa2012年05月21日 23:57:04 +00:00Commented May 21, 2012 at 23:57
-
1Why would you use javascript for this?Paul Dessert– Paul Dessert2012年05月21日 23:57:18 +00:00Commented May 21, 2012 at 23:57
3 Answers 3
Create a form with the post method and have it point to the php script. If you set it up like this below you do not need to post from the javascript function because the default behavior of the html form will do the posting for you. It also degrades gracefully for people that do not have javascript enabled.
<form action="/path.to.your.php.file.php" method="POST" onSubmit="return validate();">
... your fields...
<input type="submit" value="validate and submit"/>
</form>
<script>
function validate(){
// do your validation here
return true; // return true if validation was ok, false otherwise
}
</script>
Comments
If you want to use AJAX, using the JQuery library, you can do the following to post to a page
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
OR
$.post('controller.php', function(data) {
//do something with the result
});
1 Comment
Specify a name for your form like so...
<form name="myForm" id="form1" method="post" action="phpScriptToPostTo.php">
...then run this javascript:
document.forms["myForm"].submit();
...or this in jQuery:
$('#form1').submit();
...or this in jQuery over ajax:
$.post('server.php', $('#form1').serialize())