In Javascript, implement a pull-to-refresh feature that keeps track of the Last

Just starting out in the world of coding, not a pro! I'm comfortable with PHP but a total beginner when it comes to Javascript.

In short, how can I store the last id variable from JSON to prevent my AJAX request from fetching content it already has?

I'm working on implementing a 'pull down to refresh' feature, making progress but I've hit a roadblock. The MySQL/PHP/AJAX part is set up correctly. I can pull down to refresh and see updates, but it keeps appending existing content.

I've tried different ways to assign variables using let, var, nothing, window.variable. Using Framework7 if that makes a difference.

Today represents the page, and highid is the highest id number returned in JSON. When the GET request is made, highid is sent to MySQL to fetch more recent data. The PHP/JSON/AJAX interaction works fine. However, I'm struggling to figure out how to save the variable for next time.

var html = '';

// Pull to refresh on Today tab
$$('.ptr-content').on('ptr:refresh', function (e) {

  setTimeout(function () {


 if (typeof today_highid === 'undefined') {
      var today_highid = 5;
    }
    app.request.json('/__php/json1.php', { article_id: today_highid }, function (data) {

      for(var i = 0; i < data['article'].length; i+=1){

         html+=
            '<div class="title-container">'+
            '<span class="title-date">Tuesday 19 March</span>'+
            '<h1>' +data['article'][i]['article_title']+ '</h1>'+
            '</div>'+
            '<a href="/single/">'+
            '<div class="card">'+
            '<img class="card-image" src="img/thumb-14.jpg" alt="">'+
            '<div class="card-infos">'+
            '<h2 class="card-title">' +data['article'][i]['article_content']+ '</h2>'+
            '<div class="card-bottom">'+
            '<div class="card-author">'+
            '<img class="card-author-image" src="img/authors/author-1.jpg" alt="">'+
            '<div>Camille Aline</div>'+
            '</div>'+
            '<div class="card-comments"><i class="f7-icons">chat_bubble_fill</i></i>' +today_highid+ '</div>'+
            '</div>'+
            '</div>'+
            '</div>'+
            '</a>';


      }
      //$$('.data-table table').html(tableHtml);
      // Prepend new list element
      $$('.ptr-content').find('#today-content').prepend(html);

      window.today_highid = data['status']['highid'];


    });

Any assistance or recommendation for a helpful tutorial would be greatly appreciated! Thank you!

Answer №1

The problem arises from the fact that you have assigned

window.today_highid = data['status']['highid'];
but later declare it as var today_highid = 5 within the function, which results in a mismatch. The variable today_highid belongs to the window object. Also, when referencing it as { article_id: today_highid }, you are essentially referring to the local scoped var instead of the value of window.today_highid.

To resolve this issue, move the initial value assignment outside of the function scope as shown below for better clarity.

Additionally, it is recommended to use let or const for block-scoped variables rather than using var. Refer to Javascript gotchas for more information.

let todayHighId = 5; //default

$$('.ptr-content').on('ptr:refresh', function (e) {

  setTimeout(function () {

    app.request.json('/__php/json1.php', { article_id: todayHighId }, function (data) {

      let { article, status } = data;
      let lastArticleId = article[article.length - 1];

      for(let i = 0; i < article.length i+=1){
       ....
      }

      todayHighId = status.highid;

    });
}

Avoid declaring variables with underscores(_) and accessing object properties using brackets([]) whenever possible, unless strictly required by the API design.

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

How do I reset and resubmit a form while utilizing Redux-Form for search filters?

New Update: Check out this Pen Example https://codepen.io/anon/pen/vwzGYY?editors=0011 Introduction After conducting my research, it appears that I may need to approach this problem from a different angle. Do you have any suggestions for me? Situation ...

challenge with altering data in transmission when using the GET method

$('.textedit').editable('/webpage/skeleton/edit_text/text/process', { loadurl: '/webpage/skeleton/edit_text/loadraw', loaddata: {id: $(this).attr('id'), client: $(this).data('client')}, submitda ...

Can you guide me on how to export a named function using module.exports?

I have a script file for my discord bot that includes a specific command and a function with parsing logic that I want to reuse in my main index.js // File: ./commands/scrumPrompt.js // The function const extractDeets = function (f, scrum) { let items ...

Searching for the object that occurs an uneven number of times

Currently, I am tackling a challenge on Codewars that requires identifying the element in an array that occurs an odd number of times. The current solution I have successfully passes 3 out of 6 tests. function findOdd(A) { //happy coding! let odd = &qu ...

What is the best way to organize search results in typeahead/bloodhound?

I am currently working with typeahead.js version 0.11.1 and attempting to customize the sorting of results retrieved from a remote source. Despite implementing code that should allow me to override the default sort function of bloodhound, my custom sort fu ...

Establish a cookie using the PHP session's username

I have successfully implemented a general cookie for a one-time use scenario. However, I now need to create a cookie based on the username so that a message is displayed only once per user. My approach involves setting up a PHP session for the username ass ...

"Enhance your data visualization with jQuery tree tables and JSON data

Currently, I am working on a tree table project where I need to convert JSON data into a tree table format. After doing some research online, I came across jQuery Treetable which seemed like a good fit for this task. I have successfully created the JSON da ...

Issues with Toggling Visibility in HTML, CSS, and Javascript

Currently, I am working on a website and following a tutorial called "Creating Slideshow using HTML, CSS, and Javascript" by W3Schools. In the project, I want to hide the thumbnail images located at the bottom and the navigation arrows initially and have t ...

Trouble with AJAX functionality post-database migration from MySQL to SQL Server (Undefined index error)

Currently, I am facing a major issue that has been occupying me for the past few days: I am in the process of migrating a database from MySQL to MS SQL Server 2012 for an existing web application. The data migration was successful and matches the old dat ...

Fb.UI Dialogs now appearing in Popups rather than an iframe (part 2)

Here is a related issue that I came across: With the assistance of OffBySome, I managed to display my FB.ui dialog boxes in an iframe rather than as pop-ups. However, now I am experiencing an issue where the dialog appears but the loading throbber continu ...

Using JavaScript to locate and emphasize specific words within a text, whether they are scattered or adjacent

I need help finding a JavaScript code for searching words in a text using a form and a search button. I found one that works for multiple words in a row, but it doesn't work if the words are mixed up. What changes should be made to fix this issue? An ...

The Ajax request fails to send the form files

I'm encountering an issue where a form isn't passing one variable. Here is my table structure: Schema::create('projects', function(Blueprint $table) { $table->increments('id'); $table->string(&apos ...

Creating a dynamic key for an object in node js using javascript

Currently, I'm trying to achieve the following: let obj = {} obj.obj1 = {'obj11':5} console.log(obj.obj1.obj11) //5 However, my aim is to dynamically define the last key of the last object. For instance, attempting something like this: ...

Encountering Internal Server Error when running Node-Express app on render.com with query parameters live

Currently, I am facing an issue while attempting to execute a live route with query using my nodejs express application on render.com. Strangely, all other routes connected to the crud operations are functioning properly except for the search filter route ...

Controlling user login sessions and cookies with angular.js is essential for ensuring secure and seamless

I have a login application where I need to implement session and cookies using angular.js. Below is the code for my login functionality. loginController.js: var loginAdmin=angular.module('Channabasavashwara'); loginAdmin.controller('log ...

What could be causing the HTML5 canvas not to show up on the screen?

<!doctype html> <html> <head> <title>Canvas test</title> </head> <body> <script type="text/javascript"> c = getElementById('canvas'); ctx = c.getContext("2d")' ctx.fillRect(10,10,10,10); </s ...

What could be causing my createElement to double in reactjs useEffect()?

My current dilemma is rather straightforward, focusing solely on the useEffect() parts without delving into the other codes. Whenever I hover over the text, my custom mouse cursor text ends up doubling. Here are the code snippets: const cursorIntro = ...

Switching Primary Menu Selection When Scrolling Through Various Menu Options

I need help with changing the active class of links on my single page scrolling website. I found some useful code snippets for smooth scrolling and updating the active class on scroll or click events: $(document).ready(function () { $(document).on(" ...

Comparing form submission with a button click to pass data using Ajax - success in one method but failure in the other

I am facing an issue with two pieces of jquery code in my Flask application. While one works perfectly, the other is not functioning as expected. Both the form and a button trigger the same function through ajax calls. Currently, for troubleshooting purpos ...

Matching request parameters with a JSON object using node.js and express framework

After uncommenting the lines, the code runs smoothly. However, whenever I enable the 'else' statement, I consistently receive a 'not found' message even when there is a match between req.params.code and data.airports[i].code. var exp ...