user6368630 user6368630 - 1 month ago 5
Javascript Question

Posting an input to PHP with Ajax

I have a series of input fields and I would like them to post their values to a php page for processing then return some data without reloading the page. Here is the what I have so far, however no data appears to be passing.

HTML:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("form").submit(function(form) {
$.ajax({
type:"POST",
url:"catch.php",
data: $(this).serialize(),
success: function(data) {
$('#result').html(data);
console.log(data);
}
});

form.preventDefault();
});
});
</script>
</head>
<body>
<form method="post" name="form">
<input type="submit" name="event" value="1" />
<input type="submit" name="event" value="2" />
<input type="submit" name="event" value="3" />
<input type="submit" name="event" value="4" />
</form>
<div id="result"></div>
</body>
</html>


PHP:

<?php

if(isset($_POST["event"]))
{
echo $_POST["event"];
}

?>

Answer
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>


  $(document).ready(function() {

  $('.event').on('click', function(){
    $('#event').val($(this).val());
    $('#event_form').submit();
  });
  $("form").submit(function(form) {
    $.ajax({
      type:"POST",
      url:"catch.php",
      data: $(this).serialize(),
      success: function(data) {
        $('#result').html(data);
        console.log(data);
      }
    });

    form.preventDefault();
  });
});
</script>
</head>
<body>
    <form method="post" name="form" id="event_form">
<input name="event" id="event" value="" type="hidden">
    <input type="button" class="event" value="1" />
    <input type="button" class="event" value="2" />
    <input type="button" class="event" value="3" />
    <input type="button" class="event" value="4" />
    </form>
 <div id="result"></div>
</body>
</html>
Comments