Invoke the ajax function when the page finishes loading and also when the button is

I am having an issue with displaying a report based on the election date. The function showReport() works fine when called on form load, but fails to work when called on button click.

Here are the report members:

<script>
function showReport(){
   var from = $('#from').val();
   var to = $('#to').val();
   var str = $('#str').val();
 if(from == '' && to == '')
 {
    var from = '$from';
    var to = '$to';
 }
$.ajax({
    url: "crm_data_report.php?type="+str+"&from="+from+"&to="+to,
    method: "POST",
    success: function(data) {
    console.log(data);
    var date = [];
    var value = [];
    for(var i in data)
    {
    date.push(data[i].date);
    value.push(data[i].value);
    }
    var color = Chart.helpers.color;
    var chartdata = {
    labels: date,
    datasets :
    [
    {
    label: 'Members',
    backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
    borderColor: window.chartColors.red,
    borderWidth: 1,
    data: value
    }
    ]
    };
    var ctx = $("#mycanvas");
    var barGraph = new Chart(ctx, {
    type: 'bar',
    data: chartdata
    });
    },
    error: function(data) {
    console.log(data);
    }
    });
}

The code I used to call the function on load and on button click is shown below:

<script>
$(document).ready(function(){
   showReport();
});
$('#filter').click(function(){
    showReport();
});
</script>

Answer №1

Swap out the code block with this:

$(function(){
    $('#filter').click(function(){
        showReport();
    });    
})

It's a prevalent problem where you try to attach a click event before the button is part of the DOM. In such cases, ensure to bind it only when the DOM tree is fully loaded.

Answer №2

My intuition tells me that there's no issue with your code. Would you mind giving this a shot:

<script>
$(document).ready(function(){
   displayResults();
   $('#filter').click(function(){
    displayResults();
   });
});
</script>

It could be that the DOM hasn't fully loaded (specifically the #filter element) when the click handler is being attached.

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

What could be the reason for my SQL query functioning correctly in my editor, but not in my JavaScript function?

When I run my SQL statement in my SQL editor, it works perfectly fine. However, when I try to use it in my JavaScript function, I get an error saying there is an invalid column for my client ID. function getFeedposts(data) { var limit = data.dollarLimit; ...

Manually browse through images in photoswipe by clicking on them to move to the previous or next ones

Utilizing photoswipe within my mobile app has been a seamless experience. Instead of utilizing the full screen view, we are displaying images within a target div. A new requirement was introduced to hide the built-in toolbar and incorporate arrow buttons ...

Bypassing 403 error in redux and react application

It appears that Redux or express is failing to handle an error scenario where a user updates their password using a reset password link token. https://i.sstatic.net/uo7ho.png https://i.sstatic.net/WGHdt.png An error message should be displayed as follow ...

Sails.js not triggering Ajax form action

I implemented a functionality in Sails.js to add a new customer entry into a database. Following this, I set up a form using EJS template (modeled after the signup route/form). The components involved include: Customer.js models view-create-customer.js ...

How can we efficiently generate ReactJS Router for Links and seamlessly display a unique page for each Link?

Currently, I have an array of objects named titleUrl, which contains titles and URLs retrieved from an API. To display these as links on the sidebar, I am utilizing a custom component called MenuLink. The links are generated by iterating over the keys in t ...

Tips for initiating a jQuery form submission

At this moment, the form is being submitted using the default URL. I would like it to utilize the form submit event in my JavaScript code so that it can pass the .ajaxSubmit() options. Below is the corresponding JavaScript code: $('#selectedFile&a ...

Error: Unable to locate module: Could not find '@/styles/globals.scss'

I'm encountering an error message with my import statement for the SCSS file in my _app.tsx. Can someone help me find a solution? I'm working with Next.js and have already exhausted almost every resource available online to fix this issue. ...

The difference between invoking a method directly and utilizing a function to invoke a method

Imagine we have a method inside a class that looks like this class Blog extends Component { postClicked = (id) => { this.setState({selectedPostId: id}) } render () { const newPosts = this.state.posts.map(el => { return & ...

Running Jest encounters errors when there is ES6 syntax present in the node modules of a create-react-app project

Currently, I am working on a project using create-react-app and attempting to perform unit testing on a component from office-ui-fabric-react using Jest and Enzyme. The most recent version of office-ui-fabric-react utilizes es6 syntax which is causing iss ...

Update the user information quickly

In my Express application, I have implemented several routes and a login function. Each user has a balance associated with their data, which is stored in an 'express-session'. However, when the user refreshes the page, I need the balance to be up ...

Updating Text within a Label with jQuery

Seeking assistance with a jQuery issue that I am struggling to resolve due to my limited experience. Despite attempting to search for solutions online, I have been unable to find an alternative function or determine if I am implementing the current one inc ...

Toggle class on element based on presence of class on another element

If I have 4 boxes and the user is required to choose one. I aim to assign an active class to the box that the user clicks on. However, if the user selects another box, I want to remove the class from the first clicked box and apply it to the newly clicked ...

What causes a 400 Bad Request error when attempting to send data using jQuery Ajax within the Spring framework

I am facing an issue with submitting JSON data through jQuery AJAX. I have searched for similar problems online, but none of the solutions seem to be working for me. $.ajax({ type : "POST", contentType : "applic ...

I would like to retrieve my data using my personal API and have them displayed as checkboxes

https://i.sstatic.net/qPSqe.jpgHere is an excerpt of the progress I have made main.html (it's actually a form) <div class="form-group form-check-inline"> <input class="form-check-input" type="radio" name=& ...

Having trouble getting the group hover animation to function properly in Tailwind CSS

Just starting out with tailwind css and running into a little issue. The hover animation I'm trying to apply isn't working as expected in this case. Instead of seeing the desired animated background when hovering over the group, it seems the back ...

Create a dynamic tree structure using Bootstrap Treeview and AJAX requests with jQuery and PHP

I'm currently working with Bootstrap-Treeview and I'm facing some challenges in setting the data into the Treeview using Ajax and PHP. On the server side, there is a PHP file named fetch_data.php which looks like this: <?php includ ...

Issues arise with AJAX requests while using gunicorn after logging out from the server

Over the weekend, I successfully deployed my first Django application on a VPS server. Setting up PostgreSQL, PostGIS, virtualenv, and other necessary components took some time, but I finally got the application up and running. While everything worked fin ...

How to Validate Prop Types in VueJS When Dealing With NULL and 'undefined' Values?

Despite what the official VueJS 2 documentation on prop validation says in a code example comment: // Basic type check (null and undefined values will pass any type validation) I encountered an error while testing this piece of code — could you explai ...

React js background image not filling the entire screen

Having experience with React Native, I decided to give ReactJS a try. However, I'm struggling with styling my components because CSS is not my strong suit. To build a small web application, I am using the Ant Design UI framework. Currently, I have a ...

Implementing user authentication in node.js with passport

Having trouble with a basic login system using passport. I keep getting an error when logging in with the correct credentials: Error: Express 500 TypeError - Cannot read property 'passport' of undefined Oddly enough, everything works fine when ...