change image color when reveal content

I am working on a section where I need to give color to the image when revealing the content.

This is a example of the code:

jQuery(function($){
    var revealButtons = {
        '.rv_button_1-do': '.rv_element_1-do'
    
 
    };
    $.each(revealButtons, function(revealButton, revealElement) {
        $(revealButton).click(function(e){
            e.preventDefault();
            $(revealElement).slideToggle();
            $(revealButton).toggleClass('rotateicon img-color');
        });
    });
});
body:not(.et-fb) .rv_element-do { display: none; }
.img-color {
filter: grayscale(100%);
}
.rv_button_1-do{
background-color: blue; 
padding: 12px 20px; 
color: white;
width: 200px;
text-align: center; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img decoding="async" loading="lazy" src="https://media.npr.org/assets/img/2017/01/18/red-turtle_wide-03029731def2957b2fb69fb27e44c5c2e456f4a6-s800-c85.webp" width="80" height="165" alt="" class="img-color">
<p>Example text</p>
<div class="rv_element-do rv_element_1-do">                                         
    <p>Helps to fund ten (10) Estuary pop-up outreach events, or one (1) water-quality testing location kit for an entire year, or a day of seagrass monitoring in the field. Included with this donation:</p></div>
 
 <div class="rv_button_1-do"><a>button reveal</a></div>

I tried to add a class at the moment of opening the content and remove the added filter, but I have not been successful.

Global variable declaration returns undefined, any reason for this

When I log input to the console, it returns undefined but when put inside a the anonymous function, it logs to the console as expected

I had tried the below code, and expected that the inputValue to be logged to the console on click of the addButton, however, the value from inputValue when logged was undefined, the value of inputValue is meant to be gotten from an inputbox.

`

const addButton=document.querySelector(".addButton");
let listBox=document.querySelector(".listBox");
let input=document.querySelector(".addtext").value;
let inputValue=input;
addButton.addEventListener('click',()=>{
console.log(inputValue)});

</script>
</body>
</html>`

How can i verify a interval in array with one function

How can i verify how many numbers in a array is in or out a 10-20 interval (10 and 20 included) in one function? I tried but i just got it with two functions, one to verify if its out and one to verify if its in.

let array = [1,3,7,10,14,18,20,23,27]

function inInterval(e){
    if (e >= 10 && e <=20) {
        return e
    }
}

function outInterval(e) {
    if (e <10 || e>20) {
        return e
    }
}

let inIntervalResult = array.filter(inInterval).length
let outIntervalResult = array.filter(outInterval).length

console.log(inIntervalResult, outIntervalResult)    

button onClick doesnt do anyhting NextJS using typescript

So i create a login page with a button to sign and hit API. but when i click the button, it doesn’t do anything. is there any mistake in my code? i checked console log it didn’t show any error or response.

how can i call the handleLogin function in a right way?

function LoginForm() {
  const { setAuth } = useContext<any>(AuthContext);
  const [showSnackbar, setShowSnackbar] = useState(false);
  const [field, setField] = useState({ username: "", password: "" });
  

  function fieldHandler(e: any) {
    setField({
      ...field,
      [e.target.name]: e.target.value,
    });
  }

  async function handleLogin(e: any) {
    e.preventDefault();
    try {
      const loginReq = await axios.post(
        "https://spda-api.onrender.com/api/auth/login",
        {
          headers: {
            "Content-Type": "application/json;charset=utf-8",
          },
          username: field.username,
          password: field.password,
        }
      );
      const loginResp = await loginReq.data;
      if (loginReq.status === 200) {
        setAuth(loginResp);
        Cookie.set("token", loginResp.token);
      
        Router.push("/admin/dashboard");
      }
    } catch (error) {
      const err = error as AxiosError;
      console.log(err);
      setShowSnackbar(true);
    }
  }

  return (
    <>
      <section className="h-screen">
        <div className="container px-6 py-12 h-full">
          <div className=" md:w-8/12 lg:w-6/12 mb-12 md:mb-0">
            {showSnackbar && <SnackbarAlert message="Login gagal" />}
          </div>
                    <form>
//here is the input for username and password
                <div className="mb-6">
                                 <button
                  type="button"
                  onClick={handleLogin}
                  className="inline-block px-7 py-3 bg-blue-600 text-white font-medium text-sm leading-snug uppercase rounded shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out w-full"
                  data-mdb-ripple="true"
                  data-mdb-ripple-color="light"
                >
                  Sign in
                </button>
              </form>
          
        </div>
      </section>
    </>
  );
}

export default LoginForm;

i think the way i call the function is wrong. anyone have a suggestion? thank you.

My code for a drawing will open the JFrame, but not show what I drew

So I’m trying to make a drawing for an assignment that includes different shapes. I have the code for the drawing the and the window, but when I run it the only thing that shows up is the JFrame and not the drawing I am trying to display, which in this case is a snowman.

MyFrame.Java This is my code for the drawing and JFrame

import java.awt.;
import javax.swing.
;

public class MyFrame extends Main {

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw the body of the snowman
    g.setColor(Color.WHITE);
    g.fillOval(200, 50, 200, 200);
    g.fillOval(150, 150, 300, 300);
    g.fillOval(100, 300, 400, 400);

    // Draw the buttons
    g.setColor(Color.BLACK);
    g.fillOval(250, 250, 50, 50);
    g.fillOval(350, 250, 50, 50);
    g.fillOval(300, 350, 50, 50);

    // Draw the eyes and mouth
    g.fillOval(250, 200, 20, 20);
    g.fillOval(350, 200, 20, 20);
    g.drawArc(300, 250, 100, 50, 200, 140);

    // Draw the arms
    g.drawLine(150, 200, 75, 100);
    g.drawLine(450, 200, 525, 100);

    // Draw the hat
    g.setColor(Color.BLACK);
    g.fillRect(250, 75, 100, 25);
    g.fillRect(275, 25, 50, 50);
}

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Snowman");
    frame.setSize(700, 700);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

}

Main.Java This is my other class.

import java.awt.Graphics;

public class Main {

public static void main(String[] args) {
    
    new MyFrame();

}

public void paintComponent(Graphics g) {
    // TODO Auto-generated method stub
    
}

}

javascript extract and convert into new array

I have the following array

[ {
            "contactId": "a87d096gd5fuop",
            "firstName": "John Doe",

            "registrationTypes": {
                "selectedOptions": [
                    {
                    }
                ],
                "subTotal": 1620.003
            },
            "foo1": {
                "selectedOptions": [
                ],
                "subTotal": 0
            },
         
            "events": {
                "selectedOptions": [
                    {
                        "id": "1",
                        "name": "T1",
                        "value": "4550006:3",
                    },
                    {
                        "id": "2",
                        "name": "T2",
                        "value": "4550005:3",
                    },
                    {
                        "id": "3",
                        "name": "T3",
                        "value": "4550003:3",
                    }
                ],
                "subTotal": 135.003
            },
            "freeNetworkingFunctions": {
            
            },

            "total": 1755.0059999999999
        },
        {
            "contactId": "a097f",
            "firstName": "David",

            "registrationTypes": {
                "selectedOptions": [
                   
                  {}
                ],
                "subTotal": 899.998
            },
            "foo1": {
                "selectedOptions": [
                 
                ],
                "subTotal": 0
            },
            "member": {
                "selectedOptions": [
                    {
                        
                    }
                ],
                "subTotal": 228.8
            },
            "events": {
                "selectedOptions": [
                    {
                        "id": "4",
                        "name": "T4",
                        "value": "4550002:2",
                     
                    },
                    {
                        "id": "5",
                        "name": "T5", 
                        "value": "4550001:2",
                       
                    },
                    {
                        "id": "6",
                        "name": "T6",
                        "value": "4550003:2",
                       
                    }
                ],
                "subTotal": 135.003
            },
           
            "total": 1263.801
        }
    ]

From the above array, I want to extract events, loop all the data and get only values. So my new array should be something like this:

[ {
    "contactId": "a87d096gd5fuop",
    "firstName": "John Doe",

    "registrationTypes": {
        "selectedOptions": [
            {
            }
        ],
        "subTotal": 1620.003
    },
    "foo1": {
        "selectedOptions": [
        ],
        "subTotal": 0
    },
 
    "events": [
        "4550006:3"
        "4550005:3",
        "4550003:3", 
    ],      

    },
    "freeNetworkingFunctions": {
    
    },

    "total": 1755.0059999999999
},
{
    "contactId": "a097f",
    "firstName": "David",

    "registrationTypes": {
        "selectedOptions": [
           
          {}
        ],
        "subTotal": 899.998
    },
    "foo1": {
        "selectedOptions": [
         
        ],
        "subTotal": 0
    },
    "member": {
        "selectedOptions": [
            {
                
            }
        ],
        "subTotal": 228.8
    },
    "events": [
        "4550004:2"
        "4550008:3",
        "4550003:3", 
    ],    
        "subTotal": 135.003
    },
   
    "total": 1263.801
}
]

So it should return the original array, however, events value data should be in one array.

 var arr = [];
    for(var i=0;i<data.length;i++){
        data.push(arr[i].value);
    }

var newData = […data, arr]

However, this doesn’t work. Any help would be highly appreciated.

Javascript match and highlight advanced

I’m trying to build a search engine with javascript and PHP. So far, I have had success, but I still have a bit problem with highlighting search terms and limiting the words. The backend response is returning a JSON with a title and description, and the description could be long, so I want to limit the text and highlight those words that the user is searching for.

So basically, if backend response is like:

[{
    "title": "Test topic",
    "description": "<p>This topic contains some words that user is searching for</p> 
    <div><h1>It could contain anything</h1>
    <p> It could contain anything. Important thing is that it should work.</p>
    <img src="some_pic.jpg/>"
   }]

So, if I’m searching for something like “What important topic contains”. The user should see a parsed version of the description (or whatever string given), with limiting the text radius around the search term. And for this, perfect response would be like:

This topic contains some words that user… It could contain
anything. Important thing is that it would…

So I didn’t pay attention to the details here in words, to be exact with the radius, but I think you got the idea.

So what I did so far is

  • map the response from the backend
  • delete html code (in order to prevent ex. “…ong>”) `
  • split the search term words and execute the function to find them, make them bold and make a radius around them
  • show to the user in a view

Where is the problem? I have no logic to match 2 words, I’m splitting search term, creating an array and pushing parsed version into that array.

And it looks like: (important part of the component)

{
  searchResults.length > 0 ? (
    <div>
      <span className={`text-xs text-blue`}>Threads</span>
      {searchResults?.map((searched: any, index: Key) => {
        // Replace html code (just in case)
        const searchTerm = searched.description.replace(/</?[^>]+(>|$)/g, " ");

        // Create array to push search term
        const searchArray: any[] = [];

        // Split search words into array and match results separately
        search.split(" ").map((text, i) => {
          // This function will be in the next code
          searchArray.push(searchText(searchTerm, text));
        });

        // Just a view here
        return (
          <Link key={index} href={"/forum/thread/" + searched?.slug}>
            <article
              className={`w-full bg-gray-dark  mb-2 px-3 py-1.5 rounded-xl text-gray-light`}
            >
              <h2>{searched.title}</h2>
              {searchArray.map((match, i) => {
                return (
                  <>
                    {/*Just in case, show it as html*/}
                    <div
                      className={`quill post-content text-xs text-gray`}
                      dangerouslySetInnerHTML={{ __html: match }}
                    />
                  </>
                );
              })}
            </article>
          </Link>
        );
      })}
    </div>
  ) : null;
}

And finally, a logic to highlight the text and make a radius around that word.

const searchText = (description: string, search: string) => {
        const radius = 30;
        const indexPosition = description.search(search)
        const startPosition = indexPosition - radius < 0 ? indexPosition : indexPosition - radius
        const endPosition = indexPosition + radius + search.length

        return (`...${description.slice(startPosition, endPosition)}...`).replace(search, `<span class="font-bold text-yellow">${search}</span>`)
    }

So in all that case I would see at the end (with same search term “What important topic contains”)

…anything. Important thing is that it would…
…This topic contains some words that…
…This topic contains some words that user…
… It could contain anything. Important thing…

Basically searching every word couple of times. Any ideas how to improve that logic?

Create a file with the same name as the folder where a file was uploaded

I have an HTML form within a Web App, created with GAS.

This HTML form was created from this file upload script here:

drive-multi-upload

This is the HTML form:

enter image description here

The point is that I needed the files to be uploaded in folders that follow the following pattern:
enter image description here

The first number refers to the model selected on the form, the second number refers to the slot used.

Therefore, it was necessary to create a function to identify the input chosen in the Model and, according to this input, check which is the first empty folder, then take the ID of that folder and pass it to the client side to upload the file inside it.

With the help of some members of the community, some adaptations were made and the final function was this:

    /** Modified version of script written by Tanaike */
    function createOrGetFolder(folderName, parentFolderId) {
      try {
        var parentFolder = DriveApp.getFolderById(parentFolderId), folder;
        if (parentFolder) {
          var foldersIter = parentFolder.getFoldersByName("Video");
          if (foldersIter.hasNext()) {
            var videoFolder = foldersIter.next();
            var nextFolderName = folderName + "-01";
            while (!folder) {
              video_folder = videoFolder.getFoldersByName(nextFolderName);
              if (video_folder.hasNext()) {
                folder = video_folder.next();
                var files = folder.getFiles();
                if (files.hasNext()) {
                  var [a, b] = nextFolderName.split("-");
                  nextFolderName = `${a}-${String(Number(b) + 1).padStart(2, "0")}`;
                  folder = null;
                }
              } else {
                folder = videoFolder.createFolder(nextFolderName);
              }
            }
          } else {
            folder = parentFolder.createFolder("Video");
            folder = folder.createFolder(folderName);
          }
        } else {
          throw new Error("Parent Folder with id: " + parentFolderId + " not found");
        }
        return folder.getId();
      } catch (error) {
        return error;
      }
    }

It works perfectly, the point is that this form also has a function that generates a .csv file when the form is submitted, the function is this one:

.gs file:

const saveDataAsCSV = (data, folderId) => DriveApp.getFolderById(folderId).createFile("Sample.csv", data);

HTML file:

var name = $('#name01').val();
      var description = $('#description').val();
      var model = $('#Model').val();
      upload_folder = model;
      var color = $('#Color').val();
      var form_values = [name, description, model, color];
      var data = form_values.join(",");

google.script.run.saveDataAsCSV(data, uploadParentFolderId);

My goal is to make the .csv file be generated with the same name as the folder where the file was uploaded, that is, if the file is uploaded in folder 01-01, the file name has to be 01-01.csv, if the file is uploaded in the 02-02 folder, the file name has to be 02-02.csv, and so on.

How can I achieve this?

The complete script can be viewed in the GAS of this worksheet

Convert Int to Float Without return String Javascript

I want to convert an int value to a float without returning a string value. If I use parseFloat(value).toFixed(2) it returns a string value. Example “15000.00”. I want to return without a string of 15000.00.

Is there any solution?

My expect returns value which is not a string, I need like -> 15000.00
not “15000.00”

The other API requires me to return value to float form. Postman displays {{Key ‘estimation_cost’ error: 150000 should be instance of ‘float'”,”hint”:”Check the request body”}”

Code:

var cost_float = parseFloat(result_2.purchase_request_line[i].estimation_cost).toFixed(2)
result_2.purchase_request_line[i].estimation_cost = cost_float

message”: “404 – {“status”:”error”,”msg”:” / Key ‘estimation_cost’ error: 150000 should be instance of ‘float'”,”hint”:”Check the request body”}”,

My Return “estimation_cost”: “150000.00”,

figuring out how canI make this smoke animation?

Can please anyone help me to figure out how can I make this smoke animation?
after the page loaders ends the first page we get has some serious good looking animation which I’m not able to replicate so please help me to figure it out guys!
link: https://bradguesman.com/

I’m expecting either code of that design or just the detailed explanation of the idea from which I can make that code by myself.

Javascript – Higher order functions, callbacks, returning, scope chain – I could use some assistance, see example pleas

I really could use some help in understanding how this all works. Please bare with since I am a disabled learner who sometimes can not grasp basic concepts like other people. I have tried looking it up, searching Google, and Chatgpt for answers, but I seem to have a problem with closure I believe it called.

 function eitherCallback(callback1, callback2) {
    return num => callback1(num) || callback2(num)
   
}


function filterArray(array, callback) {
  const newArray = [];
  for (let i = 0; i < array.length; i += 1) {
    if (callback(array[i],i, array)) newArray.push(array[i]);
  }
  return newArray;
}
const arrOfNums = [10, 35, 105, 9];
const integerSquareRoot = n => Math.sqrt(n) % 1 === 0;
const over100 = n => n > 100;
const intSqRtOrOver100 = eitherCallback(integerSquareRoot, over100);
console.log(filterArray(arrOfNums, intSqRtOrOver100)); // should log: [105, 9]

So, what I do not understand is the value/values being sent to eitherCallback and how the arguments work.

So first filterArray has 2 parameters, arrOfNums and intSqRtOrOver100
So I was able to figure out a lot of problems like that intSqRtOrOver100 is a function just a variable, a function expression, however, that is not hoisted so filterArray would go first.

arrOfNums would be the array, and intSqRtOrOver100 would invoke intSqRtOrOver100 the function,

First Question/Issue: intSqRtOrOver100 is the function calling eitherCallback(integerSquareRoot, over100);? So intSqRtOrOver100 would take not arguments, however, filterArray is passing it iteration of referenced index in the array passing the value to the callback which is intSqRtOrOver100. So it would be 10 passed to intSqRtOrOver100?

Yet, there are 3 arguments being sent to intSqRtOrOver100?

Second Question/Issue: When intSqRtOrOver100 is invoked by the callback, intSqRtOrOver100 is calling eitherCallback with two parameters, so the two parameters are functions passed in as arguments which I understand, however, when intSqRtOrOver100 is invoked, those two parameters are not being passed arguments since they are functions yet, somehow it is being sent an element from the array?

Third Question/Issue: So eitherCallback has two functions and is created by intSqRtOrOver100 invoked, I am passing an element from the array and somehow 3 things from filterArray? Also, no arguments are being sent since they are functions, then inside of the function I am using a return function I guess the name if “num”, however, how can Callback1(num) exist? Nothing is declared as num except itself. Changing the parameter name defaults to an error. I understand the about it being true and condition of it but, not how Callback1 is being called with “num” itself and how come the index, plus two others are being passed into it yet, I can not access the newArray, i or the array inside of eitherCallback, yet shouldn’t filterArray be the higher order function and since it’s the parent, should I be able to access it values?

Please, I have really tried for over 8 hours to understand this. I do understand some of it, but, since this is my first time asking for help, I was nervous about asking and hope I got it to come out right. If you could explain it to me simply and slowly because I am not quite understanding and I really want to learn this concept if possible. Thank you so much for your time.

Searched:

Google
Stackoverflow
Videos
ChatGPT
Chegg
Various Websites
Digital Ocean
Youtube

Doesn’t Async Await actually make a function synchronous? Why is it called async?

Why is async called async? doesn’t it actually make it synchronous/ sequential since it’s waiting for a response before proceeding to the next step?

function test1(){console.log("test1")};

function test2(){setTimeout(console.log("test2"),2000)}; // screw the syntax

function test3(){console.log("test3")};
async function foo(){
test1();
await test2();
test3();
};

it will return

test1
test2
test3

making the function foo run in order.. doesn’t async make a function synchronous??

vs without the await making it return

test1
test3
test2

isn’t this considered asynchronous since test2() is running while it goes on to test3()? and the async/ await actually makes it a synchronous sequential function since it’s awaiting for a response before proceeding to the next step?


someone is going to mention Promises and how async/ await handles promises.
sure.
but why is it called async? wouldn’t it make more sense to be called sync/ await?
am I not understanding async/ await?

Hello im doing a project for a big exam and my teacher and i thought was working but its not, Can anyone suggest anything

i getting these errors

jdoodle.cs(11,10): error CS0103: The name `Console' does not exist in the current context
jdoodle.cs(12,27): error CS0103: The name `Console' does not exist in the current context
jdoodle.cs(12,55): error CS0103: The name `Console' does not exist in the current context
jdoodle.cs(13,23): error CS0103: The name `Convert' does not exist in the current context
jdoodle.cs(25,13): error CS0103: The name `Console' does not exist in the current context
jdoodle.cs(26,30): error CS0103: The name `Console' does not exist in the current context
jdoodle.cs(28,13): error CS0103: The name `Console' does not exist in the current context
jdoodle.cs(29,27): error CS0103: The name `Convert' does not exist in the current context
jdoodle.cs(32,10): error CS0103: The name `Console' does not exist in the current context
jdoodle.cs(33,10): error CS0103: The name `Console' does not exist in the current context
jdoodle.cs(34,10): error CS0103: The name `Console' does not exist in the current context
Compilation failed: 11 error(s), 0 warnings
`class Program
{
    static void Main() {
        string Overdue_member,Highest_overdue_member;
        double  Overdue_fee, Highest_overdue_fee, Total_Overdue_fee;
        Total_Overdue_fee = 0 ;
        Overdue_fee = 0;
        Highest_overdue_member = " ";
        Highest_overdue_fee = 0;
    
         Console.WriteLine("Enter overdue member");
         Overdue_member = Console.ReadLine();         
         Console.WriteLine("Enter overdue fee for              overdue member");
         Overdue_fee = Convert.ToInt32(Console.ReadLine());         
    
        while(Overdue_fee > 0)
                {
           if(Overdue_fee > Highest_overdue_fee)
                {
                Highest_overdue_fee = Overdue_fee;
                Highest_overdue_member = Overdue_member;
                }
            
            Total_Overdue_fee = Total_Overdue_fee + Overdue_fee;
        
            Console.WriteLine("please enter overdue member");
            Overdue_member = Console.ReadLine();
        
            Console.WriteLine("please enter overdue fee");
            Overdue_fee = Convert.ToInt32(Console.ReadLine());
        
         }
         Console.WriteLine("The highest overdue member is :" +Highest_overdue_member);
         Console.WriteLine("The highest overdue fee is :" +Highest_overdue_fee);
         Console.WriteLine("The total overdue fee :" +Total_Overdue_fee);
}
}

`

The searchfilter i make didn’t fetch the data i want to search

I’m adding a search filter in my system but it won’t search.Please someone tell Me the problem with my coding.

Controller

public function facility_reservation_view(){
            $name = $this->input->post('name');
            $searchtype  = $this->input->post('searchtype');
            $datefrom  = $this->input->post('datefrom');
            $dateto  = $this->input->post('dateto');
            $status = $this->input->post("status");

            $query = $this->model_facility->facility_reservation_table($name, $status, $searchtype, $datefrom, $dateto);
        echo json_encode($query);
    }

Model

public function facility_reservation_table($name, $status, $searchtype, $datefrom, $dateto){
        // storing  request (ie, get/post) global array to a variable  
        $requestData= $_REQUEST;

        global $access;

        $columns = array( 
            // datatable column index  => database column name for sorting
                0 => 'fr_id',
                1 => 'fr_status',
                2 => 'CONCAT(fr_fname, fr_mname, fr_lname)',
                3 => 'fr_room',
                4 => 'fr_purpose',
                5 => 'CONCAT(fr_date_from, fr_time_from)',
                6 => 'CONCAT(fr_date_to, fr_time_to)'
            );

        $sql = "SELECT * FROM facility_reservation WHERE fr_enabled = 1";
        $query = $this->db->query($sql);
        $totalData = $query->num_rows();
        $totalFiltered = $totalData;  // when there is no search parameter then total number rows = total number filtered rows.

        $sql = "SELECT * FROM facility_reservation WHERE fr_enabled = 1";

        if ($searchtype == "divdate") {
            $sql .= " AND fr_date_from BETWEEN ? AND ? ";
            $data = array($datefrom, $dateto);

        }
        elseif ($searchtype == "divname"){
            $sql .= " AND fr_fname LIKE ? " ;
            $data = array($name);
            
        }
        elseif ($searchtype == "divstatus") {
            $sql .= " AND fr_status LIKE ? ";
            $data = array($status);
        }

        $query = $this->db->query($sql, $data);
        $totalData = $query->num_rows();
        $totalFiltered = $totalData;  // when there is no search parameter then total number rows = total number filtered rows.

        
        $sql .=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']."   ";  // adding length
        $query = $this->db->query($sql);

        $data = array();
        $token = en_dec("en", $this->session->userdata('token_session'));
        foreach( $query->result_array() as $row ) {  // preparing an array for table tbody
            $nestedData=array();
            $nestedData[] = $row["fr_id"];
            $nestedData[] = $row["fr_status"];
            $nestedData[] = $row["fr_fname"]." ".$row["fr_mname"]." ".$row["fr_lname"];
            $nestedData[] = $row["fr_room"];
            $nestedData[] = $row["fr_purpose"];
            $nestedData[] = $row["fr_date_from"]." ".$row["fr_time_from"];
            $nestedData[] = $row["fr_date_to"]." ".$row["fr_time_to"];

            $nestedData[] = '<button data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#viewFRModal" class="btn btn-info btnViewFR btnTable" name="update" data-value="'.$row['fr_id'].'" id="'.$row['fr_id'].'"><i class="fa fa-eye"></i> View</button> <button data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#updateFRModal" class="btn btn-success btnUpdateFR btnTable" name="update" data-value="'.$row['fr_id'].'" id="'.$row['fr_id'].'"><i class="fa fa-edit"></i>Update</button>  <button data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#deleteFRModal" class="btn btn-primary btnDeleteFR btnTable" name="delete" data-value="'.$row['fr_id'].'" id="'.$row['fr_id'].'"><i class="fa fa-trash"></i> Delete</button>';
            $data[] = $nestedData;
        }

        $json_data = array(
            "draw"            => intval( $requestData['draw'] ),
            "recordsTotal"    => intval( $totalData ),
            "recordsFiltered" => intval( $totalFiltered ),
            "data"            => $data
        );

        return $json_data;
    }

view

<div class="row">
                                        <div class="col-lg-2">
                                            <div class="form-group">
                                                <label class="form-control-label col-form-label-sm">Select Filter</label>
                                                <select id="sosearchfilter" class="form-control sosearchfilter">
                                                  <option value="divdate">Search by Date</option>
                                                  <option value="divname">Search by First Name</option>
                                                  <option value="divstatus">Search by Status</option>
                                              </select>              
                                          </div>
                                      </div>
                                      <div class="col-lg-4">
                                        <div class="form-group row">

                                            <div class="divdate" id="divdate">
                                                 <?php
                                                    $dateInTwoWeeks = strtotime('-1 weeks');
                                                    $dateInTwoWeeks = date("m/d/Y", $dateInTwoWeeks);
                                                    // echo $dateInTwoWeeks;
                                                    ?>
                                                <label class="form-control-label col-form-label-sm">Date</label>
                                                <div class="input-daterange input-group" id="datepicker">
                                                    <input type="text" id="datefrom" class="input-sm form-control material_josh search-input-select1 searchDateTo" value="<?=$dateInTwoWeeks;?>" name="start" readonly/>
                                                    <span class="input-group-addon" style="background-color:#fff; border:none;">to</span>
                                                    <input type="text" id="dateto" value="<?=today_text();?>" class="input-sm form-control material_josh search-input-select2 searchDateFrom" name="end" readonly/>    
                                                </div>   
                                            </div>
                                            <div class="divname" id="divname" style="display: none;">
                                                <label class="form-control-label col-form-label-sm">Name</label>
                                                <input type="text" class="input-sm form-control material_josh search-input-text search_name" id="search_name" placeholder="Name.." onkeypress="return (event)" /> 
                                            </div>
                                            <div class="divstatus" id="divstatus" style="display: none;">
                                                <label class="form-control-label col-form-label-sm">Status</label>
                                                <select id="search_status" class="form-control fr_status" >
                                                    <option value="<?php foreach ($get_stat->result() as $gdept) { ?>" ></option>
                                                        
                                                    <option value="<?=$gdept->fr_status_name?>"><?=$gdept->fr_status_name?></option>
                                                                    <?php } ?>
                                                </select>
                                                </div>
                                            </div>

                                        </div>
                                    <div class="col-lg col-6" style="padding-left: 0">
                                        <div class="pull-right">
                                            <label class="form-control-label col-form-label-sm "></label>
                                            <button type="submit" id="search_order" class="btn blue-grey search_order">Search</button>  
                                            <button type="button" data-target="#addFRModal" class="btn btn-primary addsupp"> Add New Room Reservation</button>  
                                        </div>                          
                                    </div>
                                    </div>

js

$(function(){
    var base_url = $("body").data('base_url'); //base_url come from php functions base_url();
    var token = $("#token").val();

    var d = new Date();
    var date = d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDate();
    var searchDateTo = $("#searchDateTo").val();

    function fillDatatable(name, status, searchtype, datefrom, dateto) {
        var dataTable = $('#table-grid').DataTable({
            destroy : true,
            "bDeferRender": true,
            "order": [[ 1, "desc" ]],
            "serverSide": true,
            "columnDefs": [
                { "targets": 1,
                  "createdCell": function (td, cellData, rowData) {
                    if (cellData == "Approved"){
                        $(td).css('background-color', '#DFF0D0')
                    }else if (cellData == "Disapprove"){
                        $(td).css('background-color', '#F5DBD9')
                    }else if (cellData == "Pending"){
                        $(td).css('background-color', '#FEECB5')
                    }else if (cellData == "Cancel"){
                        $(td).css('background-color', '#CFCFC4')
                    }else if (cellData == "New"){
                        $(td).css('background-color', '#DAF0F7')
                    }
                  }
            }],
            "ajax":{
                url:base_url+"Main_facility/facility_reservation_view", // json datasource
                type: "post",  // method  , by default get
                data: { 'name':name, 'status':status, 'searchtype':searchtype, 'datefrom':datefrom, 'dateto':dateto },
                beforeSend:function(data) {
                    $.LoadingOverlay("show"); 
                },
                complete: function() {
                    $.LoadingOverlay("hide"); 
                },
                error: function(){  // error handling
                    $(".table-grid-error").html("");
                    $("#table-grid").append('<tbody class="table-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
                    $("#table-grid_processing").css("display","none");
                }
            }
        });
    }

    function toastMessage(heading, text, icon, color) {
        $.toast({
            heading: heading,
            text: text,
            icon: icon,
            loader: false,  
            stack: false,
            position: 'top-center', 
            allowToastClose: false,
            bgColor: color,
            textColor: 'white'  
        });
    }

    fillDatatable('divdate', searchDateTo, date, "");
    
    // $(".searchBtn").on("click", function(){
    //  name = $(".searchName").val();
    //  status = $(".searchStat").val();
    //  fillDatatable(name, status);
    // });


    $("#sosearchfilter").change(function() {
        var searchtype = $('#sosearchfilter').val(); // id ng dropdown
        var currentdate = new Date();
        var dateto = $('#searchDateTo').val();
        var datefrom = $('#searchDateFrom').val();
        
        if(searchtype == "divdate") {
            $('.divdate').show('slow');
            $('.divname').hide('slow');
            $('.divstatus').hide('slow');
            $(".search_name").val("");
            $(".search_status").val("");
            $(".searchDateTo").val($.datepicker.formatDate('mm/dd/yy', dateto));
            $(".searchDateFrom").val($.datepicker.formatDate('mm/dd/yy', datefrom));
        }
        if(searchtype == "divname") {
            $('.divdate').hide('slow');
            $('.divname').show('slow');
            $('.divstatus').hide('slow');
            $(".search_name").val("");
            $(".search_status").val("");
            $(".searchDateTo").val("");
            $(".searchDateFrom").val("");

        }
        if(searchtype == "divstatus"){
            $('.divdate').hide('slow');
            $('.divname').hide('slow');
            $('.divstatus').show('slow');
            $(".search_name").val("");
            $(".search_status").val("");
            $(".searchDateTo").val("");
            $(".searchDateFrom").val("");

        }
    });

    $("#search_order").click(function() {
        searchtype = $('#sosearchfilter').val();
        datefrom = formatDate($("#datefrom").val());
        dateto = formatDate($("#dateto").val());
        name = $('#search_name').val();
        status = $('#search_status').val();
        checker = 0;

        if (searchtype == "divdate") {
            if (datefrom == "" || dateto == "") {
                toastMessage('Note', 'Please fill in the Date fields.', 'info', '#FFA500');
                checker = 0;
            }
            else {
                checker = 1;
            }
        }else if (searchtype == "divname") {
            if (name == "") {
                toastMessage('Note', 'Please fill in the Name.', 'info', '#FFA500');
                checker = 0;
            }
            else {
                checker = 1;
            }
        }else if (searchtype == "divstatus") {
            if (status == "") {
                toastMessage('Note', 'Please fill in the Status Field.', 'info', '#FFA500');
                checker = 0;
            }
            else {
                checker = 1;
            }
        }


        if (checker == 1) {
            fillDatatable(searchtype, datefrom, dateto, name, status);
        }
    });

Expecting to get the right code so I can fetch the data I wanted to search

Here’s my MVC coding and wanted to show you all so you can answer me clearly been stuck here for a while and would be happy if someone could help me.