0

I am using python flask, I want the status of the button to change from "like" to liked when a user clicks it. I get no console errors, XHR loads perfectly. If I click the button and reload the page manually the status of the button changes, but I will like to do the reload with Ajax. Here is my code, thanks in advance. The backend returns a JSON object with jsonify.

HTML:

<button class="btn btn-pill btn-warning btn-xs" id="async_like">
<span class="icon icon-thumbs-up"></span> Like

jQuery:

<script>
$('button#async_like').click(function () {

  $.ajax({
    url :"{{ url_for('.like_post', id=post.id) }}",
    type : 'POST',
    success : function (resp) {
        $('#async_like').append(resp);
    }
  })
})
</script>
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
aharding378
  • 207
  • 1
  • 3
  • 16

1 Answers1

0

One possible approach could be to use query string parameter when reloading HTML document. At load event of window check if location.search is not an empty string, or is a specific key, value pair, if the condition is true, set the HTML using the query string key and value.

$.ajax()
.then(resp => {
  $("#async_like").html(resp);
  location.href = location.href + "?button=" + resp
})

At .ready() alias jQuery() at each HTML document check if the query string exists to set HTML of an element

$(() => {
  if (location.search) {
    let [prop] = [...new URLSearchParams(location.search).values()];
    if (prop === "clicked") {
      $("#element").html(prop);
    }
  }
});

plnkr http://plnkr.co/edit/3VQVSevHFvSE8SYcNEvU?p=preview

guest271314
  • 1
  • 15
  • 104
  • 177