Issue encountered while transferring data from view to controller via ajax

I'm looking for a way to send the ID of the checked field and the string "checked" to the database using AJAX. I'm not very familiar with how AJAX works.

<h2 id="h2">To Do List</h2>
        <ul id="new">
            <?php if(!empty($details)){ foreach($details as $key => $del) {  ?>
                <li id="try-0"><input class= "box" type="checkbox"><input class="set field" name="list[]" type="text" value="<?php echo $del['value'];?>"></li>          
            <?php  } ?>

            <li id="try-0"><input class= "box" type="checkbox"><input class="set field" name="list[]" style="margin: 5px 0 5px 10px;width: 297px;height: 35px;" type="text" value=""></li>

            <?php } else{ ?>
                <li id="try-0"><input class= "box" type="checkbox"><input class="set field" name="list[]" type="text" value=""></li>
            <?php } ?>   
        </ul>
        <button class="btn btn-info" id="btn1">add</button>
    

Javascript

<script type="text/javascript">
        $(document).ready(function() {
            var x =1;
            $('#btn1').hide();
            $('body').on('keyup', '.field', function(){
                var search_text = $('.field').last().val();
                if(search_text==""){
                    $('#btn1').hide();
                } else{
                    $('#btn1').show();
                }
            });

            $("#btn1").click(function (event) {
                event.preventDefault();
               $('#new').append('<li" id="try-'+x+'"><input class= "box" type="checkbox"><input  name="list[]" class="set field" type="text" value=""></li>'); 
                $('#btn1').hide();
                x++;      
            });

            $('body').on('click', '.box', function(){
                var sta = 'checked';
                $.ajax({
                    type: "POST",
                    url: "<?php echo base_url();?>homeController/statuspass",
                    data: {search_name:sta},
                    success: function(data){
                        // console.log(success);
                    }
                });
            });
        });
    </script>
    

When I click the checkbox, I want the checkbox's ID and a string to be passed to the controller and saved in the database.

However, when I try this, I get an error:

POST http://localhost/todolist/homeController/statuspass 500 (Internal Server Error)
    send @ jquery.min.js:2
    ajax @ jquery.min.js:2
    (anonymous) @ (index):146
    dispatch @ jquery.min.js:2
    y.handle @ jquery.min.js:2
    

Answer №1

An issue has been detected on the server end. Consider using xDebug to troubleshoot your PHP code or inserting die() messages in your controller action for better insight into the problem.

Answer №2

To properly implement your Js code, it should look something like the following:

$(document).on('click', '#myFormSubmit', function(event) {
    event.preventDefault();

    var id = $('#hiddenInputThatHasMyID').val();
    var blah = 'blah';
    var blahblah = 'blahblah',

    // Make sure you have a way to retrieve the above variables or search for how to do so 

    // You can serialize your form data like this
    // var data = $('form#myForm').serialize();

    // Or manually create it like this
    var data = {id:id, blah:blah, blahblah:blahblah};

    $.ajax({
        url: "<?= site_url('controller/method') ?>",
        method: 'POST',
        data: data,
        dataType:'JSON',
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
    });
});

This code will send your data to the specified controller/method and receive a response from it. In your controller's method, expect something like the following:

public function method()
{
    $id = $this->input->post('id');
    $blah = $this->input->post('blah');
    $blahblah = $this->input->post('blahblah');

    // Perform necessary operations here and return variables
    $data['ret_var1'] = 'val1';
    $data['ret_var2'] = 'val2';

    // Output data as JSON
    header('Content-Type: application/json');
    echo json_encode($data);
}

In your ajax response, utilize the returned variables like so:

var var1 = response.var1;    // val1
var var2 = response.var2;    // val2

I hope this explanation clarifies things.

Additional Notes:

Remember to format your URL using

url: "<?= site_url('controller/method') ?>"

Answer №3

CodeIgniter URLs are optimized to work well with underscores in the letters. Make sure to update your controller name from homeController to HomeController, ensuring that the first letter is capitalized and any subsequent letters are lowercase except for the first one. Also verify that you extend CI_Controller. Secondly, check if the method statuspass is available in your HomeController class.

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

Tips for boosting performance in PHP when working with extensive arrays

Apologies if my question seems trivial, but I am seeking guidance on how to resolve a particular issue. Currently, I have a large multidimensional array that looks like the following: $array_value = Array ( [0] => Array ...

Exploring the integration of AJAX callbacks with ASP.NET User controls

What is the most effective approach for integrating user controls that require AJAX callbacks? My objectives include: Utilizing browser events (such as drag and drop) to trigger an AJAX notification that can initiate a control event, allowing the code o ...

Utilizing backreferencing in PHP's preg_replace function

I'm struggling to grasp the concept of using preg_replace with backreferencing. The goal is to take a plain-text string and convert any links within it to HTML link syntax. For example, "www.mydomain.tld" or "" or "" should all be enclosed in an HTML ...

"Discover the step-by-step process for displaying the menu on a WordPress

After installing the new classifieds theme on my Wordpress website, I noticed that the menu from the previous theme is still showing up. However, when I hover over the menu, it disappears and only reappears once my cursor is no longer hovering over it. ...

Uploading files in chunks using a combination of HTML, JavaScript,

I've been using a file chunking solution (although I can't recall its origin), but I've made some modifications to suit my requirements. Most of the time, the file uploads successfully; however, there are instances where an error occurs. U ...

"Implementing a seamless auto-refresh feature using jQuery without any

I am working with two PHP files where I fetch data from a database in one file and then retrieve all that JSON encoded data in another PHP file using the .getJSON() method. My goal is to refresh the entire page without any blinking or flickering. Any sug ...

Unintended redirects are occurring with AJAX requests when using the send() method

After loading the web page, I utilize AJAX to populate a list asynchronously. However, when the AJAX request is sent to retrieve data for the list box, instead of receiving JSON data as expected, an unintended web page containing the list box is returned. ...

Passing variables via redirection using Zend framework

In my ChildFamily controller, I currently have the following method: public function statusAction(){ $form = new AddChildForm("add"); $view = array( 'form'=>$form ); $familyId = $this->params()->fromRoute("id"); $error = ...

Which flavor of Ubuntu is optimal for setting up a LAMP and web development server? What are the advantages of using Ubuntu 32-bit for this

Currently, I am considering installing Ubuntu for my web development server which will primarily use the LAMP environment, as well as RoR and Python. Additionally, I am contemplating setting up a version control server. However, that is the extent of my pl ...

Can the App be initiated manually using AngularJS and AJAX injection?

My current Angular application is loaded dynamically into the existing webpage. This means that all scripts (such as angular.min.js and controllers) are included in the Wicket AJAX request and injected into the webpage. The scripts are added to the head o ...

Transferring data from Unity to PHP: Passing a variable's value

My PHP file is used for displaying a PDF file that contains variables retrieved from the following PHP file. $areaOfCircle; ... ... $pdf->WriteFixedPosHTML($areaOfCircle, 20, 50, 20, 50, 'auto'); In addition, I have included my Unity script b ...

Is there a way to integrate PHP functionality into JavaScript?

When it comes to using JavaScript and PHP together, a common challenge is retrieving information from a database and utilizing that data in a JavaScript function. In my case, I need this functionality for implementing password change functionality on a w ...

Is there a way for me to determine the value or array that has been passed in the form?

I am facing a challenge and need help solving it. I have a project that involves interacting with a database, where I created a CRUD HTML table for data manipulation. There are 15 tables in the relative database, and I need to insert, delete, and edit reco ...

employing the d3.queue method to defer execution until receiving the AJAX response

Seeking examples of integrating AJAX, d3, and PHP to extract data from a database and create graphs. Any guidance would be appreciated. I am currently using d3 to generate a force chart based on database information retrieved through AJAX and PHP. I have ...

Recreating dropdown menus using jQuery Clone

Hey there, I'm facing a situation with a dropdown list. When I choose "cat1" option, it should display sub cat 1 options. However, if I add another category, it should only show cat1 options without the sub cat options. The issue is that both cat 1 a ...

How to Use jQuery Post Method to Submit a Form Without Redirecting

I am looking to enhance the user experience of my form by preventing it from reloading upon submission. Specifically, I want to trigger the call to index.php when the submit button named "delete-image" is clicked in the scenario outlined below. It's i ...

Guidelines for accessing the POST request entity with Slim framework

After sending JSON data from an Android Java application using the code below: HttpPost httpPostRequest = new HttpPost(URLs.AddRecipe); StringEntity se = new StringEntity(jsonObject.toString()); httpPostRequest.setEntity(se); I am now looking to receive ...

PHP Cross-site scripting validation is failing to function as intended

I've been working on a contact form script and recently attempted to implement XSS validation following the guidance provided on W3Schools. However, I'm facing an issue where if I input a "<" in one of the fields and submit it, the email I rec ...

Creating a Rails application that dynamically fills a table with data from a

Encountering an issue with Ruby on Rails. I have a "Host Model" that contains a method which has a longer runtime. class Host < ActiveRecord::Base def take-a-while # implement logic here end Attempting to access a page where this method ru ...

Using Django to pass context data in a JsonResponse

Currently working on a webpage that incorporates filters to refine the displayed results. Upon triggering an Ajax call, the filters are transmitted to the Django backend for processing. The filtered data is then expected to be returned to the front-end. T ...