如何使用php和ajax处理表单?

How to process form with php & ajax?

html:

<form>
 <input type="radio" value="1" />
 <input type="radio" value="2" />
 <input type="radio" value="3" />
 <input type="radio" value="4" />
 <input type="button" id="go" value="go"/>
</form>

How to collect value from radio, then submit it in php $value=''; and show to user this value after clicking button #go?

I want to make simple form. User chooses value from form, then clicks on button. This value will be shown to user instantly and it will be adds to mysql database.

For the HTML, don't forget to give the radio buttons a name attribute.

<form id="form">
  <input type="radio" value="1" name="my_radio" />
  <input type="radio" value="2" name="my_radio"  />
  <input type="radio" value="3" name="my_radio" />
  <input type="radio" value="4" name="my_radio" />
  <input type="button" id="go" value="go"/>
</form>

For the Javsacript, specify your file instead of file.php

$('#form').submit(function(){
   $.post('file.php', { $(this).serialize() }, function( data ) { 
     alert( data.radio_value ); 
   })
}); 

For the PHP

if( isset( $_POST['my_radio'] ) )
{
   echo json_encode( array('radio_value' => $_POST['my_radio'] ) ); 
}

You need to set name the name for the radio buttons.

<form id="foo">
 <input type="radio" value="1" name="bar"/>
 <input type="radio" value="2" name="bar"/>
 <input type="radio" value="3" name="bar"/>
 <input type="radio" value="4" name="bar"/>
 <input type="button" id="go" value="go"/>
</form>

If you can use jQuery then you can use this code:

$('#go').click(function() {
    $.post('script.php', $('#foo').serialize(), function(data) {
        alert(data);
    });
});

and in php

<?php
// connect to database
$bar = mysql_real_escape_string($_POST['bar']);
mysql_query("INSERT INTO table (bar) VALUES ('$bar')");
echo $bar;
?>