{"error": "Please use POST request"}

I’m trying to Output something like this.

Here is my Code.

<div class="container">
  <div class="row">
    <div class="col-sm-4">
      <form id="checkout" >
        <div class="form-group">
          <label for="username">Username</label>
          <input type="text" class="form-control" id="username" value="Bob" required>
        </div>
        <div class="form-group">
          <label for="password">Password</label>
          <input type="password" class="form-control" id="password" value="Password" required>
        </div>
        <button type="submit" id="checkoutSubmit" class="btn btn-submits btn-primary">Submit</button>
      </form>
    </div>
  </div>
</div>
<hr>

JS file
var jsonData = {
  "status": -1,
  "message": "Form validation errors",
  "formErrors": {
    "username": [{
      "noNumber": "'Bob' must contain at least one number (0-9)"
    }, {
      "noSymbol": "'Bob' must contain at least one symbol (!@#$%^&*)"
    }],
    "password": [{
      "noAlpha": "Must contain at least one letter (a-z A-Z)"
    }]
  }
};

$.ajax({
  method: 'POST',
  dataType: 'json',
  url: '/echo/json/',
  data: {
    json: JSON.stringify(jsonData)
  },
  success: function(data) {
   
  }
});

I keep getting this error

{“error”: “Please use POST request”}

I don’t see an issue of whats going on

The AJax code is in another file

The issue is that your submit button is firing off a submit event which the form is handling in the default way. The error message is complaining that your form is trying to send form data in a GET request. Since you’re doing client side validation, you’ll need to solve this by attaching a click handler to your submit button and preventing the default action.

$('#checkoutSubmit').click(function(event) {
    event.preventDefault();
});
2 Likes

I’ve attached the click handler and the error is gone. However, it won’t display the form validation error

You don’t have any code that does validation yet. When you do, you can run it in your click handler after preventDefault. If all you want to do is run that $.ajax function, put it in your click handler.