7

I'm making an web that is a single-page website interacting with the server through Ajax in CodeIgniter. The general coding is of the following type:

controller (user.php):

public function get_user_content() {
    $id = $this->input->post('id');
    $hits = $this->user_model->user_data($id);
    $s = '';    
    foreach ($hits as $hit) {
       $s .= $hit->name;
       $s .= $hit->age;
    }
    echo $s;
}

model(user_model.php):

function user_data($id) {
   //do sql operation
   return $query->result();
}

view:

...
...
<a href="#" id="23" class="user-data">Click here for user details</a>
...
...

javascript:

('.user-data').click(get_user_data);
....
....
function get_user_data(response) {
    return $.ajax({
        type: "POST",
        url:  "<?php echo base_url();?>index.php/user/get_user_content",
        data: { id: this.id },
        success: function(response) {
            $("#somediv").append(response);
            $(".someclass").click(another_function);
        },
        error: function(error) {
            alert("Error");
        }
    });
}

So, looking at the above javascript, there are separate functions for all actions that send some data to the server and the particular html content is updated via Ajax.

I had the following questions (I'm just new to this stuff):

1. Is there any better way of doing ajax in javascript than my implementation.
2. I'm not using the concept of views in CodeIgniter. I just `echo` results through my controller functions that gets embedded in javascript. This is because I want dynamic update in my app. It is a single page and there is no concept of new-page/new-tab. Is there any better way? 

I'm not aware of any open-source projects that might make it easier/more optimized.

xan
  • 4,640
  • 13
  • 50
  • 83

3 Answers3

1

For making code more simplified, readable & with great coding standard answer will be yes for both to improve your javascript code & way you are getting a response from the Ajax call.

  1. Improve Javascript : You might have one common js included in you header portion, if not create & include one. This common jar contains only common functions throughout the application. Create one function with the name may be like sendAjaxRequest() in that common.js. This function will have some parameters like divId (refresh div id), url(post url), options(array of options) & function will look like this:

    function sendAjaxRequest(strDivId, strRequestUrl, options) {
         options = options || {};
         var defaultOptions = {url: strRequestUrl, type: 'POST', beforeSend: function(request,options){showLoadingImage(strDivId);}, success: function(html){$('#'+strDivId).html(html); removeLoadingImage(strDivId); }};
         options = $.extend({},defaultOptions,options);
         $.ajax(options);
    }
    

    Call this function from where ever required on application. like

    ('.user-data').click( function() { sendAjaxRequest('somediv', url,{data: { id: this.id }}) });

    Benefit : This method is very useful in the future when you want to keep google analytics on ajax call also or want to track your ajax calls. It is always good to have common functions.

  2. Resposnse from ajax call: You can load views in Controller->function in case of ajax call also, nothing need to change or configure for this. Use of this way is always good practice to maintain standardness & readablity in the code.

Note : Here in this case you might worry about using a second action on load of your first Ajax call, for this standard way is to write second action on load of view of that particular Ajax call view (Write second click code in that particular view only)
like

('.someclass').click( function() { sendAjaxRequest('someOtherDiv', otherUrl,{data: { id: this.id }}) });


In short at the end user divide & conquer rule (Divide an html page into blocks & create the huge page) to create good applications. Its really fantastic way, as I am using this way in my codings overall.

Ramesh Mhetre
  • 404
  • 2
  • 12
0

First Answer:

The ajax request seems fine, you can add dataType option also to expect particular type of response, As you are using post you can use jquery.post as an alternative

Example

$.post( "<?php echo base_url();?>index.php/user/get_user_content", function(data) {
  alert( "success" );
}, 'html') // here specify the datatype
.fail(function() {
  alert( "error" );
})

You can also use done callback instead of success

Second answer:

Controller

public function get_user_content() { 
    $id = $this->input->post('id');
    $hits = $this->user_model->user_data($id);
    $user_array = array();
    foreach ($hits as $hit) {
       $temp_array = array();
       $temp_array = array('name' => $hit->name);
       $temp_array = array('age' => $hit->age);  
       $user_array = array($temp_array);

    }
    $this->load->view('user', $user_array);
}

Modal

Remains the same

View (user.php)

example say user.php

<?php
echo "<div class='somediv'>";
if (sizeof($user_array)) {
  for ($row = 0; $row < sizeof($user_array); $row++ ) {
     echo "User Details: Name - " . $user_array[$row]['name'] . ", Age - " . $user_array[$row]['age']; 
     echo "<br/>";
  }      
} else { 
  <a href="#" id="23" class="user-data">Click here for user details</a>
} 
echo "</div>";
?>

Javascript

$('.user-data').on('click' function () {  // better to use event delegation as content is loaded dynamically
   get_user_data(); 
});

function get_user_data() {
    $.post( "<?php echo base_url();?>index.php/user/get_user_content", function(data) {
      alert( "success" );
      $("#somediv").append(data);
      $(".someclass").click(another_function);
    }, 'html') // here specify the datatype
    .fail(function() {
      alert( "error" );
    });
}

Reference

stackoverflow.com/questions/18471627/codeigniter-load-a-view-using-post-and-ajax

Community
  • 1
  • 1
Raunak Kathuria
  • 3,185
  • 1
  • 18
  • 27
0

1- There is other ways to do ajax calls , being better or not is based on your needs, This post clears this point

2- your way is good, still you could use some enhancements to your functions to be a complete web-services same as handling errors - in case - and to return the output data as json allowing you to control it from your JavaScript function for a better handling & representation.

3- from what i understood you're getting data for single user each time ,in this case using $query->row() would be make your life easier extracting the data than using $query->result() , but in case you are getting multiple records you could loop it withing your JavaScript function.

here's another approach to your example with little enhancements that might be helpful :

controller (user.php):

public function get_user_content($id) {
    $output -> hit = $this -> user_model -> user_data($id);
    if (!$output -> hit) {
        $output -> msg = "NORECORDS";
    } else {
        $output -> msg = "SUCCESS";
    }
    echo json_encode($output);
}

model(user_model.php):

function user_data($id) {
    //do sql operation
    return $query -> row();
}

JavaScript :

     function get_user_data(response) {
    $.get("<?php echo base_url();?>index.php/user/get_user_content/" + this.id, function(data) {
        if (data.msg != 'SUCCESS') {
            alert(data.msg);
            return;
        }
        var hit = data.hit;
        $("#somediv").append("Name: " + hit.name + "Age: " + hit.age);
        $(".someclass").click(another_function);
    }, "json");
}
Community
  • 1
  • 1
aemad
  • 111
  • 1
  • 9