0

This script basically serializes a form and do get request on an api and retrieves json response. Received response can be modified by adding additional parameters via said form and serialized and is send to api and so forth. Right now every time i press submit only the last element shows up on the screen. I tried append functionality but it creates duplicate of the same set items instead of refreshing the items on the page. I believe it is a enclosure issue that may be trivial but i am not well versed in jquery and java script in general.

<script>
$(document).ready(function() {
  var APISOURCE = '../api/software/?format=json'
  $('#filterform').on('submit',function(e){
    e.preventDefault();
    var query = $('#filterform').serialize();
    console.log(query);
        $.ajax({
                datatype: 'json',
                url: APISOURCE,
                query: query,
                success: function(data){
                    console.log(data.results[0]);
                    $.each(data.results, function(i,results){
                        content = '<p>' + results.developer + '</p>';
                        content += '<br/>';
                        //$(content).empty("#softwarelist").appendTo("#softwarelist");
                        $("#softwarelist").html(content);
                      });


                }/* response processing function ends */
            });/* ajax function ends */

  });
});
</script>
shaytac
  • 3,789
  • 9
  • 36
  • 44

3 Answers3

2

Try building a string by concatenating each result as you go and setting it to your div at the end of your loop:

Also, content will be undefined - I'll presume you mean results.content as returned from your AJAX return.

var content;
$.each(data.results, function(i,results){
    content += '<p>' + results.developer + '</p><br>' + results.content;
});
$('#softwarelist').html(content);
scrowler
  • 24,273
  • 9
  • 60
  • 92
  • Be sure to initialize content: `var content = '';` – par Dec 12 '13 at 04:10
  • As you have it now `content` is `undefined` when you enter the `each()` loop. – par Dec 12 '13 at 04:14
  • Check out this [JSFiddle](http://jsfiddle.net/bdpdx/6d3pu). If you try to use `+=` on an undefined variable you'll get something you don't want. In this case after the first loop iteration you'll have `content === 'undefined

    ...'`

    – par Dec 12 '13 at 08:33
1

You should edit code as below:

  $("#softwarelist").html(''); //remove old html first
  $.each(data.results, function(i,results){
                    content = '<p>' + results.developer + '</p>';
                    content += '<br/>';
                    //$(content).empty("#softwarelist").appendTo("#softwarelist");
                    $("#softwarelist").append(content); //append new content
  });
Thanh Khánh
  • 621
  • 1
  • 9
  • 21
0

make the content as array and push the elements into that array to add all the values and later display that array

varun kumar
  • 115
  • 1
  • 12