简体   繁体   中英

POST to PHP from javascript

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

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>

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
});

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM