save function ajax failure

I have created a function that adds a row after confirmation. The issue is that after submitting, the tables do not reload and show an error alert. In reality, the data is successfully saved but I need to refresh the page for the table to reload. Below is my Ajax jQuery code:

function reloadPage()
{
    window.location.reload();
}

function save()
{
    $('#btnSave').text('saving...'); 
    $('#btnSave').attr('disabled', true); 
    
    var url;

    if(save_method == 'add') {
        url = "<?php echo site_url('activity/save')?>";
    } else {
        url = "<?php echo site_url('activity/update_activity')?>";
    }

    $.ajax({
        url : url,
        type: "POST",
        data: $('#form-input').serialize(),
        dataType: "JSON",
        success: function(data)
        {
            $('#myModal').modal('hide');
            reloadPage();
            $('#btnSave').text('save');
            $('#btnSave').attr('disabled', false);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error adding / update data');
            $('#btnSave').text('save');
            $('#btnSave').attr('disabled', false);
        }
    });
}
<button id="btnSave" onclick="save()" class="btn green">Save</button>

My controller:

public function save() {
    $actype = $this->input->post('actype');
    $activity_name = $this->input->post('activity_name');
    $project = $this->input->post('project');
    $portion = $this->input->post('portion');
    $activity = $this->input->post('actid');

    $data = array(
        'activity_type_id' => $actype,
        'activity_name' => $activity_name,
        'project_id' => $project,
        'portion' => $portion,
        'activity_id' => $activity
    );

    $this->activity->insertactivity($data);

    redirect("activity/input");
}

After clicking the save button, it shows an 'Error adding / update data' alert, however, the data has actually been saved when the page is reloaded. Where is the error in my Ajax code?

Answer №1

Trigger a server-side refresh.

window.location.reload(true);

If you omit true, the page may reload from the browser cache.

Additionally, in the controller, using redirect("activity/input"); is not suitable for an AJAX request. Consider this approach instead.

$this->activity->insertactivity($data);
echo json_encode(array('result' => TRUE));

Your controller code could be more concise. Take a look at this example

public function save()
{
    $data = array(
            'activity_type_id' => $this->input->post('actype'),
            'activity_name' => $this->input->post('activity_name'),
            'project_id' => $this->input->post('project'),
            'portion' => $this->input->post('portion'),
            'activity_id' => $this->input->post('actid')
    );

    //Assuming insertactivity returns TRUE upon successful insertion and FALSE otherwise
    $results['result'] = $this->activity->insertactivity($data);
    echo json_encode($results);
}

You can verify the "result" in the success function

success: function(data)
{
  if(data.result === true)
  {
    $('#myModal').modal('hide');
    reloadPage();
    $('#btnSave').text('save'); //change button text
    $('#btnSave').attr('disabled',false); //set button as enabled 
  } else {
    //Adjust the DOM to indicate any issues encountered
    //consider including this in your controller's response.
  }
},

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

Discover the exclusive Error 404 dynamic routes available only in the production version of NEXT13! Don

Hey everyone, I'm encountering an issue with NEXT's dynamic routing (Next 13). My folder structure looks like this: - user/ -- [id]/ --- page.js It works fine in dev mode but not in production. What am I trying to do? I've created a "page ...

retrieve the path of any module within an npm monorepo

I am working on a project using an NPM monorepo structure which utilizes ECMAScript Modules (ESM): <root> |_package.json |_node_modules/ | |_luxon (1.28.0) |_packages/ |_pack1 | |_node_modules/ | | |_luxon (3.0.1) | |_main.js |_pack2 |_ ...

Creating a smooth animated scroll to a specific #hash while keeping elements hidden on the page

I'm facing an issue with a JavaScript function that scrolls to a selected element with scroll animation. Everything is working fine, however, I encounter a problem when sliding up or down to show/hide certain elements. When a clicked link contains th ...

Rails Navigation Issue: JQuery Confirmation Not Functioning Properly

Having a Rails app, I wanted to replicate the onunload effect to prompt before leaving changes. During my search, I came across Are You Sure?. After implementing it on a form, I noticed that it only works on page refreshes and not on links that take you a ...

Angular Testing - issue with promise returning unexpected results

I'm having trouble with populating vm.chartData in my HomeCtrl. Even though I've mocked data to it in the beforeEach() function, when I console.log(scope.vm.chartData), it returns undefined. However, other scope variables like graphLoading are pr ...

What is the method by which a server sends data to a client in long polling without the client

My current method of requesting data from the server via ajax in intervals feels too easy and lazy for achieving real-time effects. I am now considering switching to long polling or comet techniques because they encourage the server to push data when avai ...

Implementing key strokes in an HTML input field within a geckoWebBrowser

I am currently using the "geckoWebBrowser1" component to navigate to a URL that displays a login textbox with the ID: login-email Although I have successfully inserted "[email protected]" into the aforementioned textbox, it is essential to simulate k ...

What steps can I take to guarantee that a directive's link function is executed prior to a controller?

Our application features a view that is loaded through a basic route setup. $routeProvider .when('/', { template: require('./views/main.tpl.html'), controller: 'mainCtrl' }) .otherwise({ re ...

I am noticing that my popover is causing my page to shift when I click it. It is expanding the width of my page more than I would

Upon clicking the user id popover on my page, it expands the page width instead of adjusting within the page boundaries. This is the issue: https://i.stack.imgur.com/EqaMo.png There's a small white space present that I want to eliminate. When the po ...

Passing this as a function parameter in Jquery

HTML <input type="button" id="1" class="add" value="+" title="Add" onclick="set(this);"/> JS function set(obj){ alert(obj.id); } The code snippet provided above seems to have an issue. My Requirement I am looking for a solution that allows ...

Dynamic dropdown menu triggers AJAX call but fails to retrieve necessary HTML content and data in PHP

In my recent project, I have been working on implementing cascading drop downs using PHP and Ajax. The goal is to populate the second drop-down based on the selection made in the first one. However, despite my efforts, it seems like something is not workin ...

Can we verify if this API response is accurate?

I am currently delving into the world of API's and developing a basic response for users when they hit an endpoint on my express app. One question that has been lingering in my mind is what constitutes a proper API response – must it always be an o ...

Enhancing the efficiency of typed containers in JavaScript

Recently, I uncovered a clever method for creating fake 'classes' in JavaScript, but now I'm curious about how to efficiently store them and easily access their functions within an IDE. Here is an example: function Map(){ this.width = 0 ...

Steps for removing an element from an array using Mongoose and Node.js

After reading and attempting to implement the solutions provided by others, I am still struggling to understand why it's not working for me. This is my first project involving backend development. While progressing through a course, I decided to work ...

Having an issue where $.ajax is unexpectedly redirecting

Today I delved into the world of AJAX, and I must say, it's pretty fascinating. I have a scenario where users can update information in HTML tables without having to reload the page. It worked flawlessly the first time with this... For clarification ...

Tips for clearing state when simply refreshing a DataTable on the page

When it comes to a datatable on a page, I am facing a unique challenge. I want the datatable to be refreshed with a clear state (no column order, etc.), but if the page is accessed by pressing the back button, it should retain its state. I have experiment ...

Trouble with formatting in React

I am presented with the following code snippet that I did not author: render: function () { if(this.state.loading){ return <div><span><i className="fa fa-spinner fa-spin"></i> Loading...</span></div& ...

Is there a way to retrieve the width of the parent element in ReactJS from a child component?

The issue has been fixed: I forgot to include .current in my ref... I am trying to determine the width of the element that will hold my component. I came across a solution on SO, but unfortunately it did not work for me as it returned undefined: import R ...

Having trouble retrieving Bengali-language data from the server using jQuery AJAX

I am facing an issue where I am unable to fetch data in Bengali language from the server using ajax. Strangely, the data retrieved from the server is getting replaced by some unknown characters. However, if I directly retrieve the data without using ajax, ...

Instantiate a fresh Date object in JavaScript by passing in my specific parameter

Check out this code snippet: $(function () { var timestamp = 1443563590; //Tue, 29 Sep 2015 21:53:10 GMT var today2 = moment.unix(timestamp).tz('America/New_York').toString(); alert(today2); //var dateinNewYork = new Date(wh ...