Django div reload - ajax GET after POST does not get latest database model instances












2















In a chat-like app, I'm using ajax calls to POST a new message and update the messages displayed on the page without reloading the entire page. My ajax call for posting works - a new message instance is created in the database. However, afterwards when I make an ajax call to GET all messages, the new message is missing from the resulting query set. If I refresh the page fully, I can see all the messages, but that's not what I'm after.



HTML messages template:



    {% for message in messages %}
<p>
{{ message.content }}
</p>
{% endfor %}


HTML chat template:



<div id="chat">
{% include "messages.html" %}
</div>

<form id="post-message-form", method="post" enctype="multipart/form-data">
[my form goes here]
</form>


JavaScript:



$('#post-message-form').on('submit', function(event){
event.preventDefault();
$form = $(this);
var data = new FormData($form.get(0));

$.ajax({
url: '/post/a/new/message/',
type: 'POST',
data: data,
success: refresh_chat,
cache: false,
contentType: false,
processData: false
})

return false;
}

function refresh_chat(){
$.ajax({
url: '/get/all/messages/,
type: 'GET',
success: function(json) {
$('#chat').html(json['data']);
}
})
return false;
}


Views:



import json
from django.template import loader
from .forms import MessageForm

# /post/a/new/message/
def post_message(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
message = form.save()
return HttpResponse(
json.dumps({'status': 1,
'message': 'Message posted!'}),
content_type='application/json'
)

# /get/all/messages/
def get_messages(request):
if request.method == 'GET':
messages = loader.render_to_string('messages.html', context={'messages': Message.objects.all(), 'form': MessageForm()})
return HttpResponse(
json.dumps({'data': messages}),
content_type='application/json'
)


Any ideas why I do not get the latest database data when I call an ajax GET after POST? Thanks!










share|improve this question

























  • success: refresh_div - should this be refresh_chat?

    – Robin Zigmond
    Nov 21 '18 at 10:08











  • Yeah, sorry, that was a typo. It's not what's causing my problem though.

    – Viktor Petrov
    Nov 21 '18 at 10:19











  • What database are you using?

    – Daniel Roseman
    Nov 21 '18 at 12:39













  • SQLite, default Django app setup.

    – Viktor Petrov
    Nov 21 '18 at 17:25
















2















In a chat-like app, I'm using ajax calls to POST a new message and update the messages displayed on the page without reloading the entire page. My ajax call for posting works - a new message instance is created in the database. However, afterwards when I make an ajax call to GET all messages, the new message is missing from the resulting query set. If I refresh the page fully, I can see all the messages, but that's not what I'm after.



HTML messages template:



    {% for message in messages %}
<p>
{{ message.content }}
</p>
{% endfor %}


HTML chat template:



<div id="chat">
{% include "messages.html" %}
</div>

<form id="post-message-form", method="post" enctype="multipart/form-data">
[my form goes here]
</form>


JavaScript:



$('#post-message-form').on('submit', function(event){
event.preventDefault();
$form = $(this);
var data = new FormData($form.get(0));

$.ajax({
url: '/post/a/new/message/',
type: 'POST',
data: data,
success: refresh_chat,
cache: false,
contentType: false,
processData: false
})

return false;
}

function refresh_chat(){
$.ajax({
url: '/get/all/messages/,
type: 'GET',
success: function(json) {
$('#chat').html(json['data']);
}
})
return false;
}


Views:



import json
from django.template import loader
from .forms import MessageForm

# /post/a/new/message/
def post_message(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
message = form.save()
return HttpResponse(
json.dumps({'status': 1,
'message': 'Message posted!'}),
content_type='application/json'
)

# /get/all/messages/
def get_messages(request):
if request.method == 'GET':
messages = loader.render_to_string('messages.html', context={'messages': Message.objects.all(), 'form': MessageForm()})
return HttpResponse(
json.dumps({'data': messages}),
content_type='application/json'
)


Any ideas why I do not get the latest database data when I call an ajax GET after POST? Thanks!










share|improve this question

























  • success: refresh_div - should this be refresh_chat?

    – Robin Zigmond
    Nov 21 '18 at 10:08











  • Yeah, sorry, that was a typo. It's not what's causing my problem though.

    – Viktor Petrov
    Nov 21 '18 at 10:19











  • What database are you using?

    – Daniel Roseman
    Nov 21 '18 at 12:39













  • SQLite, default Django app setup.

    – Viktor Petrov
    Nov 21 '18 at 17:25














2












2








2








In a chat-like app, I'm using ajax calls to POST a new message and update the messages displayed on the page without reloading the entire page. My ajax call for posting works - a new message instance is created in the database. However, afterwards when I make an ajax call to GET all messages, the new message is missing from the resulting query set. If I refresh the page fully, I can see all the messages, but that's not what I'm after.



HTML messages template:



    {% for message in messages %}
<p>
{{ message.content }}
</p>
{% endfor %}


HTML chat template:



<div id="chat">
{% include "messages.html" %}
</div>

<form id="post-message-form", method="post" enctype="multipart/form-data">
[my form goes here]
</form>


JavaScript:



$('#post-message-form').on('submit', function(event){
event.preventDefault();
$form = $(this);
var data = new FormData($form.get(0));

$.ajax({
url: '/post/a/new/message/',
type: 'POST',
data: data,
success: refresh_chat,
cache: false,
contentType: false,
processData: false
})

return false;
}

function refresh_chat(){
$.ajax({
url: '/get/all/messages/,
type: 'GET',
success: function(json) {
$('#chat').html(json['data']);
}
})
return false;
}


Views:



import json
from django.template import loader
from .forms import MessageForm

# /post/a/new/message/
def post_message(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
message = form.save()
return HttpResponse(
json.dumps({'status': 1,
'message': 'Message posted!'}),
content_type='application/json'
)

# /get/all/messages/
def get_messages(request):
if request.method == 'GET':
messages = loader.render_to_string('messages.html', context={'messages': Message.objects.all(), 'form': MessageForm()})
return HttpResponse(
json.dumps({'data': messages}),
content_type='application/json'
)


Any ideas why I do not get the latest database data when I call an ajax GET after POST? Thanks!










share|improve this question
















In a chat-like app, I'm using ajax calls to POST a new message and update the messages displayed on the page without reloading the entire page. My ajax call for posting works - a new message instance is created in the database. However, afterwards when I make an ajax call to GET all messages, the new message is missing from the resulting query set. If I refresh the page fully, I can see all the messages, but that's not what I'm after.



HTML messages template:



    {% for message in messages %}
<p>
{{ message.content }}
</p>
{% endfor %}


HTML chat template:



<div id="chat">
{% include "messages.html" %}
</div>

<form id="post-message-form", method="post" enctype="multipart/form-data">
[my form goes here]
</form>


JavaScript:



$('#post-message-form').on('submit', function(event){
event.preventDefault();
$form = $(this);
var data = new FormData($form.get(0));

$.ajax({
url: '/post/a/new/message/',
type: 'POST',
data: data,
success: refresh_chat,
cache: false,
contentType: false,
processData: false
})

return false;
}

function refresh_chat(){
$.ajax({
url: '/get/all/messages/,
type: 'GET',
success: function(json) {
$('#chat').html(json['data']);
}
})
return false;
}


Views:



import json
from django.template import loader
from .forms import MessageForm

# /post/a/new/message/
def post_message(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
message = form.save()
return HttpResponse(
json.dumps({'status': 1,
'message': 'Message posted!'}),
content_type='application/json'
)

# /get/all/messages/
def get_messages(request):
if request.method == 'GET':
messages = loader.render_to_string('messages.html', context={'messages': Message.objects.all(), 'form': MessageForm()})
return HttpResponse(
json.dumps({'data': messages}),
content_type='application/json'
)


Any ideas why I do not get the latest database data when I call an ajax GET after POST? Thanks!







python json ajax django






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 10:19







Viktor Petrov

















asked Nov 21 '18 at 10:00









Viktor PetrovViktor Petrov

318




318













  • success: refresh_div - should this be refresh_chat?

    – Robin Zigmond
    Nov 21 '18 at 10:08











  • Yeah, sorry, that was a typo. It's not what's causing my problem though.

    – Viktor Petrov
    Nov 21 '18 at 10:19











  • What database are you using?

    – Daniel Roseman
    Nov 21 '18 at 12:39













  • SQLite, default Django app setup.

    – Viktor Petrov
    Nov 21 '18 at 17:25



















  • success: refresh_div - should this be refresh_chat?

    – Robin Zigmond
    Nov 21 '18 at 10:08











  • Yeah, sorry, that was a typo. It's not what's causing my problem though.

    – Viktor Petrov
    Nov 21 '18 at 10:19











  • What database are you using?

    – Daniel Roseman
    Nov 21 '18 at 12:39













  • SQLite, default Django app setup.

    – Viktor Petrov
    Nov 21 '18 at 17:25

















success: refresh_div - should this be refresh_chat?

– Robin Zigmond
Nov 21 '18 at 10:08





success: refresh_div - should this be refresh_chat?

– Robin Zigmond
Nov 21 '18 at 10:08













Yeah, sorry, that was a typo. It's not what's causing my problem though.

– Viktor Petrov
Nov 21 '18 at 10:19





Yeah, sorry, that was a typo. It's not what's causing my problem though.

– Viktor Petrov
Nov 21 '18 at 10:19













What database are you using?

– Daniel Roseman
Nov 21 '18 at 12:39







What database are you using?

– Daniel Roseman
Nov 21 '18 at 12:39















SQLite, default Django app setup.

– Viktor Petrov
Nov 21 '18 at 17:25





SQLite, default Django app setup.

– Viktor Petrov
Nov 21 '18 at 17:25












1 Answer
1






active

oldest

votes


















0














Turns out if I do my chat refresh on the ajax "done" call instead of on "success" it works:



$('#post-message-form').on('submit', function(event){
event.preventDefault();
$form = $(this);
var data = new FormData($form.get(0));

$.ajax({
url: '/post/a/new/message/',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false
}).done(function() {
refresh_chat();
});

return false;
}


Thanks for commenting!






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53409499%2fdjango-div-reload-ajax-get-after-post-does-not-get-latest-database-model-insta%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Turns out if I do my chat refresh on the ajax "done" call instead of on "success" it works:



    $('#post-message-form').on('submit', function(event){
    event.preventDefault();
    $form = $(this);
    var data = new FormData($form.get(0));

    $.ajax({
    url: '/post/a/new/message/',
    type: 'POST',
    data: data,
    cache: false,
    contentType: false,
    processData: false
    }).done(function() {
    refresh_chat();
    });

    return false;
    }


    Thanks for commenting!






    share|improve this answer




























      0














      Turns out if I do my chat refresh on the ajax "done" call instead of on "success" it works:



      $('#post-message-form').on('submit', function(event){
      event.preventDefault();
      $form = $(this);
      var data = new FormData($form.get(0));

      $.ajax({
      url: '/post/a/new/message/',
      type: 'POST',
      data: data,
      cache: false,
      contentType: false,
      processData: false
      }).done(function() {
      refresh_chat();
      });

      return false;
      }


      Thanks for commenting!






      share|improve this answer


























        0












        0








        0







        Turns out if I do my chat refresh on the ajax "done" call instead of on "success" it works:



        $('#post-message-form').on('submit', function(event){
        event.preventDefault();
        $form = $(this);
        var data = new FormData($form.get(0));

        $.ajax({
        url: '/post/a/new/message/',
        type: 'POST',
        data: data,
        cache: false,
        contentType: false,
        processData: false
        }).done(function() {
        refresh_chat();
        });

        return false;
        }


        Thanks for commenting!






        share|improve this answer













        Turns out if I do my chat refresh on the ajax "done" call instead of on "success" it works:



        $('#post-message-form').on('submit', function(event){
        event.preventDefault();
        $form = $(this);
        var data = new FormData($form.get(0));

        $.ajax({
        url: '/post/a/new/message/',
        type: 'POST',
        data: data,
        cache: false,
        contentType: false,
        processData: false
        }).done(function() {
        refresh_chat();
        });

        return false;
        }


        Thanks for commenting!







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 '18 at 6:16









        Viktor PetrovViktor Petrov

        318




        318
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53409499%2fdjango-div-reload-ajax-get-after-post-does-not-get-latest-database-model-insta%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            Npm cannot find a required file even through it is in the searched directory