Data from javascript to python(using post)

I am trying to give data from javascript to python, using post

On my Javascript

$('ABC').on("click", function(){
    $.post( '/user',
        {
            user: 'here'
        }
    )});

And giving this to python

@app.route("/user", methods=['GET', 'POST'])
def user():
    id = user
    return id

Above code should show html with just user.

But page does not move when on click..

Any idea?

728x90

2 Answers Data from javascript to python(using post)

You need to provide a callback function in $.post

$('ABC').on("click", function() {
  $.post('/user', {
    user: 'here'
  }, function(response) {
    $("#result").html(response);
  });
});

You can also abbreviate this to the .load() method:

$('ABC').on("click", function() {
  $("#result").load('/user', {
    user: 'here'
  });
});

1 weeks ago

From what I understand, you're looking for this:

$('ABC').on("click", function() {
  var $form = $("<form>").attr("action", "/post").attr("method", "post");
  $form.append($("<input>").attr("type", "hidden").attr("name", "user").val("here"));
  $("body").append($form);
  $form.submit();
  return false;
});

This will create a hidden POST form, populate it, append it to <body> and submit it.

1 weeks ago