Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax driven content using CodeIgniter

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.

like image 601
xan Avatar asked Dec 18 '13 23:12

xan


People also ask

How to use Ajax in Codeigniter 4 with gravitas?

With gravitas, we will create views and load all the data inside the view and display on the user screen using AJAX in Codeigniter 4. You must have a composer package installed on your device to install the Codeigniter application. After installing the app, change the name of the folder such as codeigniter-ajax-crud.

How to display user records in CodeIgniter view using Ajax?

Create a model and manifest a function that fetches all the user records from the database that we will show later using AJAX in the Codeigniter view. Create app/Models/UserModel.php file and place the following code.

What is the contenteditable attribute in HTML5?

The contenteditable attribute is one of the new most helpful addition in HTML5. Today we are utilising the contenteditable attribute in HTML5 to build a simple ajax driven editable table in CodeIgniter.

Is it necessary to make explicit the sending of Ajax header?

For libraries like jQuery for example, it is not necessary to make explicit the sending of this header, because according to the official documentation it is a standard header for all requests $.ajax (). But if you still want to force the shipment to not take risks, just do it as follows:


1 Answers

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.

like image 194
Ramesh Mhetre Avatar answered Oct 29 '22 05:10

Ramesh Mhetre