2

I have an HTML form that I want to submit to a flask endpoint, /add_int. When the form is submitted I intercept it with Jquery and submit the form to the endpoint using AJAX as follows:

var form = $( this ).serialize()

$.post({                           
   url: "{{ url_for('add_int') }}",
   data: JSON.stringify(form),
   contentType: 'application/json;charset=UTF-8',       
   success: function(resp) {
       console.log(resp);
   }
 });

The endpoint looks like this:

 @app.route('/add_int', methods=['GET', 'POST'])
 @login_required
 def add_int():
    # do stuff
    return jsonify(status="success!")

My issue is that I never get to the endpoint.

When I examine my console I see

POST http://127.0.0.1:5000/[object%20Object] 404 (NOT FOUND) 

instead of

POST http://127.0.0.1:5000/add_int

as I'd expect.

Note that if I set

url: '/add_int',

I run into the same problem.

I've found cases that use almost identical code that don't mention this problem: e.g. how can I use data posted from ajax in flask?

My guess, is that my url is being resolved as a String object rather than a url, but I can't figure out why it's happening, and how to fix it.

What's going on?

2 Answers 2

2

You should remove the call to JSON.stringify, you can pass a serialized form directly as POST data and JSON.stringify is turning your object into [Object object].

url: '/add_int', isn't working because (it appears that) your frontend is running on a different port than the backend, so it will be rejected as a "cross domain" request. Have you inspected the value that "{{ url_for('add_int') }}" is returning?

Sign up to request clarification or add additional context in comments.

4 Comments

I made the change to JSON.stringify, to no avail.
I just updated my answer, what is "{{ url_for('add_int') }}" returning? And if you inspect the request in the console, is the correct data now being passed to the server?
Thanks. I'm confused about the url because I can use url: '/add_int' as a url for a GET ajax request without any difficulties
I can't say for sure, but it looks like url_for is failing and returning an error or something instead of the url you are expecting. My advice would be to dump the return value and see what's going on.
1

Try not specifying the hash keys explicitly. http://api.jquery.com/jquery.post/

$.post("{{ url_for('add_int') }}",
        JSON.stringify(form),
        function(resp) {
            console.log(resp);
        },
       'application/json;charset=UTF-8'
       );

1 Comment

To add to the answer a little, $.ajax needs the url key. The shortcuts (.e.g, $.get, $.post) take the URL as the first parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.