Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax response inside a div

Tags:

jquery

ajax

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?

like image 849
black_belt Avatar asked May 13 '12 23:05

black_belt


2 Answers

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');
    }
});​
like image 61
VisioN Avatar answered Sep 21 '22 14:09

VisioN


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

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

The selector should be .result not #result

like image 42
gdoron is supporting Monica Avatar answered Sep 21 '22 14:09

gdoron is supporting Monica