Tom Wall
Tom Wall

Reputation: 125

Javascript not receiving data from form onsubmit for Ajax call

Every time I enter in the 3 parameters, and click submit, I am alerted with "name=&startDate=&endDate=". It's not updating $('#request') after I click submit. Does anyone see where I may be going wrong?

Here is my HTML:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="match.js"></script>
<script src="Chart.js"></script>
</head>

<body>

<form id="request" onsubmit="match.js">
    <label>Name <input type="text" name="name" id="name" ></label>
    <label>Start Date <input type="date" name="startDate" id="startDate" ></label>
    <label>End Date <input type="date" name="endDate" id="endDate"  ></label>
    <input type="submit" value="Submit">
</form>

</body>
</html>

And my Javascript:

$(function(){
  $(function(e){
    $.ajax({
      url: 'match_api.php',
      type: 'post',
      data: $('#request').serialize(),
      dataType: 'json',
      success: function(data) {
          alert($('#request').serialize());
     });
     e.preventDefault();
  });
});

Upvotes: 2

Views: 10012

Answers (2)

epascarello
epascarello

Reputation: 207501

I am not sure where you learned this

onsubmit="match.js"

Does nothing at all other than cause a JavaScript error. It does not magically bind the JavaScript file to the function.

If you want to attach to the submit event, you need to do

$(function(){
    $("#request").on("submit", function(e){
        $.ajax({
          url: 'match_api.php',
          type: 'post',
          data: $('#request').serialize(),
          dataType: 'json',
          success: function(data) {
              alert($('#request').serialize());
          }
         });
         e.preventDefault();
    });
});

and the HTML would just be

<form id="request">

Upvotes: 2

Dat Nguyen
Dat Nguyen

Reputation: 1891

Here is your HTML:

<body>

<form id="request" onsubmit="match()">
    <label>Name <input type="text" name="name" id="name" ></label>
    <label>Start Date <input type="date" name="startDate" id="startDate" ></label>
    <label>End Date <input type="date" name="endDate" id="endDate"  ></label>
    <input type="submit" value="Submit">
</form>

</body>
</html>

And your Javascript:

function match(){
    $.ajax({
      url: 'match_api.php',
      type: 'post',
      data: $('#request').serialize(),
      dataType: 'json',
      success: function(data) {
          alert($('#request').serialize());
     });
     e.preventDefault();
  };

Upvotes: 3

Related Questions