views:

54

answers:

2

I'm building a tagger. After a user submits a tag, ajax returns:

{"returnmessage":"The Ajax operation was successful.","tagsinserted":"BLAH, BLOOOW","returncode":"0"}

I want to take the tagsinserted and loop through it, and during each loop take the item in the list and insert it on the HTML page. suggestion on how to do this right?

Here is the current code:

$("#tag-post").click(function(){
    // Post $('#tag-input').val()
    $.ajax({
        url: '/tags/ajax/post-tag/',
        data: { newtaginput : $('#tag-input').val(), userid : $('#userid').val()},
        success: function(data) {
            // After posting
            alert('done');

        }
    });     

});
A: 

You can loop through the tags by calling data.tags.split(',') and looping through the array it returns.

You can insert tags to the page by calling $('<li />').text(tag).appendTo('someSelector').

SLaks
Thanks but can you show me the end 2 end?
AnApprentice
+1  A: 

You can do something like this:

$("#tag-post").click(function(){
  $.ajax({
    url: '/tags/ajax/post-tag/',
    data: {newtaginput : $('#tag-input').val(), userid : $('#userid').val()},
    success: function(data) {
      $.each(data.tagsinserted.split(', '), function(i, v) {
        $("<div></div>").text(v).appendTo("#tagHolder");
      });
    }
  });
});
Nick Craver
I like this. strange.. Here is the response:{"returnmessage":"The Ajax operation was successful.","tagsinserted":"adadada","returncode":"0"}I'm getting a tagsinserted is undefined?
AnApprentice
@nobosh - Add the `dataType: 'json',` option to your $.ajax call and `alert(data);` to your success call, what do you get?
Nick Craver
It's still saying "data.tagsinserted is undefined" in Firebug.... Here is the response again: {"returnmessage":"The Ajax operation was successful.","tagsinserted":"tettttt","returncode":"0"}
AnApprentice
For Alert Data, it's showing up right I think: {"returnmessage":"The Ajax operation was successful.","tagsinserted":"tettttt","returncode":"0"}
AnApprentice
alert(data.tagsinserted); is altering undefined too
AnApprentice
@nobosh - That's with `dataType:'json'`?
Nick Craver