Pass Parameter to Selector for Ajax Call onClick?

Have a JQUERY AJAX call in a $(document).ready(function()..) that loops through MongoDB docs and adds HTML Divs to the page with a .get

Included in each Div is a <button type='button' id='deleteItem' class='close' onClick='deleteThisItem(" + i + ")' aria-hidden='true'>&times;</button>"

Each Div also has a form field, with a hidden value for returning the doc _id to then use in Express/Node.js to find and delete the correct doc (this does work in another app..)

"..<form name='theForm' id='theForm" + i + "'>
<input type='hidden' name='iD' id='iD' value='" + doc._id + "'>.."

Am looking to have the button delete the MongoDB doc onClick using an AJAX .post

      // handle DELETE (x) button clicks     
    $('#deleteItem').click(function(i) {

      number = i;
      alert(number);

      // make an ajax call
      $.ajax({
        dataType: 'json',
        data: $('#theForm' + number).serialize(),
        type: 'POST',
            url: "http://localhost:9999/delete",
            success: gotAllSuccess,
            error: gotAllFailure
        });

    });

Tried using a global variable (not ideal) var number = 0;, to pass the i parameter through a function outside of the $(document).ready(function()..) and have been researching callback techniques to callback the ajax, but nothing has done the trick..

function deleteThisItem(i)
{
  number = i;
  alert(number);

  //some callback to the Jquery in the ready doc?       
}

Answers


Since you have multiple records, don't use id for the button since id of an element must be unique, use class attribute to group them. Also there is no need to have an inline click handler

<button type='button' class='close deleteItem' data-id='" + i + "' aria-hidden='true'>&times;</button>

then use delegated event handler like

jQuery(function ($) {
    $(document).on('click', '.deleteItem', function () {
        var $this = $(this);
        var number = $this.data('id');
        alert(number);

        // make an ajax call
        $.ajax({
            dataType: 'json',
            data: $('#theForm' + number).serialize(),
            type: 'POST',
            url: "http://localhost:9999/delete",
            success: gotAllSuccess,
            error: gotAllFailure
        });

    });
})

Need Your Help

Is there any online application to store or bookmark new plugins or technologies I learnt for future use?

php web-applications web-technologies

I am a programmer. Everyday I see new plugins, library, framework and technologies. Some I use for my work, some I read. It's difficult to member what I have learnt and which was the purpose of use...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.