Using AJAX to submit a form to a CodeIgniter 3 controller

I am working on adding a notification feature and need to run an ajax query through the controller when a button is clicked.

Here's the script I'm using:

 $('#noti_Button').click(function (e) {
            e.preventDefault();
             $.ajax({
                url: '<?php echo site_url("profile/read_notif")?>'

            });
});

The Controller:

public function read_notif(){
        $this->profile_model->read_notifs($data['id']);
        return;
    }

And the Model:

function read_notifs($id)
    {
        $read = array(
            'read' => '1'
        );
        $this->db->where('recipient', $id);
        $this->db->update('tbl_notifications', $read);
        return;
    }

After trying this method, I noticed that the database wasn't being updated as expected. In my HTML, it's just a simple button.

Answer №1

Snippet

$('#notificationButton').on('click', function (event) {
        event.preventDefault();
         $.ajax({
            url: '<?php echo site_url("profile/read_notif")?>',
            success:function(response)
            {
                alert(response);
            }

        });
    });

Handler

public function read_notification(){
        $this->profile_model->mark_as_read($data['id']);
        echo $this->db->last_query();
    }

Answer №2

Implementing an AJAX call in Ruby on Rails can be achieved with this code snippet. Here, we are using the controller to fetch data based on user input.

$('#Button').on('change', function(event) {
  var selected_resource_id = $(this).val();
  $.ajax({ 
   type: 'GET', 
   url: "<%= Home_index_path %>",
   data: { id: selected_resource_id }, 
   success: function (data) {  
    alert("AJAX request successful");
   }
  });
});

Answer №3

Make sure to use the error function to verify if there are any errors when submitting your form.

$('#button').click(function (e) {
        e.preventDefault();
         $.ajax({
            url: '<?php echo site_url("profile/read_notif")?>',
            success:function(data)
            {
                alert(data);
            }

        });
    });

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

Steps for creating a node.js and ejs file to deploy on 000webhost

I have developed a simple todo-app using node.js and ejs templating. My goal is to host it using 000webhost, a free web-hosting service. I successfully hosted a react app for free on this platform by running "npm run build", which converted the ...

How to retrieve an array from a JSON object with JavaScript

After receiving an object from the server, I am specifically looking to extract the array ITEMS. How can I achieve this? I attempted using array['items'] but it did not yield the expected result and returned undefined { "items": [ { ...

communicating global variables between Django and JavaScript

I want to make variables from my settings.py accessible in all JavaScript code used throughout my project. What is the best way to accomplish this elegantly? Currently, I am considering two options: Create a context processor and define these globals ...

When you click on the column header to sort, the corresponding column row changes color in JavaScript

https://i.sstatic.net/4ELuv.jpg When a user clicks on a column to sort, the color of the column changes or highlights the row. In my tablesorter with ascending and descending sorting capabilities, I want the sorted column to change colors for better visib ...

Guide on utilizing getelementsbytagname for retrieving LI values

As I attempt to locate a specific product on amazon.com, my goal is to extract the ASIN for each item. This particular code snippet runs through various search options and retrieves the price of each product from Amazon one by one. However, in addition to ...

ExpressJS looping back

After exploring and practicing the creation of Rest APIs with both Loopback and ExpressJS individually, When using Loopback: I found it to be quite time-consuming to go through all the documentation and learn about loopback-specific features. However, i ...

Optimizing JavaScript for efficient handling of large arrays

I'm currently developing an image editing program using JavaScript to expand my knowledge of the language. The images I am working with are typically around 3000 x 4000 pixels in size, resulting in a total of 48,000,000 values to manage when convertin ...

Require assistance in getting a slider operational

Hello there! I could really use your assistance with this code. I have been trying to make it work using JavaScript, but I'm determined not to incorporate any external JS files. Here is the snippet of JavaScript code I am working with: "use strict"; ...

Passing entire database records from model to view in Codeigniter

Hi, I'm having trouble with my code and I can't figure out why it's not working. Here is the Controller: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Admin extends CI_Controller { ...

Arrays passed as query parameters to Next.js router.query may result in the value being

When trying to pass objects from an array to another page using router.query, individual objects like router.query.title work as expected. However, when attempting to pass arrays such as router.query.reviews, it returns something like reviews: ['&apos ...

Trouble with retrieving dates in ISO format

My collection stores the date of birth field in ISO format, for example: ISODate("1980-01-01T20:20:19.198Z") However, when I use a date time picker on my HTML page, it displays the date like this: 01/01/1980 Unfortunately, when querying for the date of ...

The issue lies with Express Mongoose failing to store the data

Encountering some issues when trying to save an object created in Express nodejs using mongoose. Despite receiving a confirmation that the object is saved, it cannot be located even after attempting to access it through the server. Express route for savi ...

Navigate to a different directory within Cypress by utilizing the cy.exec() function

Dealing with cypress to execute a python script in another directory. However, it seems like the directory change is not functioning as expected. visitPythonProject() { cy.exec("cd /Users/**/Desktop/project/"); cy.exec("ls"); // thi ...

Looking for assistance in establishing a connection between Node.js and Angular.js

I have a decent understanding of mongodb and node.js, but I'm struggling with angular.js. I need some help in figuring out how to retrieve data from my node.js code using angular.js. If there are any errors in my node.js code, please let me know. var ...

What steps can I take to ensure that my React child components will render successfully, even if a prop is absent

TLDR; Seeking solution to render child components in React even if a property of this.props is missing. My React app utilizes Yahoo's Fluxible and fetches data from a Wordpress site using WP REST API. Sometimes, the API may return incomplete data cau ...

Running JavaScript functions that make asynchronous calls to multiple endpoints simultaneously

Currently, I am working on implementing asynchronous endpoints using .NET C# to be called with JavaScript/AJAX. The main goal is to handle multiple requests (>2 at the same time) in separate threads, so that each user receives responses individually fro ...

Organize nested level components in react native into a more structured order

Currently, I am working with some JSON data that has the following structure: const data = { "stores": [ { "name": "s1", "id": "6fbyYnnqUwAEqMmci0cowU", "customers": [ { "id": "4IhkvkCG9WWOykOG0SESWy", ...

Trigger a jQuery event when a different selection is made in the dropdown menu

There are 2 choices available in the dropdown menu. <select id="_fid_140" onchange="chooseRecordPicker()" > <option value="736">9000000146</option> <option value="x3recpcker#">&lt; Browse choices... &gt;</option> Upo ...

Develop a series of sequential tests for the playwright to execute

Can someone assist me with my code? I am attempting to write a test in Playwright that navigates to the forgot password page, creates a new password, and then tries to log in using that new password. However, I am encountering an issue with retrieving the ...

Using Vue to cycle through an array of objects, and emphasize the chosen item by clicking on it

I have to display an array of objects in the DOM by using map method. Each item has a @click event listener where I want to highlight it with a CSS class 'hover'. The desired functionality is to mimic a menu system where only the clicked item sho ...