Simon Guldstrand
Simon Guldstrand

Reputation: 488

jquery ajax post sends me to action page and wont show result data

I have the following script for making Ajax/Jquery post request. The script works (I get correct response on back-end). But I cant seem to make any alerts, so I think there is some problem with the success function. Do you guys see any obvious mistakes? The browser gets the correct responses (Inspect webpage in chrome).

<script>
        $(document).ready(function() {
            var frm = $('#registerform');
                frm.submit(function(x) {
                    x.preventDefault();
                    $.ajax({
                        type: 'POST',
                        url: 'http://localhost:8080/api/v1/register',
                        data: frm.serialize(),
                        crossDomain: true,
                        success: function(data){
                            if(data == 200){
                                alert("successfully registered");
                                $('#alert').append("successfully registered");
                            }
                            if (data == 400){
                                alert("email or password empty");
                            }
                            if(data == 403){
                                alert("passwords do not match");
                            }
                        }
                    });

                });
            });
      </script>

Upvotes: 0

Views: 48

Answers (2)

Simon Guldstrand
Simon Guldstrand

Reputation: 488

When playing with console.log i found out that sending res.sendStatus(200) from the backend results in the client (browser) getting the response "OK". So when changing to res.json on the server it works...

Upvotes: 0

dowomenfart
dowomenfart

Reputation: 2803

You are trying to compare your data that you are getting back from your request with HTTP status codes. So, what you need do is put in some additional parameters in your success function. Here is a nice Fiddle that I seen on another stackoverflow question that might help you out. http://jsfiddle.net/magicaj/55HQq/3/.

$.ajax({
    url: "/echo/xml/",
    type: "POST",
    data: {
        //Set an empty response to see the error
        xml: "<response></response>"   
    },
    dataType:"text xml",
    success: function(xml, textStatus, xhr) {
        console.log(arguments);
        console.log(xhr.status);
    }
});

The xhr.status is what you will need to compare against instead of your data.

Upvotes: 1

Related Questions