in Education by
I have a POST request that passes data to my database when the form is submitted. Photo of what I mean: home.html $(document).ready(function(){ var postForm = $(".form-post") //POSTING DATA INTO DATABASE postForm.submit(function(event){ event.preventDefault(); var thisForm =$(this) var actionEndPoint = thisForm.attr("action"); var httpMethod = thisForm.attr("method"); var formData = thisForm.serialize(); $.ajax({ url: actionEndPoint, method: httpMethod, data: formData, success:function(data){ console.log(data) $(".form-post")[0].reset(); //I WANT TO PASS THE NEWLY ADDED DATA TO DISPLAY WITHOUT REFRESH $.ajax({ type: 'GET', url: '{% url "postInfo" %}', dataType : 'json', success: function(cdata){ $.each(cdata, function(id,posts){ $('#cb').append('' +posts['fields'].title+ ' ' +posts['fields'].body+ ''); }); } }); }, error:function(errData){ } }) }) }) As it is now it shows multiple of the same posts every time I add a post. This is my views views.py def postInfo(request): # GET REQUEST if request.method == 'GET' and request.is_ajax(): mytitle = Post.objects.all().order_by('-date_posted') response = serializers.serialize("json", mytitle) return HttpResponse(response, content_type='application/json') def posting(request): # POST REQUEST if request.method == 'POST' and request.is_ajax(): title = request.POST.get('postTitle') content = request.POST.get('postContent') post = Post() post.title = title post.body = content post.author = request.user post.save() return HttpResponse('') models.py class Post(models.Model): title = models.CharField(max_length=50) body = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title How can I make it so it just shows the post that I have added + what's in the database without showing multiple of the same posts? Thanks for any help. JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by
You are getting multiples because you are asking for every post in the database to be sent upon the success of the POST request. Assuming cdata is an array, you could do something like let innerHtml; cdata.forEach(function(obj) { innerHtml.append(`${data['fields'].title} ${data['fields'].body}`); }); $('#cb').html(innerHtml); $('#cb').html(...) will replace the HTML content of the element rather than add to it so you will not get any duplicate entries. Also using a template literal in the append method can make things a little cleaner. Or you could simply send only the post you have just created in your posting view in it's HttpResponse. This will also be faster as you reduce the number of requests made when the form is submitted. views.py # Other endpoints ... def posting(request): # POST REQUEST if request.method == 'POST' and request.is_ajax(): title = request.POST.get('postTitle') content = request.POST.get('postContent') post = Post() post.title = title post.body = content post.author = request.user post.save() # Send new post as response response = serializers.serialize('json', post) return HttpResponse(response, content_type='application/json') home.html $(document).ready(function(){ var postForm = $(".form-post"); // POSTING DATA INTO DATABASE postForm.submit(function(event){ event.preventDefault(); var thisForm = $(this); var actionEndPoint = thisForm.attr("action"); var httpMethod = thisForm.attr("method"); var formData = thisForm.serialize(); $.ajax({ url: actionEndPoint, method: httpMethod, data: formData, success: function(data) { console.log(data); $(".form-post")[0].reset(); // Add the new post to $('#cb') $('#cb') .append(`${data['fields'].title} ${data['fields'].body}`); }, error: function(errData){ // Do something } }) }) })

Related questions

0 votes
    I have a POST request that passes data to my database when the form is submitted. Photo of what I ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 13, 2022 in Education by JackTerrance
0 votes
    I am using a framework, which returns invalid JSON String like: /* { "myobject" : "test"} */ ... , JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 2, 2022 in Education by JackTerrance
0 votes
    We are planning to use the jQuery library to augment our client side JavaScript needs. Are there any major ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 25, 2022 in Education by JackTerrance
0 votes
    I have a simple MVC3 Controller Action like this [HttpGet] [OutputCache(Duration = 1200,Location=System.Web. ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 13, 2022 in Education by JackTerrance
0 votes
    First I'll explain my senario: I have a page in which users login or register. The login control ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 10, 2022 in Education by JackTerrance
0 votes
    When I use ajax call from a modal window, the request url seems not correct. I have a webserver ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 7, 2022 in Education by JackTerrance
0 votes
    My question is a variant of the question here However, there are two differences: I don't know how ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 23, 2022 in Education by JackTerrance
0 votes
    My question is a variant of the question here However, there are two differences: I don't know how ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 23, 2022 in Education by JackTerrance
0 votes
    I am building a backoffice to a certain site, and here i need to delete the comments from the ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 9, 2022 in Education by JackTerrance
0 votes
    I am using jquery ajax get. SO when my form is submitted it then submits to a php file but the ... , JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 7, 2022 in Education by JackTerrance
0 votes
    I am building a backoffice to a certain site, and here i need to delete the comments from the ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 7, 2022 in Education by JackTerrance
0 votes
    I am building a backoffice to a certain site, and here i need to delete the comments from the ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 5, 2022 in Education by JackTerrance
0 votes
    I am using jquery ajax get. SO when my form is submitted it then submits to a php file but the ... , JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 5, 2022 in Education by JackTerrance
0 votes
    I am building a backoffice to a certain site, and here i need to delete the comments from the ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 5, 2022 in Education by JackTerrance
0 votes
    I am trying to paginate the results of an SQL query for use on a web page. The language and the ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 27, 2022 in Education by JackTerrance
...