black_belt
black_belt

Reputation: 6799

Ajax response inside a div

I am trying to show the value of ajax response inside a div and for that I have the following code in my view file.

<script type="text/javascript" src="MY LINK TO JQUERY"></script>

<script  type="text/javascript">
     $(function(){ // added
     $('a.vote').click(function(){
         var a_href = $(this).attr('href');

     $.ajax({
            type: "POST",
            url: "<?php echo base_url(); ?>contents/hello",
            data: "id="+a_href,
            success: function(server_response){
                             if(server_response == 'success'){
                                  $("#result").html(server_response); 
                             } 
                             else{
                                  alert('Not OKay');
                                 }

                      }
  });   //$.ajax ends here

  return false
    });//.click function ends here
  }); // function ends here
 </script>

  <a href="1" title="vote" class="vote" >Up Vote</a>
  <br>
  <div class="result"></div>                                        

my Controller (to which the ajax is sending the value):

function hello() {
              $id=$this->input->post('id');
              echo $id;
             }      

Now what I am trying achieve is get the server_response value (the value that is being sent from the controller) in side <div class="result"></div> in my view file.

I have tried the following code but its not showing the value inside the div.

Could you please tell me where the problem is?

Upvotes: 13

Views: 88321

Answers (3)

VisioN
VisioN

Reputation: 145368

The problem is that you have mixed arguments of Ajax success handler. First goes data which your script gives back, then goes textStatus. Theoretically it can be "timeout", "error", "notmodified", "success" or "parsererror". However, in success textStatus will always be successful. But if you need to add alert on error you can add error handler. And yes, change selector in $("#result") to class. So corrected code may look like this:

$.ajax({
    type: "POST",
    url: "<?php echo base_url(); ?>contents/hello",
    data: "id=" + a_href,
    success: function(data, textStatus) {
        $(".result").html(data);    
    },
    error: function() {
        alert('Not OKay');
    }
});​

Upvotes: 14

gdoron
gdoron

Reputation: 150253

success: function(server_response) {
        $(".result").html(server_response);
}​

<div class="result"></div> // result is the class

The selector should be .result not #result

Upvotes: 6

Matt Healy
Matt Healy

Reputation: 18531

Try changing <div class="result"></div> to <div id="result"></div>, because that's what you're referencing in your ajax success function

$("#result").html(server_response);

Upvotes: 1

Related Questions