Ajax Content Using CodeIgniter

I am creating a website, which is a one-page website that interacts with the server via Ajax in CodeIgniter. 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 specific html content is updated via Ajax .

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

 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 do not know about any open source projects that could simplify / optimize.

+7
javascript jquery ajax php codeigniter
source share
3 answers

To simplify the code, readable and with an excellent standard coding response will be yes to improve javascript code and the way to get the response from an Ajax call.

  • Improve Javascript : You can have one generic js included in the header part if you don't create and include it. This common jar contains only common functions throughout the application. Creating a single function with the name can be like sendAjaxRequest () in common.js . This function will have some parameters, such as divId (update div id), url (post url), parameters (array of parameters), and the 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 it is required in the application. as

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

    Advantage . This method is very useful in the future when you want google analytics on an ajax call to also track your ajax calls. It is always good to have common features.

  • Resposnse from ajax call: You can load views into the Controller-> function in the case of ajax call, and nothing needs to be changed or configured for this. Using this method is always good practice to maintain the standard and readability of the code.

Note. Here in this case, you can worry about using the second action when loading your first Ajax call, since this standard way is to record the second action when loading the view of this particular kind of Ajax call (write the second click code into this specific view)
as

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


In short, the final user rule is to divide and conquer (divide the html page into blocks and create a huge page) to create good applications. This is really a fantastic way, since I use this method in my encodings in general.

+1
source share

First answer:

The ajax request seems fine, you can add the dataType parameter also to expect a certain type of response, Since you are using a message, 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 the executed 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: 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" ); }); } 

Link

stack overflow

0
source share

1 There are other ways to make ajax calls, better or not, based on your needs, This message clears this point

2 Your path is good, yet you can use some improvements for your functions to be full-fledged web services, the same as processing errors - in case - and return output as json, allowing you to manage it from your JavaScript function for better handling and performance.

3- from what I understand, each time you get data for one user, in this case using $query->row() will make it easier to extract data than using $query->result() , but if you get several records you can loop through your javascript function.

here is another approach to your example with minor improvements that may be useful:

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"); } 
0
source share

All Articles