0

I am using jquery.webspirited.coms tagit jquery, which is working correctly in the sense of creating the tags, separating on the front end, but when I POST the data, it's only posting the last tag as the value to the database..

I can't find any documentation on how to correctly install the addon apart from what code to put in the header etc, here is the header code.

<script type="text/javascript">
$(function () {

  $('#topic').tagit();    

  $('#topicGetTags').click(function () {
    showTags($('#topic').tagit('tags'))
  });
  $('input[type=submit]').click(function(){
    tag = $('#topic').tagit('tags');
    console.log(tag);
    for (var i in tag)
      $('form').append("<input type='hidden' name='tags[]' value='"+tag[i].value+"' >");

  });
  function showTags(tags) {
    console.log(tags);
    var string = "Tags (label : value)\r\n";
    string += "--------\r\n";
    for (var i in tags)
      string += tags[i].label + " : " + tags[i].value + "\r\n";
    alert(string);
  }
});
</script>

The input

<ul id="topic" name="tags[]"></ul>

The tagit.js file itself has almost 500 lines, so rather than copy/paste it here, here is a link to it.

http://webspirited.com/tagit/js/tagit.js

Also here is the INSERTION code, incase it's something I need to look at there

$tags = isset($_POST['tags']) ? $_POST['tags'] : null;

if (is_array($tags)) {
foreach ($tags as $t) {
    // escape the $t before inserting in DB
    $sql = "INSERT INTO tags (tags) VALUES('$t')";
}

Thanks for any tips

user2571547
  • 87
  • 1
  • 1
  • 9

2 Answers2

0

Change the hidden input name to name="tag[]" and you'll receive an array in $_POST['tag'] in your PHP script - at present you're overwriting the previous input which is why you're only receiving one item.

You can then loop over the array and insert them as required in your database.

Anthony Sterling
  • 2,451
  • 16
  • 10
0

Try this:

$tag = isset($_POST['tag']) ? $_POST['tag'] : null;

if (is_array($tag)) {
    foreach ($tag as $t) {
        // escape the $t before inserting in DB
        $sql = "INSERT INTO tags (tag) VALUES('$t')";
    }
} else {
    echo 'Invalid tag';
}

*Updated: Change below code (Use tage[] for name and wrap append code in {}. May be you have something between for and append and your append code executing after for loop end)

for (var i in tag)
    $('form').append("<input type='hidden' name='tag' value='"+tag[i].value+"' >");

As below:

for (var i in tag) {
    $('form').append("<input type='hidden' name='tag[]' value='"+tag[i].value+"' >");
}
Manoj Yadav
  • 6,560
  • 1
  • 23
  • 21