Learning how to use AJAX with CodeIgniter

Asked
Active3 hr before
Viewed126 times

5 Answers

90%

Fetch Records from Database with AJAX,Facilitate Codeigniter Errors,Install Codeigniter 4, Codeigniter 4 Google Column Charts Integration Tutorial

You must have a composer package installed on your device to install the Codeigniter application.

composer create - project codeigniter4 / appstarter

Next, get inside the app folder:

cd codeigniter - ajax - crud
load more v
88%

Quitting before the start date: is the non compete enforceable? ,I've also found in CodeIgniter that 'XMLHTTPRequest' isn't returned in the response headers, when using the standard Javascript AJAX call as mentioned above. ,Connect and share knowledge within a single location that is structured and easy to search., Why do some planets in Star Trek have a numeric designation while others have just a name?

you would just print it out basically, and re-capture that information via javascript:

public
function test() {
   $somenumber = $this - > input - > post('someNumber');
   if ($somenumber == 12) {
      print "Number is 12";
   } else {
      print "Number is not 12";
   }
}

your javascript might look something like this:

var xhr;
xhr = new XMLHTTPRequest();
xhr.onreadystatechange = function() {
   if (xhr.readyState == 4) {
      // this is where the return information is
      alert('Status: ' + xhr.status + ' Response: ' + xhr.responseText);
   }
}

xhr.open('POST', '/front/test');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('someNumber=12');

here's a jQuery example of all the above:

var options = {
   'someNumber': 12
}

$.post('/front/test', options, function(data) {
   alert(data); // should print "Number is 12"
});
load more v
72%

CREATE TABLE crud(
   `id`
   int(11) NOT NULL,
   `first_name`
   varchar(30) NOT NULL,
   `last_name`
   varchar(30) NOT NULL,
   `email`
   varchar(30) NOT NULL,
   PRIMARY KEY(id)
);
load more v
65%

With the help of an example you will learn how to post data to a controller using the CodeIgniter jQuery Ajax method.,So in this tutorial  we learned about how we can post data by jQuery Ajax in CodeIgniter. Keep reading our blog posts for getting in touch with more coding tricks.,great tuto , but how to get result back in case of checking from database and resturn a result ?, mazen mezlini says: April 17, 2015 at 10:46 am great tuto , but how to get result back in case of checking from database and resturn a result ? Reply

$.ajax({
   name: value,
   name: value,
   ...
})
load more v
75%

CodeIgniter 4 Upload Image using Ajax Method, Click here.,CodeIgniter 4 Upload Image using Ajax Method,Image Upload with Preview Using Ajax in CodeIgniter 4, Click here.,CodeIgniter 4 Image Upload with Form Tutorial

Here is the command to install via composer –

$ composer create - project codeigniter4 / appstarter codeigniter - 4

Open project in terminal

$ cp env.env

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create table with some columns.

CREATE TABLE `users`(
   `id`
   int(11) NOT NULL AUTO_INCREMENT,
   `name`
   varchar(120) DEFAULT NULL,
   `email`
   varchar(120) DEFAULT NULL,
   `mobile`
   varchar(45) DEFAULT NULL,
   PRIMARY KEY(`id`)
) ENGINE = InnoDB DEFAULT CHARSET = latin1;
 #-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 # DATABASE
 #-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
//...

$routes - > get("add-user", "UserController::addUser");
$routes - > post("save-user", "UserController::saveUser");

Open project into terminal and run this spark command to create model.

$ php spark make: model User--suffix
< ? php

namespace App\ Models;

use CodeIgniter\ Model;

class UserModel extends Model {
   protected $DBGroup = 'default';
   protected $table = 'users';
   protected $primaryKey = 'id';
   protected $useAutoIncrement = true;
   protected $insertID = 0;
   protected $returnType = 'array';
   protected $useSoftDelete = false;
   protected $protectFields = true;
   protected $allowedFields = [
      "name",
      "email",
      "mobile"
   ];

   // Dates
   protected $useTimestamps = false;
   protected $dateFormat = 'datetime';
   protected $createdField = 'created_at';
   protected $updatedField = 'updated_at';
   protected $deletedField = 'deleted_at';

   // Validation
   protected $validationRules = [];
   protected $validationMessages = [];
   protected $skipValidation = false;
   protected $cleanValidationRules = true;

   // Callbacks
   protected $allowCallbacks = true;
   protected $beforeInsert = [];
   protected $afterInsert = [];
   protected $beforeUpdate = [];
   protected $afterUpdate = [];
   protected $beforeFind = [];
   protected $afterFind = [];
   protected $beforeDelete = [];
   protected $afterDelete = [];
}

Open project into terminal and run this spark command to create controller.

$ php spark make: controller User--suffix
< ? php

namespace App\ Controllers;

use App\ Models\ UserModel;

class UserController extends BaseController {
   public
   function __construct() {
      helper(["url"]);
   }

   public
   function addUser() {
      // layout of add user form
      return view('add-user');
   }

   public
   function saveUser() {
      if ($this - > request - > getMethod() == "post") {

         $rules = [
            "name" => "required",
            "email" => "required|valid_email",
            "mobile" => "required"
         ];

         if (!$this - > validate($rules)) {

            $response = [
               'success' => false,
               'msg' => "There are some validation errors",
            ];

            return $this - > response - > setJSON($response);
         } else {

            $userModel = new UserModel();

            $data = [
               "name" => $this - > request - > getVar("name"),
               "email" => $this - > request - > getVar("email"),
               "mobile" => $this - > request - > getVar("mobile"),
            ];

            if ($userModel - > insert($data)) {

               $response = [
                  'success' => true,
                  'msg' => "User created",
               ];
            } else {
               $response = [
                  'success' => true,
                  'msg' => "Failed to create user",
               ];
            }

            return $this - > response - > setJSON($response);
         }
      }
   }
}

Start development server:

$ php spark serve
load more v

Other "undefined-undefined" queries related to "Learning how to use AJAX with CodeIgniter"