Try Tuts+ Premium, Get Cash Back!
CodeIgniter from Scratch Day 8: AJAX
videos

CodeIgniter from Scratch: Day 8 – AJAX

This entry is part 8 of 17 in the CodeIgniter From Scratch Session
« PreviousNext »

The CodeIgniter from Scratch series was unexpectedly, and significantly popular. Today, I’m pleased to announce that, with the help of one of my best authors, Burak, we’ll be continuing the series! Additionally, the most often requested topic is the subject for today’s screencast: combining CodeIgniter and jQuery.

Remember, it is not required that you watch the previous lessons in order to understand today’s screencast. It’s a self-contained article. However, if you’re new to CodeIgniter, we do recommend that you start from the beginning!

Catch Up

Day 8: AJAX

Other Viewing Options

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.k-design.ro Ionut Bucur

    I have the impression that Wampserver run slower on win7 than xp…. (on my pc too)….

    Thanks and keep up the good work!!!

    :)

    (greetings from Romania too!!!)

    • Yusuf

      @lonut Bucur

      delete the line “::1 localhost” in “c:/windows/system32/drivers/etc/hosts”. it should make speed up.

      @Burak
      güzel olmuş teşekkürler.

      • Branimir

        … or switch to ubuntu (linux) like me :)

  • Ertac

    Bir suredir bu seriyi takip ediyordum. Jeff’in sesine alismistik ki bugun Burak’i gorunce biraz sasirdim. :)

    Guzel video tesekkurler Burak ..

    Thanks for the nice tutorial. keep the good work.

  • Robert

    A great addition to these tutorials – please keep them coming.

    Also a few comments on future ‘days’.

    - Stick to the rehearsed content – don’t make it up as you go along

    - Delivery is a little monotone – spice it up a little

    - Do any ‘cleanup’ work up front, and just comment that “I had to do X, Y and Z to the original code because….”

    - Don’t move quite so fast, and explain what you’re doing as you go along. This is one area Jeffrey really excels at, but there’s no harm in copying something that works.

    Well done.

    Rob.

    • Philip

      Actually I found his process of cleaning up informative.
      As a newbie I get as much out of witnessing the pros thinking process as I do seeing the new code itself – even during mistakes or debugging.

      • http://passivetools4u.com/wbwso.php Selby

        I agree. Sort of seeing the strategy of finding errors is just as beneficial as the actual tutorial.

  • OcdCoder

    Burak,
    Your password field you had as a variable character (VARCHAR) 32, you could change it to just CHAR(32) for a performance increase. This is because, as you stated, a password will always be 32 characters and hence, not variable. Other than that, good tutorial!

  • Khalil

    I am looking for Codeigniter + jQuery (Ajax based) Pagination. Please post a screencast.

    Thankyou

    • http://www.code.my devlim

      u may want to use this library -> http://github.com/neotohin/CodeIgniter-Ajax-pagination-Library,

      and if u want to remove, “show total [num] of [num]” and add effect such as fadeIn when the user click the pagination link, u need to remove one function and modify the ajax function in this library.

      cheer

  • murat

    i found this tut little weak , after i watched video i realized that i spend almost 20 min just to begin ajax.
    maybe it is good for first time coder, other than that better than nothing.

  • nuki

    Good tutorial but:

    Stop the mouse!!!!!

    • http://www.phpandstuff.com Burak
      Author

      My right hand really seems hyper-active. I noticed after watching my own videos.

      • http://www.ariona.net Rian Ariona

        yeah.. stop you mouse movement.. it’s really disturbing. by the way nice screencast.

  • http://w3mentor.com/learn/category/php/codeigniter/ Murari

    I like this video..

  • egander

    Hi there – NiceTut on ajx tech and ci….

    By the way … Is there any chance of expecting a tutorial on CI, about the differnet linking problems, when uploaded to our own server site ????

    There arent any problemswith mamp – but when it hits my server – it doesnt work for me ….. with the linking part…

    So – am I the only experiencing these problems…. ????

    Please help me out – … a good video tut on the issue… please…

    Best regards…

  • DKline

    Erm…. 1 word…. “Kohana”. Stop wasting your time with CI.

    • Zwammer

      2 words: nonexistent documentation. The reason why CodeIgniter is so popular, is because of the large community and thorough documentation…

    • Korky

      Absolutely the documentation for Kohana is extremely weak and thin. Also, I found the community not very helpful, as opposed to a huge, very helpful one in CI (and Cake also).

  • http://www.dalibor-sojic.info Dalibor Sojic

    This is my way submitting form:

    $(‘#anyForm’).submit(function() { // on form submit
    var data = $(this).serialize(); // serialize form fields
    $.post($(this).attr(‘action’), data, function(reponse) { // post to “action”
    // do whatever with response
    });
    return false;
    });

  • http://twitter.com/tomasdev Tom

    I’m bothering you :p (you told that we can make suggestions here)

    Instead of appending the template to a div, you could use the .find() jQuery method to look what is returned by AJAX inside the element you care about (this case, the contact_form), so you replace it like:

    (inside success case ajax)

    var new_txt = msg.find(“#contact_form”).html();
    $(“#contact_form”).html(new_txt);

    That’s it!
    $(“#me”).love(jQuery());

  • Sven van de Berg

    Why using codeigniter, kohanaphp looks allot better. It’s OOP and has allot more functions than CodeIgniter.

  • http://gravityfx.org/ emcgfx
  • http://www.mesmerlab.com Jason

    ug… 4th time I’ve tried to watch this screencast…. I’d really like to know where to start if we’ve done the previous 7 screencasts. I don’t need to know how to set up the database, etc.

    • furytheory

      He shows you how to build the database using phpmyadmin, but if you need the hard code for upload to phpmyadmin or terminal, here you go:

      CREATE DATABASE ci_series;
      USE ci_series;
      CREATE TABLE membership (
      id INT(11) NOT NULL auto_increment,
      first_name VARCHAR(50) NOT NULL,
      last_name VARCHAR(50) NOT NULL,
      username VARCHAR(50) NOT NULL,
      password VARCHAR(32) NOT NULL,
      email_address VARCHAR(100) NOT NULL,
      PRIMARY KEY(id)
      );
      INSERT INTO membership VALUES(’1′, ‘insert_f_name_here’, ‘insert_l_name_here’, ‘insert_username_here’, md5(‘insert_password_here’), ‘insert_email_address_here’);

      Hope this helps.

  • http://www.acknexturk.com Quadraxas

    Süper, ağzına sağlık!

    Thanks for the great episode, keep the series up!

  • http://www.night40.com Mr-H

    thanks, sems to be intersent

  • Elanio

    Great tutorial.

    I do have a request or an issue with this. While everything works great, the end user on submit is left wondering if their e-mail was submitted.. How can you incorporate a ‘loading.gif’ to show that the form is working and processing your e-mail before loading in the successful view?

    • soma

      @elanio, you can use the ajaxStart(), ajaxStop() methods of jQuery to globally show a ajax loader animation.

  • http://www.jobsriver.com Hari @ Khin Maung Zaw

    Hi Burak, thanks a lot for these series…

    But I only confuse what is mean

    “It’s a good framework for beginners, well documented and has a big community. But I somewhat agree that it is not future-proof.”

    I just start to build CI apps. But I still confuse over what should I use WordPress or CI.

    BTW thanks and “Mingalarbar” Greeting from Myanmar….

    • Zwammer

      CodeIgniter still uses PHP4. Since more and more people are migrating to and writing their code in PHP5, PHP4 will become obsolete over the next few years…

      Cheers

      • Zwammer

        However, CodeIgniter 2.0 is built using PHP5. So there you go. Use CodeIgniter ;)

        I think it’s hard to compare CI to WordPress, as they are to different things. WordPress is a CMS/Blog tool and CI is a framework. Obviously, with CI you are free to build your software however you want since it is merely a framework. You still have to think about the approach you’re going to take to build a webapp. In WordPress’ case, you already have a full app and you have to modify it to suit your needs.

        So the choice is purely based on your needs. Do you want something highly customizable and flexible, go for CI. Do you want to quickly set up a site which does not need a lot of customization? Choose WordPress…

      • Korky Kathman

        So that no one will read Zwammer’s post and get the wrong idea, CodeIgniter (the most recent two version) now supports PHP5 with no problems. OOP is strong and it shouldn’t interfere with any coding you are now implementing.

  • jeff

    seriously – bud… we’re on day 8… you shouldn’t have to tell us about WAMP. if people don’t know about localhost then you should be refering them to something other than codeigniter. but you shouldn’t be trying to bring them up to speed.
    STOP! going over everything from every other video in this series. if people can’t drop in and figure it out, then let them come through the series — everytime i watch one of these the first 5-12 minutes is utter bull. and your video doesn’t allow fast-forward on all browsers (aparently)

  • Iván T.

    35 minutes just for that.. :/

    Maybe if you stop stuttering you could reduce it by half..

    Really, you make me nervous.

  • http://idonthave.com Peter

    go to the point! please

  • http://www.code.my devlim

    Good tutorial, but ur sound little bit not clear and this make me need increase my speaker volume and ur breath is too heavy that make the sound more unclear and little bit sleepy.
    btw, it does teach what the tittle of this post about.

  • Charles

    I really liked this tutorial, very quick and easy to setup. I did extend my personal version to submit to the database, with validation so I thought I should incorporate sending this back in json format which was really very easy to do.

    I just send back an array with true or false and the html to display whether it is error messages or success and then let jquery handle the response to show the error messages or thank you note.

  • Korky

    Wow there are a lot of critical comments here. Mostly, it seems to plug other products that aren’t nearly as good and some criticizing everything from mouse movement to speech to breathing. Are you kidding me?

    Get a life people! This is FREE education. Or maybe you’d rather go somewhere and pay for it? If so, please do. Otherwise, keep your mouth shut and be thankful.

    Burak, thank you for your tutorial! Don’t let a few ungrateful souls, deter you!

    • andresxv

      couldn’t agree more

      • Kars

        Indeed! I’m glas this is provided.

  • Loner

    Creating arrays and objects 101:

    var array = [];
    var o = {}

    Please know the difference.

  • http://www.saheltech.com Web Design SF Bay Area

    Great tutorial. I have been using CodeIgnitor for quite some time now and found this MVC framework very easy to learn and implement. Adding ajax via jQuery is another great thing to add to my skillset.

  • maramot

    The tutorial named deceptively. AJAX stands for “Asynchronous JavaScript and XML”. This tutorial does not demonstrate the retrieving of data from xml or from a database, something I actually do need a tutorial for. In 34 minutes all we see is how to validate a form with javascript and use basic jquery syntax. The use of the Codeigniter framework is completely irrelevant to this exercise.

    • Jeffrey

      I’m with you, the validation of CI is better than the video

  • neerose

    can any point where i can get the database for this example???

  • Kars

    Didn’t Jeffrey promise to cover the scaffolding part, and asked us if he forgot, that we should tell? I haven’t seen it covered yet. Maybe in the upcoming tuts. Am still busy with these tuts.

  • http://www.buzzednow.com Buzzednow

    I’ve already made a website based on the whole CI tut, except for the ajax part. Thanks

  • http://www.web-design-talk.co.uk Rob

    Why are you creating an array of form data when you can use the serialize function:

    $(‘form#some_form’).submit(function() {
    var data = $(this).serialize();

    return false;
    });

    PErsonally, of all the tutorials so far, that was the worse. Kinda seemed like you were making it up as went along – not planned too much.

    • http://www.digital-results.com Frank Martin

      By using the serialize function you can’t check if the form is being sent via AJAX, which you’d need to cater for users who aren’t using javascript. You could append an input using jQuery but that would be lame. I think using an array works well.

  • Korky Kathman

    I think this was a great lesson, and I even liked the afterthoughts that you made, because they are a lot like things I do. That’s realistic and helpful, I think.

    I am having a problem, in that when I set up the ajax in the contact_form.php, I type that in exactly the way you do, and yet, I get absolutely NO msg returned off the “success” parameter. I guess, what I’m trying to understand is how is that “success” determined? It’s clear that I’m getting no call-back function, so I’m assuming it failed somehow. The result is that I never get an alert message and it goes straight to the Thank You screen.

    Did anyone else have this issue? If so, how did you reconcile it?

    Thanks.

    • Korky Kathman

      Ah never mind, I was referring to the wrong controller and function. UGH! Silly me.

  • ido

    what’s wrong with chapters 6&7? i can’t see them at all could you please upload them as the rest of the files?

  • Shaz

    Ok so I’ve went to look at some jQuery after failing to get a clue from the first time I watched this. Gonna watch it again and hopefully, it’ll be much much better.

  • John Burchell

    I’ve watched this whole series a couple of times and I learn more each time I look at it. This one is particularly helpful, in that, it shows two different coding styles and gives you a couple of things to look for when things don’t line up right. Because it was a bit more relaxed, I had the impression I was getting a personal tutorial just by watching the activities of a normal work project.

    Good Job!

  • haily_php

    With your way, I have done well to show data from second select box through first select-box; but i have one problem. First, if i chosen the first value, ( in second select-box) program would have not run; it would run from other values. Then, I chosen first value again, it run normally
    How will I do to get the first value and to show data in second select-box automatically when I’ll run program first.

    — controllers–

    <option value="”>

    $(‘#sub2_mainmenu’).change(function() {

    var form_data = {
    sub2_mainmenu: $(“#sub2_mainmenu”).val(),
    };

    $.ajax({
    url: “”,
    type: ‘POST’,
    data: form_data,
    success: function(msg) {
    $(‘#submenu’).html(msg);
    }
    });
    });

    submenu: the place that I want to show data in second select-box

  • http://www.mediafirehunt.com/ mediafirehunt

    nice tutorial………

  • http://pabxpromo.com pabx panasonic

    very nice thanks :)

  • jcho360

    THANKS! IT HELP ME A LOT

  • Scully

    Thanks Burak.

    Is there a way to do this with AJAX while still utilizing CI’s form validation tools?

  • http://dsgn1graphics.com dsgn1graphics

    Really nice, thank you for the video…

    Q:
    I’m trying to Ajax from a .js file loaded into my head tag. Say its called default.js for example, and all of my scripts and functions are in there. Since my request isn’t coming from a view php fil, how do I create the proper url so I can pass that information to my controller. My js folder is on the root, along with my css folder and images etc., not inside of the application directory.

  • nharry

    YAWN! Reminds me slightly of those lengthy war stories my granddad used to tell.

  • http://blog.jstoutenburg.com jehoshua02

    NOTE: Form validation with Javascript is only an enhancement, not a replacement for server side validation!
    Client side code can be manipulated to bypass validation, allowing invalid data to be submitted to the server.
    Validation should always be done on the server side. Client side validation is an optional enhancement.

    I would have thought that a good subject for AJAX would have been a continuation of the pagination tutorial. Or at least show how you can have multiple things on one page and interact with one without affecting the others.

  • Aleš Vaupotič

    Just remember to include your CSRF token in CI2 if you’re using one:

    var form_data = {
    csrf_token: $(‘input[name*="csrf_token"]‘).val(),
    first_name : $(‘#first_name’).val(),
    last_name : $(‘#last_name’).val(),
    ajax: ’1′
    };

    It should be identified by name rather than ID as CI2 creates an input without ID.

    Great series, BTW!

  • MIchael

    Amazing that it takes 4 minutes before the tute starts!

  • Matanya

    Great tut!
    Notice though that the name validation you performed doesn’t require ajax, as it can normally be done on the client-side before submitting the form. IMHO, A better example would be accessing a database to see if a username is already taken.

  • mark

    Your code does not seem to work for me. It does not catch the submit button. I have exactly the same code but with CI_Controller. What is the issue? newest version of CI and JQ.

    • Derek

      I had the same problem. What caused it for me was not putting a period in front of the the word ajax e.i. “$.ajax({ url: …”. I was incredibly frustrated as well. I’m using the newest CI and JQ also. Hope that helps.

  • http://960Creative.com Niyi

    I followed the tutorial exactly and it works fine. But I decided to place the ajax in an external file js/script.js the same way that’s done for the css file. When I do this the ajax call does not load the php in the ‘url’ parameter instead it reads it like a string.

    /www2/index.php/%3C?php%20echo%20site_url(%27contact/submit%27);%20?%3E”

    File path:
    /application
    /www2/system
    /www2/css
    /www2/js
    /www2/js/script.js

    I’ve tried changing to different paths but nothing works. Only when I hard code the url (copy/paste from my browser) it works fine.

    Is there a reason that it’s not reading the php?

    Thanks

    • http://960creative.com Niyi

      I see what I did there. I am using version 2.1 while the first tut in the series was and earlier version. When Jeff took the application folder out of the system folder, I did the “same” too. But didn’t realize that version 2.1 already comes with the application folder on the outside. So basically what I did was just move it out of the root folder.

      Then again, I’ve been using that method for all the other tuts (even after day 8) and they work fine, Just the ajax ain’t working. So yea, I still need help with that.

  • Andrea

    Great tutorial, very clear and well-explained. Thanks Burak