dochsner
dochsner

Reputation: 249

Jquery Ajax form not submitting and url is showing csrf token

I'm sort of new to Ajax and I'm trying to submit a form using jquery, ajax and thymeleaf for the view. I know the post url works because if I just tell the ajax to submit as soon as the page loads whatever is in the form is submitted to the databse with no problem, but if I try to do it using a submit button, then the form goes blank, and the url changes to something like this http://localhost:8080/viewCourse/post/1?_csrf=d512fb5c-08e5-4373-895e-1297b0c35a4b, and nothing enters the database, yet there isn't an error in the console either, so I'm not sure what's happening.

Here's my jquery and ajax

var postId = /*[[${post.id}]]*/'1';

var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");

$(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
});

$("#submit").click(function() {
    $.ajax({
        url : "newComment",
        type : "post",
        data : {
            "postId" : postId,
            "newComment" : $("#newComment").val()
        },
        success : function(data) {
            console.log(data);
            location.reload();
        },
        error : function() {
            console.log("There was an error");
        }
    });
});

and here's my html using thymeleaf

<div id="newCommentForm">
    <form>
        <div class="form-group">
            <textarea rows="2" id="newComment" placeholder="comment"
                      class="form-control" style="width: 520px;">
            </textarea>
        </div>
        <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
        <input type="submit" value="Comment" id="submit" class="btn btn-info"/>
    </form>
</div>

If anyone can see what I'm doing wrong and let me know that would be great, thanks in advance.

Upvotes: 1

Views: 841

Answers (2)

malifa
malifa

Reputation: 8165

First of all, you have to declare your click listener in the $(document).ready(function(){}); otherwise this part of code is run before your DOM elements exist and therefore they don't call your click function.

After you fixed this, you will see that your form will perform its default action (the same like you're experiencing right now). For this you have to prevent the default action of your submit button:

$(document).ready(function(){
    $("#submit").on("click", function(ev) {
        ev.preventDefault();

        ...

    });
});

Personally i like on("click", ...) more but your way will work as well. Hope it helps.

Upvotes: 2

Karl Gjertsen
Karl Gjertsen

Reputation: 4928

Is the form going blank or is the page going blank?

You are not preventing the HTML form submit, so the form is being submitted, which is why the values are in the URL.

Try:

$("#submit").click(function(e) {

    e.preventDefault()

    // ajax code here

});

Upvotes: 1

Related Questions