Executing Javascript with Ajax requested data - A guide to making your script run smoothly

Battlefield Page

In the graphic provided, there is a battlefield page featuring 20 users. To capture and store this data in a MySQL database, I have created a JavaScript script. However, an issue arises when trying to collect data from the next page after clicking "next" to load more users.

When the Ajax call fetches the next set of 20 users, the script fails to log the new information because the page does not fully reload during an Ajax call, preventing the script from executing. Is there a method to force a page reload when clicking the Ajax link?

Below is the code snippet:

grabData(); var nav = document.getElementsByClassName('nav')[0].getElementsByTagName('td')[2].getElementsByTagName('a')[0];

 nav.addEventListener("click", function(){
      grabData();
  });

  function grabData(){
      var rows = document.getElementsByClassName('table_lines battlefield')[0].rows;
      var sendData = '';

      for(i=1; i < rows.length -1 ; i++){
          var getSid = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].getElementsByTagName('a')[0].href; 
          var statsID = getSid.substr(getSid.indexOf("=") + 1); //Grabs ID out of stats link
          var name = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].textContent.replace(/\,/g,"");
          var tff = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[3].textContent.replace(/\,/g,"");
          var rank = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[6].textContent.replace(/\,/g,"");
          var alliance = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[1].textContent.trim();
          var gold = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[5].textContent.replace(/\,/g,"");

          if(alliance == ''){
              alliance = 'None';
          }

          if(gold == '??? Gold'){
              gold = 0;
          }else{
              gold = gold.replace(/[^\/\d]/g,'');
          }
          sendData += statsID + "=" + name + "=" + tff + "=" + rank + "=" + alliance + "=" + gold + "@";
      }
      $.ajax({
          // you can use post and get:
          type: "POST",
          // your url
          url: "url",
          // your arguments
          data: {sendData : sendData},
          // callback for a server message:
          success: function( msg ){
              //alert(msg);
          },
          // callback for a server error message or a ajax error
          error: function( msg )
          {
              alert( "Data was not saved: " + msg );
          }
      });
  }

Therefore, this script fetches the information and sends it to a PHP file on the backend. When I navigate to the next page on the battlefield, I need to trigger this script again.

UPDATE: Issue Resolved. By locating the "next" anchor tag within the DOM tree, I was able to add an event listener that re-executes the JavaScript every time it is clicked.

Answer №1

Sure, you have the ability to manually trigger a page reload like this:

window.location.reload(true);

But the whole purpose of AJAX is to avoid reloading the entire page, so in some cases you'll need to write additional JavaScript to mimic the server-side code that initially generates your page.

If the code in question runs on page load using JavaScript, you can convert it into a function and then call that function again in the success handler of your AJAX request.

For more information, you can visit this Stack Overflow thread.

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

Open $_POST in a new tab that has been edited for your convenience

<form method="post" target="_blank" action="battle.php" onsubmit="window.open('battle.php','','width=700,height=500,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left=30,top=0');" > < ...

Here's a method to extract dates from today to the next 15 days and exclude weekends -Saturday and Sunday

Is there a way to generate an array of dates starting from today and spanning the next 15 days, excluding Saturdays and Sundays? For example, if today is 4/5/22, the desired array would look like ['4/5/22', '5/5/22', '6/5/22' ...

I'm encountering an issue in JavaScript while attempting to convert the following string into a JSON object. Can anyone assist in identifying the problem with this string?

How can I correct this string to make it a valid JavaScript JSON object? txt = '{"Categories" : [{"label":"petifores","id":"1"}, {"label":"wedding cake","id":"2"}, {"label":"shapes of cakes","id":"3"}, ...

Discover the best practices for implementing MongoDB's latest Schema Validation functionality within your Express.js application

Need help implementing MongoDB's Schema Validation in an Express server? While working on a simple todo app, I opted for the native MongoClient over mongoose but still require a schema for my data. According to MongoDB's documentation available ...

Integrating objects into the <select> element through the combination of C#, JavaScript, and HTML connected to a SQL

Can someone assist me in resolving this issue? I am trying to populate an HTML element with database fields using C# and JavaScript, but so far my code is not producing any output. I have also attempted to include a button that calls the "loadGrp" function ...

Customize CSS to target the first and last elements in a row using flexbox styling

I am facing a challenge in selecting the last element of the first row and the first element of the last row within a flex container. The setup involves a flex-wrap: wrap; for my flex container where all elements have flex: auto; with different sizes. Thi ...

Why is it important to avoid reassigning parameters in real-life situations? Can you provide an example of a problem that may arise from this practice?

Many inquiries focus on the best methods to follow the no-param-reassign linting rule, but there is a lack of requests to demonstrate the reasoning behind the rule. It is common to hear claims like 'Assigning values to variables defined as function p ...

Angular-Google-Maps - display issues arise when adjusting map size on mobile devices

After implementing my map, I noticed that on mobile or resolutions lower than 768px, the map renders incorrectly. It seems like all the map tiles load in the top left corner and then render correctly. Even setting the resize event did not resolve this iss ...

Why does it seem like only one div is being added?

I am facing an issue with dynamically appending multiple div elements. Despite my efforts, only one div element is showing up on the browser when I try to test the code. I have searched for similar problems but could not find any solutions. Any assistanc ...

Start CSS3 Animation Automatically

I am working on a multi-page website with a slider that includes a CSS3 animation featuring the famous rocket animation. Here is the code snippet I used: #outerspace { position: relative; height: 400px; background: #fff; color: #fff; } di ...

Should Raphael charts be rendered on the server side or should we stick with ajax and render them on the client side?

In my MVC3 application, I am utilizing the gRaphael library to draw charts by submitting input via ajax and receiving Json data in response for chart rendering. While server-side rendering is generally faster and preferred, gRaphael does not support it out ...

Dynamic scrolling feature for lists that moves horizontally

When working with a lengthy list, I encountered an issue with horizontal scrolling. It worked fine when the list was statically implemented as shown below. <div style="margin-top:100px;white-space: nowrap;"> <ul > <li style= ...

What is the method for assigning a value to a JSON object using data from another JSON object?

I am faced with the task of setting the seqNo property in one JSON object, b, based on the id from another JSON object, a. How can I achieve this? var a = [{id: "Make", seqNo: 4}, {id: "Model", seqNo: 1}, {id: "XModel", seqNo: 2 ...

What method can be used to keep Chromium open while using Puppeteer?

I am trying to figure out how to launch only one instance of Chromium from my first script and then connect to it from subsequent scripts. I am aware of the puppeteer.connect() method, but the issue is that when I start the script responsible for launching ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

Generating JSON responses using Django REST framework to facilitate table visualizations on the front end

I am facing an issue with my django-rest-framework where I am trying to display a table using the Google Chart data drawing library. However, I keep encountering an error message saying "You called the draw() method with a String rather than a DataTable or ...

Populate the dropdown menu with data from a JSON file

Recently, I created a custom JSON file and wanted to populate a select>option using this data. However, I encountered an error message saying: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/.../p ...

Steps for positioning an item above CardActionArea

I would like to figure out how to position an object above the CardActionArea. For example, if I have a button on top of the CardActionArea and click on that button, both the CardAction and Button actions will be triggered simultaneously. I want it so that ...

Tips for creating a zoomable drawing

I have been working on this javascript and html code but need some assistance in making the rectangle zoomable using mousewheel. Could someone provide guidance? var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...