A basic AJAX call in Codeigniter

I am encountering some challenges with ajax and codeigniter. Despite posting a previous question (link to question) and thinking I had resolved it, I am still facing issues. I am seeking assistance in creating simple code using ajax/codeigniter to increment a number inside a div/span upon clicking.

For the past few days, I have been attempting to achieve this, but I keep running into errors. My CodeIgniter settings are as follows:
base_url: localhost/test/
index: index.php
autoload: url
default controller: welcome (left unchanged for testing purposes)

I would greatly appreciate a straightforward example to implement this. I have tried again, but unfortunately, have not succeeded. Here is what I attempted this time:

Controller (welcome.php)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {


function __construct()
    {
        parent::__construct();
    }

public function index()
{
    $this->load->view('welcome_message');
}

function increase(){
    $increase = $this->input->post('increase');
    echo increase++;
}
}

JS (Ajax)

function increase(){
var number = parseInt($('#number').html()) + 1;
$.ajax({
        type: 'POST',
        url: 'localhost/test/welcome/increase',
        data: { increase:number },
        success:function(response){
            $('#number').html(response);
        }
});

}

View (HTML/CSS)

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript"></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery_v1.9.1.js"> </script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/script.js">            </script>
<style type="text/css">
#number {
display: block;
text-align: center;
width: 100px;
height: 30px;
margin: auto auto;
line-height: 30px;
border: 1px solid #999999;
border-radius: 5px;
}

</style>
</head>
<body>
    <span id="number" onclick="increase()">0</span>
</body>
</html>

I am using the latest xampp on windows 7. The error I encounter when clicking on the span is:

POST http://localhost/test/localhost/test/welcome/increase 404 (Not Found)

Answer №1

Ensure that the CSRF token from cookies is included in the submission to avoid invalidating the request, especially if CSRF is activated in config.php.

If you need to retrieve cookies in JavaScript, you can utilize this plugin and pass it to CI accordingly.

ci_token

and

ci_cookie

keys may have distinct names and can be located in config.php.

Setting up a route for the request and utilizing

site_url()

is recommended instead of

base_url()

var SITE = "<?php echo site_url();?>" // This global variable allows your JavaScript files to be external

-

var data = { 'ci_token' : $.cookies.get('ci_cookie'), 'increase' : parseInt(number)}
$.ajax({
    url : SITE + "/link/to/controller/method",
    data : data,
});

Answer №2

Utilize the site_url() function in CodeIgniter

 function increase(){
   var number = parseInt($('#number').html()) + 1;  
   $.ajax({
     type: 'POST',
     url: '<?php echo site_url("welcome/increase")?>',
     data: { increse:number }, //<--- here should be increase
     success:function(response){
        $('#number').html(response);
     }
  });

}

On the other hand, if you add http:// before localhost, it should function as well

 url: 'http://localhost/test/welcome/increase',

Nevertheless, it is always best practice and highly recommended to use site_url() when calling a controller in CI. This helps to prevent errors when the code is transferred to a live server.

Answer №3

When working with ajax, it is recommended to avoid using external links for your JavaScript and stick to internal links instead.

Remember to configure your $config['base_url'] to http://localhost/test/ in the config.php file.

function increment(){
    var number = parseInt($('#number').html()) + 1;
    $.ajax({
        type: 'POST',
        url: '<?php echo base_url()?>welcome/increase',
        data: { increment:number },
        success:function(response){
           $('#number').html(response);
        }
   });

}

Answer №4

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript"></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery_v1.9.1.js"> </script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/script.js">            </script>
<style type="text/css">
  #number {
    display: block;
    text-align: center;
    width: 100px;
    height: 30px;
    margin: auto auto;
    line-height: 30px;
    border: 1px solid #999999;
    border-radius: 5px;
  }

</style>
</head>
<script>
function increase(){
  var number = parseInt($('#number').html()) + 1;
  $.ajax({
      type: 'POST',
      url: '<?php echo base_url()?>welcome/increase',
      data: { increase:number },
      success:function(response){
         $('#number').html(response);
      }
  });

}
</script>
<body>
<span id="number" onclick="increase()">0</span>
</body>
</html>

Answer №5

To start, it's important to establish the site base_url in the application/config file and then utilize this base_url when making ajax calls in your code. Assuming that your base_url is http://localhost/test/.

function updateCount(){
   var count = parseInt($('#count').html()) + 1;
   $.post('<?php echo base_url()?>welcome/updateCount',{count :count},function(response){
          $('#count').html(response);
   });    
}

Next, update the updateCount function in your controller like this:

function updateCount(){
   $newCount = $_POST['count'];
   echo ++$newCount;
}

}

Answer №6

give this a shot:

function increment(){
        var value = parseInt($('#value').html()) + 1;
        $.ajax({
            type: 'POST',
            url: 'localhost/test/Welcome/increment/',
            data: "increment=" + value,
            dataType: "text",
            success:function(result){
                $('#value').html(result);
            }
        });

 }

Answer №7

If you're utilizing this ajax code in a .php file, you should make sure to adjust your URL like this:

function increase(){
var number = parseInt($('#number').html()) + 1;
var base_url = "<?php echo base_url();?>";
$.ajax({
    type: 'POST',
    url: base_url+'welcome/increase',
    data: { increase:number },
    success:function(response){
        $('#number').html(response);
    }
  });
}

Alternatively, if you're working in a .js file, you'll need to insert this line within the head tag:

<script> var base_url = "<?php echo base_url();?>";</script>

Then, you can use the following:

function increase(){
var number = parseInt($('#number').html()) + 1;
$.ajax({
    type: 'POST',
    url: base_url+'welcome/increase',
    data: { increase:number },
    success:function(response){
        $('#number').html(response);
    }
  });
}

Hopefully, this addresses the issue. It's advisable to set the base_url in config.php when working in a local environment like so:

$root = "http://".$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url']    = $root;

Answer №8

Explore::::::    
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="<?php echo base_url();?>css/jquery.js"> </script>
<style type="text/css">
#number {
display: block;
text-align: center;
width: 100px;
height: 30px;
margin: 50px auto;
line-height: 30px;
border: 1px solid #999;
border-radius: 5px;
}
body{
cursor: default;
}
</style>
</head>
<script>
function increment(){
var number = parseInt($('#number').html());
$.ajax({
  type: 'POST',
  url: '<?php echo base_url()?>main/samp_data',
  data: { increment:number },
  success:function(response){
     $('#number').html(response);
  }
  });
 }
</script>
<body>
<span id="number" onclick="increment()">0</span>
</body>
</html>




Controller::::::
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

    public function index(){
        $this -> load -> view('sample_view');
    }

    public function samp_data(){
        $increment = $this->input->post('increment');
        echo ++$increment;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving values from multiple Select components in Material-UI is key

I have encountered an issue with my two MUI Select components on the page. I am attempting to set values based on the id of the Select component. Initially, when I check (id === "breed-select") in the console, it returns true, but shortly after ...

Combining user input data using JavaScript and Vue.js

I am working on a form using Vue.js and I want to combine the data from the input fields upon submission. I have been struggling to achieve this and created a jsfiddle to showcase my attempt. In my form, I have three Vue components for each of the input f ...

Backend server encountered an issue with processing punycode

[ALERT] 18:13:52 Server Restarting Prompt: C:\Code\MERN_Projects\podify_app\server\src\db\index.ts has been altered (node:22692) [DEP0040] DeprecationWarning: The punycode module is outdated. Consider utilizing a modern a ...

What is the process for loading an HTML form into a specific target using Angular?

Is there a way to load an HTML form into a target in Angular without the use of jQuery? I have a working script, but I am currently stuck on: <html> <head> <script src="components/angular/angular.js"></script> <script&g ...

Adding JSON data to a table with the keys in the first row is a simple process that can be achieved

Previously, I have created tables with XML formatted results and JSON data in the "key: data" format. To access the data, I would use syntax like results.heading1 and then map the data into a table by matching the key with the data. Now, a new client is o ...

Add a specific CSS class to a div element depending on the status of a checkbox

Is there a way to dynamically append data based on the selected items in a checkbox table? I want to be able to add multiple or single items by clicking the add button. The key is to avoid appending duplicate data that already exists in the view. Any sugge ...

Automatic button rotation

I managed to set up a button that works on click with a delay, making it semi-automatic. However, I'm struggling with getting it to not pause after just one click. Here's what I have so far: <!DOCTYPE html> <html> <body> &l ...

Does anyone know of a way to integrate a calendar feature into a React application using a library

Greetings to everyone, I trust you are all enjoying a fantastic day. I am in search of an interactive calendar similar to this one for one of my applications https://i.sstatic.net/D3S3a.png Does anyone know of a React library that could assist me in crea ...

What is the proper way to utilize setTimeout in TypeScript?

Let's take a look at an example of how to use setTimeout in Angular and TypeScript: let timer: number = setTimeout(() => { }, 2000); However, upon compilation, you may encounter the following error message: Error TS2322: Type 'Timeout' ...

The functionality of removing a class on the body element is ineffective when using pagepiling.js

After creating a website using pagepiling.js, I implemented a script that adds the 'active' class to the section currently in view. My goal was to add a specific class to the body when my section1 is considered active. Here's the initial app ...

Resolving "Module not found: Error: Can't resolve 'url'" issue in Angular 14 while invoking web3 smart contract function

How do I resolve the web3-related errors in my Angular 14 dapp? I attempted to fix the issue by running npm i crypto, npm i http, and more. Every time I try to call a function from a smart contract with code like this.manager = await report.methods.mana ...

Enhance state using the values from radio buttons in a React application

Seeking the best approach to update or set my state that stores values for radio button answers. This pertains to a personality test with 20 questions, and I aim to store all 20 answers. Each radio button input has an onChange event. My objective is to st ...

Using THREE.js to incorporate a stroke above extruded text

Looking to enhance text with a horizontal line above it: var geo = new THREE.TextGeometry("x", geometry_options); var mat = new THREE.MeshBasicMaterial({color: 0, side:THREE.DoubleSide}); geo.computeBoundingBox (); var vec = new THREE.Shape(); vec.moveTo( ...

Tips for displaying real-time error notifications from server-side validation using AJAX

Seeking a way to display inline error messages from my Symfony2 Backend without refreshing the page. I considered replacing the current form in the HTML with the validated form containing the error messages returned by the backend through AJAX. However, ...

Ionic (Angular) experiencing crashes due to numerous HTTP requests being made

My template contains a list of items <ion-list class="ion-text-center"> <div *ngIf="farms$ | async as farmData"> <ion-item (click)="selectFarm(farm)" *ngFor="let farm of farmData" detail=&quo ...

Enhance user experience with real-time form validation in Bootstrap 4 as the user inputs

In order to troubleshoot my issue, I created a simple index.php file with 2 input fields and a button that redirects to page2.php. These input tags have a regex pattern for Bootstrap-4 form validation. Issue 1: The validation only occurs after clicking ...

Exploring an array using bluebird promises

I am currently facing an issue where I need to iterate over an array containing promises. My goal is to multiply all the values in the array by 2 and then return the updated array: var Bluebird = Promise.noConflict(); var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9 ...

There seems to be an issue with the functionality of chrome.storage.local.set()

Struggling with Chrome storage handling, I have reviewed the newest documentation for Chrome storage and implemented the following code snippet (found within an AJAX call success function, where info.userName is a value fetched from my backend program): ch ...

Only a select few expandable elements in the jQuery accordion

How can I create an accordion menu with only a few expandable options? I am looking to include the following items in my menu: Home, Support, Sales, Other The "Home" option is just a link without any sub-menu. Clicking on it should direct users to a spec ...

Leveraging highland.js for sequentially executing asynchronous functions while maintaining references to the initial stream data

I am dealing with a series of events: var eventStream = _([{ id: 1, foo: 'bar' }, { id: 2, foo: 'baz' }]); My task is to load an instance of a model for each event in the stream (my Data Access Layer returns promises) and then tri ...