January 30, 2012 jquery

Using jQuery and ajax with Codeigniter

Using jQuery and ajax with Codeigniter

In previous posts I have already written about how to get database information using jQuery, ajax and PHP. Today, I would like to integrate that same approach while using the codeigniter framework. Take a look at it here, if you haven’t read it yet.

To integrate jQuery with codeigniter, might sound a bit scary at first, but mind you, it’s not something out of this world. We will implement the same example from the previous jQuery post. We will use the same html page used in previous post of ajax jquery, and will only change how our PHP script will look, making it specific for codeigniter. Thus, making this post a bit vague for those that do not know how this works yet. Again, I recommend all that have not read my previous post, to do so.

The final resulting html page was:

Only one change needs to be done to this page, and it lies within the ajax call. Since we are using codeigniter, then we all know that the standard way of calling a function and a method is through the url and looks something like, the base_url / controller / function / additional parameters. In this particular example, we will create a new controller named profiles. Within the controller, we are going to have a function named: get_all_users(), so in this html page, we are going to change the ajax url parameter to this:

This should return something like this:

Or if you have removed the index.php then:

Now, instead of having that ‘getdata.php’ file, we will create the products controller file for this task we are going to run. It will basically do the same process, except in a ‘codeigniter’ kind of way. Let’s create it:

Note: for the sake of this tutorial, I will place my logic within the controller, but the best practices are to create your logic within a model.

File name: products.php

This logic is a bit simpler than the original post, but it’s just to get the idea on how to create an ajax, jquery connection using codeigniter. The html page should look something like this:

The basic idea is technically the same as when creating an interactive website with jquery and PHP. Only a few tweaks needed to be made in order for this to work within a codeigniter environment.

Hope you all enjoyed.

35 thoughts on “Using jQuery and ajax with Codeigniter

  1. Nice tutorial loco.

    There is a typo on your code example:
    “class Products extends CI_Cotnroller{” it should read “class Products extends CI_Controller{“… “Controller” is missed spelled 😉

  2. Por lo que pude entender este ejemplo me viene como anillo al dedo, pues en mi proyecto necesito algo así, solo con algunas variaciones.

    1- Necesito pasarle un parámetro al controlador(id) para limitar la búsqueda en base de datos, luego que este me devuelva solo el valor de un campo.

    ej. le paso id=5 y me devuelve el valor del campo nombre cuyo id sea 5.

    No se si mi ejemplo ilustra mi problema, podría ud. ayudarme?gracias de antemano.

      1. Gracias por responder.

        Entiendo lo que me dices, solo que olvidé referir que soy poco menos que un novato en ajax, por lo que, aunque en teoría entiendo, en la práctica no tengo idea. Le explico mi necesidad para que pueda ayudarme:
        Tengo un cuadro de lista con los productos al lado un input para introducir la cantidad a solicitar.
        necesito que al seleccionar un producto e introducir la cantidad se consulte la base de datos y en caso de la cantidad ser mayor emita una alerta, para ello necesito enviar el id del producto.
        gracias nuevamente por su atención

  3. Client side :

    function ajax_submit_gen ( form_selector, submitter, server_message )
    {

    /* Eli Orr 2/2012
    // form_selector – The input->post(‘items’) ;
    $a = explode(‘&’, $serialized_params );

    $i = 0;
    $params = array ();
    $status =’ parsing:’;

    while ($i found_errors ($found_errors);
    return 0;
    }

    return $params;

    }

  4. Hello! Your tutorial seems nice for beginners but please – do not mess controllers methods with model methods. All traffic on db side needs to be in your model, due to MVC.

    1. Indeed. Skinny controllers and fat models should be everyone’s way of thinking. For the sake of simplicity ( and tutorials ) though, I tend to do that sometimes.

  5. Just a small note on CI’s base_url() function, instead of using:
    base_url().’profiles/get_all_users’

    It’s better practice to use:
    base_url(‘profiles/get_all_users’)

    The base_url() function appends the parameter to the base URL it pulls from the config, then returns that. 🙂

  6. Qué pasa con esto?

    url: ”

    Si estoy usando un archivo .js externo para la consulta con AJAX?

    Se me ocurre formas de resolver esto, pero no quiero juntar la consulta AJAX en la vista mediante variables extra al fragmento footer. se me ocurre obtener base_ur mediante javascript. En fin, si me das tu opinión estaría agradecido.

  7. Hi your tutorial is simply awesome but one thing that i’ve noticed ? why do you have some data models in your controller? that’s a bad practice i think ? 😀 btw. keep it up bro! 😀

    1. Well, it’s actually for the sake of simplicity. I have noticed that many people ask about this, so from now on, I’m going to make a bit more comprehensive tutorials concerning the structures I talk about.

      Glad you liked it though.

  8. Hi,

    What changes should I make to submit form values. I tried the following code but it with no success. It is not passing the values to controller :-

    1. Hi Anita,

      Try this:

      With this, you should be able to access those variables with the followig:

      Hope this helps.

  9. JSON data is not appended to div element…its shown in the response from server in firebug but is not actually shown in the page…Can you point out the problem?

    1. got this solved myself! I had forgotten to delete the doctype,head etc at the top of one of my views…Thnx for the tutorial…

  10. When I use this code error occured ”
    A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: Products::$db

    Filename: controllers/Products.php

    Line Number: 9

    Fatal error: Call to a member function get() on a non-object in D:\xampp\htdocs\cirnd\application\controllers\Products.php on line 9″

    Please tell me , whats problem.

      1. when I am loading database class this error occured – “Fatal error: Cannot use object of type stdClass as array in D:\xampp\htdocs\cirnd\application\controllers\Products.php on line 18

        Please tell me how can run this programme.

    1. If you look at your controller you will have mistyped $this->db-> , You will have probably put _> instead of ->.

      I have had this issue before

  11. I think there is an error. Isn’t the controller supposed to be called “Profiles” instead of “Products”? There are many places where you write “products” whereas the “get_all_users” method should be relevant to the “profiles”.

  12. Hi,
    I wanted to know one thing for clear from the code above. With or without a framework, will I be able to call a function / method within class? I have searched many forums (SO for example) and I have come across only one answer – it cannot be done. I even tried and all I got was a 404 error. Amazingly, there are lot of answers for ASP .NET while calling a method using $.ajax. Why not for PHP ? I have see many plugins (if you can call it so) like phery.js but somehow I am not convinced. Also the piece of code in your example is within the view. I prefer to have my js code as external and include it at the bottom on the view. Now will the $.ajax call in your example work if it is in an external js file.?

    Thanks,
    Girish

  13. $output_string .= ‘{$row[‘value’]}\n’;

    tengo problema en el foreach al parecer no me recoge los datos de la base de datos:

    dentro de la columna CodigoProducto me sale esto en el navegador{$prods[“IdProducto”]}

Leave a Reply

Your email address will not be published. Required fields are marked *

The qTranslate Editor has disabled itself because it hasn't been tested with your Wordpress version yet. This is done to prevent Wordpress from malfunctioning. You can reenable it by clicking here (may cause data loss! Use at own risk!). To remove this message permanently, please update qTranslate to the corresponding version.