Munchmallow
Munchmallow

Reputation: 311

jquery Ajax Doesn't Send JSON Data

I am trying to send an ajax send request, but it always goes into error.

$('form#contactForm button.submit').click(function () {

            var contactName = $('#contactForm #contactName').val();
            var contactEmail = $('#contactForm #contactEmail').val();
            var contactSubject = $('#contactForm #contactSubject').val();
            var contactMessage = $('#contactForm #contactMessage').val();

            var data = {
                'contactName': contactName,
                'contactEmail': contactEmail,
                'contactSubject': contactSubject,
                'contactMessage': contactMessage
            };

            $.ajax({
                type: "POST",
                url: "/",
                data: data,
                dataType: 'json',
                contentType: "application/json",
                success: function (msg) {
                    alert('success message: ' + msg);
                    if (msg == 'OK') {
                        $('#image-loader').fadeOut();
                        $('#message-warning').hide();
                        $('#contactForm').fadeOut();
                        $('#message-success').fadeIn();
                        $('#contactForm button.submit').prop('disabled', true);
                    }
                    else {
                        $('#image-loader').fadeOut();
                        $('#message-warning').html(msg);
                        $('#message-warning').fadeIn();
                    }

                },
                error: function (err) {
                    if (contactName.length === 0 || contactEmail.length === 0 || contactSubject.length === 0 ||
                        contactMessage.length === 0) {
                        $('#message-warning').html('Please check form once again.');
                        $('#message-warning').fadeIn();
                        event.preventDefault();
                    }
                    alert('inside error: ' + err.message);
                }
            });
            return false;
});

This always shows alert('inside error: ' + err.message);in error.I also tried data: JSON.stringify(data)and it didn't work either. Is there a problem with datavariable? Where is the problem?

Network tab:

Request URL:http://localhost:3000/
Request Method:POST
Status Code:400 Bad Request
Remote Address:[::1]:3000
Response Headers
view source
Connection:keep-alive
Content-Length:24
Content-Type:text/html; charset=utf-8
Date:Sun, 23 Oct 2016 00:12:43 GMT
ETag:W/"18-9LwX+BuZqYnTTqGm6GcNuA"
X-Powered-By:Express
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:102
Content-Type:application/json
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
contactName=My+Name&contactEmail=email%40email.com&contactSubject=My+Subject&contactMessage=My+Message

backend post

router.post('/', function (req, res) {
    if (typeof req.body.contactName === 'undefined' || typeof req.body.contactEmail === 'undefined' ||
        typeof req.body.contactSubject === 'undefined' || typeof req.body.contactMessage === 'undefined' ||
        !validator.isEmail(req.body.contactEmail)) {
        return res.status(400).send('error');
    }
    mail.sendMail(req.body.contactName, req.body.contactEmail, req.body.contactSubject, req.body.contactMessage);
    return res.status(200).send('okay');
});

Upvotes: 0

Views: 1866

Answers (3)

Enix
Enix

Reputation: 4579

The ajax client expects your response MIME type as 'json', however you provided a plain text 'okay' as response.

If you still need to send json as a response, you can make use of res.type change your backend like this:

router.post('/', function (req, res) {
    if (typeof req.body.contactName === 'undefined' || typeof req.body.contactEmail === 'undefined' ||
        typeof req.body.contactSubject === 'undefined' || typeof req.body.contactMessage === 'undefined' ||
        !validator.isEmail(req.body.contactEmail)) {
        return res.status(400).type('json').send({"result": "error"});
    }
    mail.sendMail(req.body.contactName, req.body.contactEmail, req.body.contactSubject, req.body.contactMessage);
    return res.status(200).type('json').send({"result":"okay"});
});

Then your frontend should work as expected. For most of the case, you don't need to specify dataType, because ajax could determine the mime type automatically base on your server response.

Upvotes: 0

Munchmallow
Munchmallow

Reputation: 311

I have removed dataType: 'json'and contentType: "application/json"and ajax request succeeded. I still don't know why but it worked after removing them.

Upvotes: 1

sideroxylon
sideroxylon

Reputation: 4416

dataType refers to the expected response from the server - see HERE. If the response is not JSON, remove dataType: 'json' from the ajax function, and jQuery will make an intelligent guess.

Upvotes: 0

Related Questions