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?

Community
  • 1
  • 1
ABM
  • 1,628
  • 2
  • 26
  • 42

2 Answers2

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?

Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • I made the change to JSON.stringify, to no avail. – ABM Oct 07 '14 at 17:35
  • 1
    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? – Rob M. Oct 07 '14 at 17:35
  • 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 – ABM Oct 07 '14 at 17:37
  • 1
    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. – Rob M. Oct 07 '14 at 17:41
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'
       );
Luke Yeager
  • 1,400
  • 1
  • 17
  • 30
  • 2
    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. – dirn Oct 07 '14 at 18:24