2

PROBLEM SOLVED.. I update my code accordingly.. Thanks all

Intro: My code display array of message traces (each message display in grey-panel). User can delete unwanted message by click on delete button, the message will be deleted in both DB and disappear from screen.

Seems my delete function is not working.. Appreciate for advice.. I don't know AJAX.. this is my first try. Thanks in advance.

The following are my code:

ajax code:

$(document).ready(function(){
    $("body").on("click", "#responds .del_button", function(e) {
        e.preventDefault();
         var $btn = $(this),
             $li = $btn.closest('li');

        var traceId = $li.data('trace-id');

        jQuery.ajax({
                  type: 'post', 
                  url: 'traceDelete', 
                  dataType: 'text',

                  data: { 'traceId': traceId },

                  success: function (res) {
                      if (res === '1') {
                          $btn.fadeOut();
                      }
                  },
                  error: function (xhr, ajaxOptions, thrownError){
                      alert(thrownError);
                  }
        });
    });

part of view code:

<ul id="responds">
    <?php foreach ($line as $dataName => $contents){ ?>    
        <li data-trace-id="<?php echo $contents->trace_id; ?>">
            <div class="grey-panel" style="text-align:right">
                <div class="del_wrapper" id="<?php echo $contents->trace_id; ?>">
                    <a href="#" class="del_button" id="<?php echo $contents->trace_id; ?>" data-hover="tooltip" title="Delete this message <?php echo $contents->trace_id; ?>"  >
                        <i class="fa fa-times"></i>
                     </a>
                </div>
                <div class="col-sm-12 col-xs-12">
                  <?php print $contents->trace_hdr.'<br />';
                  print $contents->trace_src.'<br />';
                  print $contents->trace_dest.'<br />';
                  // some other things ?>
                </div>
            </div>
        </li> 
    <?php } ?>
</ul>

controller code:

public function traceDelete($traceID) {
    if ($traceId = $this->input->post('traceId')) {
    return $this->model_general->deleteTrace($traceId);
    }
    return false;
}

model code:

public function deleteTrace($id) {
    $this->db->where('trace_id', $id);
    $this->db->delete('trace_tbl');
    return $this->db->affected_rows() > 1 ? true:false;
}
Julie
  • 313
  • 6
  • 18
  • Is there any error in firebug console for ajax? I think your ajax will throw 500 error. – kishor10d Nov 15 '16 at 12:56
  • @kishor yes.. i hit 500 error – Julie Nov 15 '16 at 13:32
  • Please post your error with the question – Giri Annamalai M Nov 15 '16 at 14:38
  • Ok, then you have to provide the proper url to your Ajax. E.g. http://localhost/index.php/your_controller/traceDelete – kishor10d Nov 15 '16 at 14:38
  • i think my javascript not working .. i didnt get correct value for myData .. not sure where the problem.. coz i dont see any error anymore.. manage to reach success:function(traceDelete) and get alert "Deleted" – Julie Nov 16 '16 at 01:38
  • @Julie check by placing a `console.log(myData)` underneath `var myData = DbNumberID`.Keep your console open to see the value in the var. – techie_28 Nov 16 '16 at 07:00

2 Answers2

2

First, you are using the id attributes wrong. They are meant to be unique as in appear on one element and not multiple as you have done. (As well, id attributes cannot start with a digit.) There's really no need to put it on multiple containing elements as you can easily traverse to the parents or children with jQuery's .find(), .parent(), .closest(), and other traversing methods. However, this should not be the cause of your problem.

Now, what I do think is the cause of your problem is that you are passing the 2nd character of your id attribute into your AJAX request.

$(document).ready(function(){
    $("body").on("click", "#responds .del_button", function(e) {
        e.preventDefault();
        // assign the ID e.g. "abc" to clickedID
        var clickedID = this.id; 
        // problem: assign the second character of your ID i.e. "b" into DbNumberID
        var DbNumberID = clickedID[1];
        // assign the same value to myData (which is redundant)
        var myData = DbNumberID; 

        $(this).hide(); 

        jQuery.ajax({
            type: "POST", 
            url: 'traceDelete', 
            dataType:"text", 
            // sending "myData=b"
            data: { myData: myData }, 
            success:function(traceDelete){
                alert("Deleted");
                $(DbNumberID).fadeOut();
            },
            error:function(xhr, ajaxOptions, thrownError){
                alert(thrownError);
            }
        });
});

I am not too familiar with CodeIgniter anymore, but you need to get value from the $_REQUEST or $_POST array or use their built-in function.

$myData = $this->input->post('myData'); // because you are sending myData

EDIT

This is untested but here's how I would do it.

HTML

First, let's use HTML5 data attribute call it data-trace-id. This will be used instead of your numerous improper usages of id attributes.

<ul id="responds">
<?php foreach ($line as $dataName => $contents) : ?>    
    <li data-trace-id="<?php echo $contents->trace_id ?>">
        <div class="grey-panel" style="text-align: right">
            <div class="del_wrapper">
                <a href="#" class="del_button" data-hover="tooltip" title="Delete this message <?php echo $contents->trace_id ?>">
                    <i class="fa fa-times"></i>
                </a>
            </div>
            <div class="col-sm-12 col-xs-12">
                <?php echo $contents->trace_hdr ?><br />
                <?php echo $contents->trace_src ?><br />
                <?php echo $contents->trace_dest ?><br />
                <!-- etc -->
            </div>
        </div>
    </li> 
<?php endforeach ?>
</ul>

JavaScript

Next, let's simplify your JavaScript. I'll use the dreaded alert() for debugging purposes -- but it's usually better to use console.log().

$(function() {
    $("#responds").on("click", ".del_button", function (e) {
        e.preventDefault();

        // keyword 'this' refers to the button that you clicked;
        // $(this) make a jQuery object out of the button;
        // always good idea to cache elements that you will re-using;
        var $li = $(this).closest('li');

        // get the associated trace ID from the list-item element;
        var traceId = $li.data('trace-id');

        alert('trace ID ' + traceId);

        // assuming you only want to hide the message only if it has been been successfully deleted from the DB?
        // if that is the case, then you have to wait for the AJAX response to tell you whether it was
        jQuery.ajax({
            type: 'post', 
            url: 'traceDelete', 
            dataType: 'text',
            // notice how I am using 'traceId'? on the server-side, the data will accessible by using $_POST['traceId'] or $this->input->post('traceId') 
            data: { 'traceId': traceId },
            // look at the response sent to you;
            // if I am not mistaken (boolean) true and false get sent back as (strings) 1 or 0, respectively;
            // so if the response is 1, then it was successfully deleted
            success: function (res) {
                alert('AJAX response ' + res);
                if (res === '1') {
                    alert('hiding button');
                    // hide the message
                    $li.fadeOut();
                }
            },
            error: function (xhr, ajaxOptions, thrownError){
                alert(thrownError);
            }
        });
    });
});

PHP

Lastly, we take the value from the $_POST array. Check whether there is a value: if so, delete the item; otherwise ignore it.

public function traceDelete() 
{
    if ($traceId = $this->input->post('traceId')) {
        echo $this->model_general->deleteTrace($traceId) ? '1' : '0';
    }
    echo '0';
}
Mikey
  • 6,728
  • 4
  • 22
  • 45
  • Thanks for the great explanation.. as I understand a lot from it.. However, it is still not working.. The trace ID is blank and AJAX response (res value) also blank – Julie Nov 16 '16 at 04:38
  • I already debug and confirm that there is value in data-trace-id.. but somehow didnt pass the value – Julie Nov 16 '16 at 04:45
  • To me, your past comments indicates that you have a PHP error. [Turn on your errors](http://stackoverflow.com/a/7371046/1022914). Are you also posting to the correct URL? Should there not be more to the URL than just `traceDelete` such as the base URL prepended to it? The fact that you are getting a blank response means that you are not going to the request handler OR you have an error somewhere in your PHP. – Mikey Nov 16 '16 at 05:57
  • I don't see any error.. all data populate accordingly.. earlier i hit 500 error after click on the delete button.. but solve it..(its a typo error) Now i get blank value for data-trace-id.. I believe it goes to the function, otherwise, I wont see the trace-id for that data.. am I wrong?.. really stuck here.. i want to use ajax so i dont have to refresh the page each time user delete the trace.. hmmm – Julie Nov 16 '16 at 06:24
  • My apology. Change commas in the `alert()` to pluses (as shown in my edit). You should be able to see the values. – Mikey Nov 16 '16 at 06:43
  • I'm not sure if this is the cause of the problem... I notice.. my base URL is .../searchTrace searchTrace is a function in Controller.. The flow of the system are as follows: 1. User search for a particular trace based on few search criteria.. 2. System display list of traces (which may include unnecessary trace) 3. User can delete the unwanted traces by click on delete button 4. Final trace is saved / download. But i don't think it is the cause – Julie Nov 16 '16 at 06:48
  • I get trace ID undefined – Julie Nov 16 '16 at 06:53
  • K, that's weird. Here is a quick [demo](http://codepen.io/anon/pen/pNEeLy). Your first problem is that you are no longer getting the trace ID on the client-side. Are you sure you followed the same structure? In terms of your second problem, now that I think about it, inside the function `traceDelete()`, change your `return`s to `echo`s as you send an AJAX response by echo'ing/printing. – Mikey Nov 16 '16 at 07:08
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/128228/discussion-between-mikey-and-julie). – Mikey Nov 16 '16 at 07:13
0

remove var DbNumberID = clickedID[1]; var myData = DbNumberID;, as its not needed. Directly assign data: { myData: clickedID },. Also get value of myData in controller via POST.

public function traceDelete() {

    $traceID = $this->input->post('myData');

    if($traceID)
        return $this->model_general->deleteTrace($traceID);

    return false;
}