Chris Dillinger Chris Dillinger - 7 months ago 24
Javascript Question

Why is my jquery ajax POST function sending my form data to my base url rather than to the url I specified?

I have a form that I would like to POST data to my backend.
I have successfully prevented myself from being redirected when submitting the form. I want the POST request to go to

MYBASEURL/form
.

The code below almost works, however the Ajax call seems to ignore my specified URL, and makes a POST request to MYBASEURL.

What I'm using:

jquery-1.12.3.min.js

Node.js v4.3.2

Express 4.x

bodyparser

<form name="myform" action="#" method="POST">
Username: <input type="text" id="user" name="username"/><br/>
Password: <input type="text" id="email" name="email"/>
<input type="submit" id="submitForm" value="submit"/>
</form>

<script type="text/javascript">
var user=$('#user').val(), email=$('#email').val();
$('#submitForm').bind('click', function() {
$.ajax({
url: "/form",
type: 'POST',
contentType: 'text/json',
data: JSON.stringify({name:user, email:email}),
complete: function() { /* Do something with the response. */ }
});
return false; // Prevent form submit.
});
</script>


Changing the relative url to an absolute url changes nothing.
Removing the '#' from action changes nothing.

How can I ensure this POST is going to
MYBASEURL/form/
rather than just to
MYBASEURL/
?

Answer

Just adding my own answer as I had a problem on both my frontend and backend:

First the variables weren't initialized in the right scope, my script should have been like:

<script type="text/javascript">
  $('#submitForm').bind('click', function() {
    var user=$('#user').val(), email=$('#email').val();
    $.ajax({
      url: "/api/users",
      type: 'POST',
      contentType: 'application/json',
      data: JSON.stringify({name: user, email: email}),
      complete: function() { 
        // Do something with the response.
      }
    });

    return false; // Prevent form submit.
  });
</script>

This allowed my $.ajax POST to correctly send to the correct path: MYBASEURL/form

My second problem was understanding that I had to set my back-end to correctly parse content type that matches the type specified in this ajax call.