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

Trouble with storing data in Angular Reactive Form

During my work on a project involving reactive forms, I encountered an issue with form submission. I had implemented a 'Submit' button that should submit the form upon clicking. Additionally, there was an anchor tag that, when clicked, added new ...

The redirection code is not being executed when calling .pipe() before .subscribe()

My AuthService has the following methods: signUp = (data: SignUp): Observable<AuthResponseData> => { const endpoint = `${env.authBaseUrl}:signUp?key=${env.firebaseKey}`; return this._signInOrSignUp(endpoint, data); }; signIn = (data: SignIn): ...

How can I retrieve a text file using an API in a Next.js application?

Is there a way to download a text file using an API in Next.js? The console.log(ninjas) function is already displaying the correct information. I have tested the API with Postman and it works perfectly. When I use GET in Postman, the same information is ...

The unexpected behavior occurs when jQuery mobile causes the page to reload

Incorporating jQuery mobile with other systems, I have a scenario where I must display an ajax loaded dialog and send data back to the main page based on the link clicked (with class link). $(document).live("pageinit", function(event) { $(document).on ...

Styling buttons with different colors using React onClick event.getSelectedItem() method

I am having an issue with adding a border when the class is set to "transportation active" in my React code. When I click on one of the icons, all of them become active instead of just the clicked one. This behavior is not what I want, as I only want the ...

Exploring the Mathematical Capabilities of jQuery

I have a question regarding a jQuery code that retrieves the price of Bitcoin from a JSON API and displays its current value in euros. I am interested in converting this to another currency, such as Danish Crown or any other. Essentially, my query is whe ...

Ways to disable the ability to close a bootstrap modal by pressing the backspace key

How can I enable the backspace button in a Bootstrap Modal form for textboxes and textareas? $('body').keydown(function (e) { if ($('#myModal').is(':visible')) { if (e.keyCode == 8) { retu ...

Learn how to manipulate data within a MongoDB database schema using Node.js and Mongoose: inserting, saving, and updating records

When inserting data into the MongoDB schema presented below, make sure that Employee name, Project name, and client name can be the same, but the employee ID must be unique. Duplicate entries are not allowed. var StatusSchema = new mongoose.Schema({ ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

How do I go about transferring data from an excel sheet to an external API with the help of JQuery/Node.js?

If I possess an excel document that needs to be delivered to an API endpoint which demands the following headers: Content-Type: multipart/form-data Content-Disposition: form-data; name="fileData"; filename="Form_SOMETHING(2).xlsx" Is it plausible for me ...

Exploring the dynamic trio of Ajax, JSON, and jQuery within the realm

Is it possible to integrate Ajax, JSON, and jQuery into a Silverlight application? I am considering a job opportunity where Silverlight is the primary technology. They plan to transition to something like MVC in 1-2 years using C#. However, I have recentl ...

Using Flask and AngularJS: Managing Scope in a Controller with Flask Templating

Currently, my primary objective is to create a table with sortable columns. While following a tutorial and attempting to implement it into my project, I have encountered an issue. It seems that the structure of my code will not allow this functionality to ...

Delaying the call of a JavaScript function with jQuery

Basic JavaScript Function: $(document).ready(function(){ function sampleFunction() { alert("This is a sample function"); } $("#button").click(function(){ t = setTimeout("sampleFunction()",2000); }); }); HTML ...

Tips for including the % symbol in the Y-axis labels on a HighChart graph

I am attempting to incorporate the % symbol after the value of 100 or -100 on the yAxis in the chart shown above. I made an attempt to add the % symbols as follows: quotes.data.frequency_counts[i].negative = Math.round(negative * -1)+'%'; quote ...

Utilizing a keycode within the jQuery plugin without the need to explicitly pass it through options

I am currently working on developing a custom jQuery plugin. My goal is to be able to check the keyCode within the plugin without needing to pass it through as an option parameter. Below, you can see the code snippet that I'm using. It's a bit c ...

Next.js is experiencing issues with the build process

I encountered an issue while working on a Next.js project with NextAuth.js. The problem arises when I try to define my authOptions, as a TypeScript error indicates that the object is not compatible with the expected type for AuthOptions. Here's the sn ...

Having trouble with the functionality of a simple jQuery toggle menu on mobile?

I am experiencing an issue with a simple toggle menu that utilizes jQuery's on: tap feature, but it is not functioning as expected: <nav id="mobile-nav"> <ul> <li>Item 1</li> <li>Item 2</li> ...

What is the connection between serialization and JSON?

Can you explain serialization? Serialization is the process of converting an object into a stream of bytes, allowing it to be sent over a network or stored in a file. This allows the object to be reconstructed later on. What exactly is JSON? JSON stands ...

"Centered in the middle of the screen, an animated

Encountering an issue with this code on Chrome. Clicking on the checkbox causes the text/checkbox to shift in position/padding/margin unexpectedly.. :( View the code on JSFiddle HTML <input id="inp" type="checkbox" /> <div id="cb" class="inp_ch ...

Is it possible to save the current permissions for a channel or category in Discord.js and then restore them after a certain event occurs?

A Little Background I recently came across a lockdown command on YT that locks down all channels in the guild when you type "!lockdown". This command overwrites channel permissions for specific roles. However, when we unlock the channels, everyone is able ...