Effortlessly add data to Codeigniter using the power of ajax

Can an associative array be utilized with Ajax for CRUD operations to insert data without reloading the page and appending it below existing data?


JavaScript Code

function addTextBox(section, id_group) {
row_section = "#row_" + section;
wrapper = $(row_section);
$(wrapper).append('<ul id="fail_' + section + '" class="input_fields" style="list-style-type:none"><li><div class="movement_group"><input type="text" id="txt_' + section + '" id_group="' + id_group + '"class="title_group" name="title_detail[\'' + section + '\']" placeholder="Input" required="" style="width: 300px" /><button type="button" style="margin-left:10px;" class="btn btn-sm sending" onClick="saveTitleGroup(\'' + section + '\', \'' + id_group + '\')">Ok</button><button type="button" onClick="remove_field(\'' + section + '\')" style="margin-left:10px;" class="btn btn-sm remove_content">X</button></div></li></ul>'); //add input box
}

function remove_field(section) {
    section_id = "#fail_" + section;
    $(section_id).remove();
}

function saveTitleGroup(section, id_group) {
    title_group = "#txt_" + section;
    title_group = $(title_group).val();
    td_section = "#td_" + section;
    row_section = "#row_section" + section;

    $.ajax({
        type: "POST",
        url: adminUrl+"/interest/save_detail",
        data: {title: title_group, interest_group_id: id_group}, 
        dataType: "text",
        cache:false,
        success: 
            function(data, textStatus, jqXHR){
                $(td_section).html(data);
            }
    });
}

View

<table id="tableinterest" class="table table-bordered table-striped">
<thead>
    <tr>
        <th>No</th>
        <th>Name</th>
    </tr>
</thead>
<tbody>
    
    <?php
    $n=0;
    foreach ($interest_groups as $interest_group) {
        $n++;   
        echo "<tr>";
        echo "<td>";
        echo $n . ". ";
        ?>
        
        </td>
        <?php
        echo "<td id='td_section_$interest_group[id]' group-id='$interest_group[id]'>";
        echo "<b style='font-size:11pt !important;'>" . $interest_group['title'] . "</b>" . "<span style='margin-left:850px; font-size:15pt;' class='glyphicon glyphicon-plus interest_add' data-toggle='tooltip' data-placement='top' title='Add Detail' onclick='addTextBox(\"section_$interest_group[id]\", \"$interest_group[id]\")'></span><button type='button' style='float:right;' class='btn btn-xs text-red btn-delete-group' data-id='$interest_group[id]' data-category='$interest_group[title]'><span class='glyphicon glyphicon-minus'></span></button> ";
        echo "<br>";
        echo "</br>";
        foreach ($interest_details as $interest_detail) {
            echo "<ul style='list-style-type:none'>";
            if ($interest_detail['interest_group_id'] == $interest_group['id']) {
                echo "<li id='" . $interest_detail['id'] . "'>" . "<label style='font-size:10pt !important;' data-title=\"$interest_detail[title]\" id=\"$interest_detail[id]\" detail_id=\"$interest_group[id]\" class='editme1' id-title='\"$interest_group[id]\"'>" . $interest_detail['title'] . "</label>" .
                "<button type='button' style='float:right;' class='btn btn-xs btn-delete-interest text-red' data-id='$interest_detail[id]' data-category='$interest_detail[title]'><span class='glyphicon glyphicon-minus'></span></button>" . "</li>";
            }
            echo "</ul>";
        }
            
        echo "<div id='row_section_$interest_group[id]'></div>";
        
        echo "</td>";
        echo "</tr>";
    } 
    ?>
    
</tbody>
</table>

Controller

function save_detail(){
    $title = $this->input->post('title');

    $save = $this->save = $this->interest_group->save();

    if ($save) {
        echo $title;
        $this->layout = false;
    } else {
        echo "save failed";
    }
}

Model

function save(){

    $id = $this->input->post('id');
    
    $data = array(
      "interest_group_id"   => $this->input->post('interest_group_id'),
      "title"               => $this->input->post('title'),
      "created_at"          => date("Y-m-d H:i:s"),
      "updated_at"          => date("Y-m-d H:i:s"),
    );

    if ($id == null) {
        $save = $this->db->insert('interest_detail',$data);

        if ($save) {
            return true;
        } else {
            return false;
        }

    } else {
        $this->db->where('id', $id);
        $update = $this->db->update('interest_detail', $data);

        if ($update) {
            return true;
        } else {
            return false;
        }

    }
}

Answer №1

Remember to use single quotes when defining a string like

$string = '<div class"dre"></div>'
. Also, keep in mind that associative arrays require quoted names, such as $array['name'], not just $array[name]. Lastly, ensure to properly concatenate strings and variables in your code.

Here's an example of how you can do this:

<table id="tableinterest" class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Name</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $n=0;
                        foreach ($interest_groups as $interest_group) {
                    $n++;   
                            echo "<tr>";
                            echo "<td>";
                            // echo $interest_group['id'] . ". " 
                            echo $n . ". ";
                            ?>

                            </td>
                            <?php
                                echo "<td id='td_section_".$interest_group['id']."' group-id='".$interest_group['id']."'>";
                                echo "<b style='font-size:11pt !important;'>" . $interest_group['title'] . "</b>" . '<span style="margin-left:850px; font-size:15pt;" class="glyphicon glyphicon-plus interest_add" data-toggle="tooltip" data-placement="top" title="Add Detail" onclick="addTextBox(section_'.$interest_group['id'].','.$interest_group['id'].')"></span><button type="button" style="float:right;" class="btn btn-xs text-red btn-delete-group" data-id='.$interest_group['id'].' data-category="'.$interest_group['title'].'"><span class="glyphicon glyphicon-minus"></span></button> ';
                                echo "<br>";
                                echo "</br>";
                                foreach ($interest_details as $interest_detail) {
                                    echo "<ul style='list-style-type:none'>";
                                    if ($interest_detail['interest_group_id'] == $interest_group['id']) {
                                        echo "<li id='" . $interest_detail['id'] . "'>" . "<label style='font-size:10pt !important;' data-title=\"".$interest_detail['title']."\" id=\"".$interest_detail['id']."\" detail_id=\"".$interest_group['id']."\" class='editme1' id-title='\"".$interest_group['id']."\"'>" . $interest_detail['title'] . "</label>" .
                                        "<button type='button' style='float:right;' class='btn btn-xs btn-delete-interest text-red' data-id='$interest_detail[id]' data-category='$interest_detail[title]'><span class='glyphicon glyphicon-minus'></span></button>" . "</li>";
                                    }
                                    echo "</ul>";
                                }

                                    echo "<div id='row_section_".$interest_group['id']."'></div>";
                            echo "</td>"
                            echo "</tr>";
                        } 
                        ?>
                </tbody>
            </table>

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

Despite encountering Error 404 with AJAX XHR, the request is successfully reaching the Spring Controller

I am attempting to upload a file with a progress bar feature. var fileInput = document.getElementById('jquery-ajax-single') var form = new FormData(); form.append('uploadFile',fileInput.files[0]); $.ajax({ url: "fi ...

Uploading with Javascript CORS consistently ends with an error event occurring

My current challenge is uploading a file to a server using JavaScript in compliance with the CORS specification. While there are numerous examples available online that successfully upload the file, I encounter an error as the final event being fired. Up ...

The display of temporary headers - Nodemailer - AJAX

I keep receiving a warning in the request header that says: Provisional headers are shown. I'm struggling to identify the root cause of this issue. This warning prevents the readyState from changing and my callbacks on the eventhandler onreadystatecha ...

The ajax client is encountering an undefined response, but it is correctly processed when accessed through the

I am in the process of setting up an ajax client with a dummy server for testing purposes. I have successfully resolved the cors issue, but now I am facing a problem where the response from the ajax client is showing as undefined. Interestingly, when I acc ...

Looping through a single object with an Ajax call

When I make this ajax call, it only displays the last object from the JSON file instead of all objects. Can someone help me understand why? Ajax Call var ajax = new XMLHttpRequest(); var data = 'data.json'; var url = 'http://localhost: ...

AJAX requests sent from different origins to AWS S3 may encounter CORS errors on occasion

My current objective is to access publicly available files stored in S3. The CORS configuration for my S3 setup is as follows: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> < ...

Interactive AJAX div click functionality

For this code to work, the user needs to first click the like button and then continue to proceed. However, I am having trouble getting the div event to function properly. The like button is located within a div called postos. When something is clicked wit ...

Issues with the HTML required attribute not functioning properly are encountered within the form when it is

I am encountering an issue with my modal form. When I click the button that has onclick="regpatient()", the required field validation works, but in the console, it shows that the data was submitted via POST due to my onclick function. How can I resolve thi ...

The JQuery function fails to execute following a successful Ajax request

I recently ran into an issue with my Ajax call. Here's the code snippet in question: $("#start-upload-btn").click(function(){ $.ajax({ type: "post", url: "", data: { newProjectName: $('#project-name') ...

How to stop an AJAX request using Chrome developer tools?

Is there a way to cancel an initiated ajax request from Chrome Developer Tools? I want to test if my fallback message displays correctly without changing the code. Setting No throttling to Offline will make all calls fail, but I just need one API to fail f ...

Opening a browser tab discreetly and extracting valuable data from it

Greetings to the experts in Chrome Extension development, I am exploring ways to access information from a webpage without actually opening it in a separate tab. Is there a method to achieve this? Here's the scenario: While browsing Site A, I come a ...

Executing JavaScript function by clicking on <img>

I've been developing a website similar to YouTube, and I'm facing difficulties with the Like/Dislike feature for comments. Currently, I have implemented it in the following way: when a user clicks on an image (thumbsUp.png or thumbsDown.png), a ...

Error when parsing JSON due to the presence of backslashes within the serialized object

When trying to call a server side function and parse the response in client side using JavaScript and Ajax, I encountered a parse error. It seems that the issue lies with the backslash that the JavaScriptSerializer adds to serialize the object. The respons ...

struggling with responseText functionality in javascript

I am encountering an issue with passing variables from PHP to JavaScript using JSON. The problem lies in the fact that I am able to debug and view the items in the responseText within my JavaScript, but I am unable to assign them to a variable or properly ...

Sending dynamic boolean model property via AJAX dynamically

I am facing an issue while passing a property from my model to an AJAX form. The boolean value is resolving as "true/false" and causing problems in the process. $.ajax({ url: '/Projects/SearchTable2', type: "GET", data: { sub ...

Ensure that the alert for an Ajax JSON record count remains active when the count is

Trying out Ajax JSON for the first time has been a bit tricky. Even though I hard coded "Record: 1" on the server side, it keeps alerting me with a total record of 0. I'm not sure where I went wrong. Could it be an issue with how I passed the array da ...

Creating an expandable discussion area (part II)

After checking out this query that was posted earlier, I am interested in implementing a similar feature using AJAX to load the comment box without having to refresh the entire page. My platform of choice is Google App Engine with Python as the primary lan ...

rating-widget not displaying when performing an ajax request

Having an issue with the star rating plugin () while using an ajax function for searching and filtering. The star rating displays correctly when the page initially loads https://i.stack.imgur.com/eaOmu.png However, when utilizing the filter and search fu ...

Returning a JSON representation of a JavaScript object

In the process of working on a script, I encountered a situation where an $.ajax call had to invoke a function upon success, returning a JavaScript object in JSON format [object object]. However, despite being able to return a well-formatted string, access ...

Unexpected token error occurs when making cross-domain AJAX requests to the server and receiving a JSON object

I have set up an express server to handle get requests to specific url endpoints. When responding to these requests, I am sending back data in JSON format to enable making Ajax calls and retrieving data from the page. To allow for cross-domain requests, I ...