Tips for sending ajax variable value to a codeigniter controller

Looking to transfer the 'q' value from an AJAX call to a controller function within CodeIgniter.

ajax code:   
function getdata(str) 
    {
        if (str == "") {
            document.getElementById("yer").innerHTML = "";
            return;
        } else { 
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("bus").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET","<?php echo site_url('money_c/taxcalculator1'); ?>?q="+str,true);
            xmlhttp.send();
               window.location="<?php echo site_url('money_c/taxcalculator'); ?>"

        }
    }
controller:

    function taxcalculator1()
            {
                $bt=$_GET['q'];
                echo $bt;
            }

Transferring the 'q' value from an AJAX request to a controller function in CodeIgniter is the goal here.

Answer №1

Once you initiate the Ajax request by sending it like this:

xmlhttp.send();

You trigger a page redirect with this:

window.location="<?php echo site_url('money_c/taxcalculator'); ?>"

This action interrupts the Ajax request, deletes the content you are attempting to modify with innerHTML, and essentially invalidates any related JavaScript functions.


If you prefer to use Ajax:

  • Include the data you want to display as part of the response from taxcalculator1
  • Utilize onreadystatechange to showcase the data to the user
  • Avoid leaving the page prematurely (eliminate the window.location line).

If your intention is to load a completely new page:

  • Avoid employing Ajax
  • Simply submit a form to a specific URL
  • Showcase the desired data for the user (in the format of an HTML document) within the response to that request

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

Encountering issue with Mailchimp post request in React app

As I am developing my web application using React without a backend, I encountered an issue while trying to integrate MailChimp. The error message that I received is as follows: ContactUs.jsx:40 POST http://localhost:3000/3.0/lists/{api-key} 404 (Not F ...

Tips for managing the State with AppContext()---Need help figuring out how to handle

Why does setting the state userHasAuthenticated to true in the login function result in isAuthenticated being logged as false (staying the same in App.js as well)? Also, when trying to use it in the Home Component, it still shows false. //-------------- ...

Overwriting private functions in JavaScript

I am currently implementing a workaround for some of jQuery's Draggable code. My objective is to make changes without altering the original source files and dynamically patch one of the internal functions. The specific function _generatePosition is ...

Unlock the power of parentheses in Rails parameters in Rails 4

Utilizing AJAX to submit a form to a Ruby method has presented an issue for me. The form names are automatically generated with parentheses, and while reading the params works fine for those without parentheses, it fails for the ones with them (obviously). ...

What is causing the regular expression to fail when using the OR operator?

Here is the code snippet I've been working on: function toCamelCase(str){ var rest = str.replace((/-/)|(/_/)g, "") ; document.write(rest); } toCamelCase("the-stealth_warrior"); When running this code, I receive an error message: Uncaught Syntax ...

Creating a personalized script in ReactJS: A step-by-step guide

If I have already built a component with Google Chart in ReactJS, and I want to implement a feature that allows the Legend to show/hide data using a JavaScript script provided here, how and where should I integrate this code to work with my chart? Here is ...

Encountering an issue with undefined property 'path' while attempting to upload an image on the frontend in React

I have encountered an issue while trying to upload an image on the frontend. The error message displayed is: message: "Cannot read property 'path' of undefined" status: "fail" When I log req.file on the backend and attempt to ...

Which method is optimal for organizing tree categories and linking them to posts, as well as locating posts based on a selected category within a MERN stack

Currently, I am utilizing the MERN stack for my project development. The project involves a tree category structure as outlined below: {id: { type: Number }, parent_id: { type: Number }, name: { type: String }, sub: { type: Boolean }} For ...

Tips for linking weight scale device to a website

I recently developed a web application that calculates the weight of products. The application was created using PHP, JavaScript, and AJAX, running on a XAMPP server. Now my client is requesting for me to integrate a weight scale machine into the applica ...

When the user clicks, show a designated search result in a separate container

I've been developing my Angular cocktail application, and I've reached a point where I can display all the cocktails in my database (only showing names). Now, I want to implement a feature where if I click on a specific cocktail, its full content ...

Prevent the user from selecting an option if the value is already present

In the process of creating a library membership form, I am utilizing an ajax request to populate the student list in a select option. The goal now is to disable the options for students who are already members of the library. View of the Form <div cla ...

Accessing Data from the Wikipedia API

After receiving a JSON response with the following structure: { "batchcomplete": "", "query": { "pages": { "97646": { "pageid": 97646, "ns": 0, "title": "Die Hard", "extract": "Die Hard is a 1988 ...

Creating dynamic axes and series in Ext JS 4 on the fly

I am looking to dynamically generate the Y axis based on a JSON response. For example: { "totalCount":"4", "data":[ {"asOfDate":"12-JAN-14","eventA":"575","eventB":"16","eventC":"13",...}, {"asOfDate":"13-JAN-14","eventA":"234","eventB":"46","even ...

In VuePress 1.x, the functionality of using the <Content> tag with pageKey is not functioning as expected

Throughout the development process, we implemented a component that would iterate through each index.md file within a folder based on the list this.$site.pages.path. However, after upgrading to version 1.0.0-alpha.39 in order to address some other issues w ...

Tips for displaying backend error messages on the frontend

I am facing an issue with returning error messages from the backend to the frontend in my Angular project. The specific requirement is to display an error message when the value of msisdn is not eligible for renewal. Currently, the hardcoded error message ...

Include the await keyword within the .then block

I'm trying to execute an await after receiving a response in the .then callback of my code: const info = new getInfo(this.fetchDetails); info .retrieve() .then((res) => { const details = this.getLatestInfo(res, 'John'); }) .ca ...

What causes bootstrap to fail on smaller screens?

While developing an app using Bootstrap, I encountered an issue where the app was not functioning properly on small screens. Everything worked perfectly on larger screens, such as a PC browser, but on a mobile browser, none of the tabs would open. When I t ...

Sending a dictionary and a file using Ajax is a useful feature when developing web

Within my HTML code, I have a single file (without a form tag) <input id="file1" type="file" class="form-control form-exception"> along with several textboxes <input id="id-one" type="text" class="form-control" > <input id="id-two" type=" ...

How to pass a jQuery variable to an AJAX function

This function captures email values $("body").on('click','.btn-info', function(e){ var email = []; $('input[type="checkbox"]:checked').each(function(){ email.push($(this).parent().siblings().eq(2).text()); ...

Adding the state of an object to an existing array of objects using the useState

My goal is to create an array of objects structured like this [{},{},{}] The state variable is constructed as shown below: this.state:{...some states, parsed:[{}]} Each object is obtained from IPFS using an async function: IPFSREADER = ele ...