Runny Yolk Runny Yolk - 1 year ago 67
Ajax Question

Submitting Form via JQuery Ajax Post Request

I have a basic messaging service on a web Node / Express web app, and I'm trying to submit the form via Ajax, using the FormData object.

If I submit the form without AJAX, then everything works fine, but with AJAX the req.body. are all undefined.

On the server, I need to look for the data somewhere other than req.body when using AJAX??

Creating the FormData object:

var ajaxData = new FormData;
ajaxData.append('newMessage', $('.new-message').val()) // I've console.logged these, and their values are correct
ajaxData.append('senderId', $('[name="senderId"]').val())
ajaxData.append('senderName', $('[name="senderName"]').val())// I've console.logged these, and their values are correct
ajaxData.append('recipientId', $('[name="recipientId"]').val())
ajaxData.append('recipientName', $('[name="recipientName"]').val())// I've console.logged these, and their values are correct

And this is the POST request:

url: $form.attr('action'),
type: $form.attr('method'),
data: ajaxData,
dataType: false,
cache: false,
contentType: false,
processData: false,
complete: function() {
console.log('message created');
success: function(data) {

error: function(xhr, textStatus, errorThrown) {


Thanks to G. Mansour for his answers below. In case anyone else gets here, the issue was the line:

contentType: false,

I tried this line at some point, which also doesn't work

contentType: 'application/json',

But when I remove the line entirely, everything is working as normal... If anyone can tell me why this line was breaking everything, I'd be interested to know.

Answer Source

This is the html part

<form id="form" action="" method="post">
<input type="text" name="msgID" id="msgID">
<input type="text" name="senderId" id="senderId">
<input type="text" name="senderName" id="senderName">
<input type="text" name="recipientId" id="recipientId">
<input type="text" name="recipientName" id="recipientName">
<input type="submit" name="dsq" value="dsqdsq">

this is the JavaScript part

<script type="text/javascript">

        url: "test.php", 
        data: $("#form").serialize(), 
        type: "POST", 
        dataType: 'json',
        success: function (e) {


    return false;


And this is the php code


Hope that will helps you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download