can’t get data from server via retrofit2

an error pops up: No value passed for parameter ‘serviceId’.

class ServicesViewModel : ViewModel() {

       private val repository = SmsRepository()
        val services = MutableLiveData<List<Service>>()
        val error = MutableLiveData<String>()
        fun loadServices() {
            viewModelScope.launch {
                try {
                  **services.value = repository.getServices()** [enter image description here][1]
                } catch (e: Exception) {
                    error.value = "Error: ${e.message}"
                }
            }
        }
    }
    class CountriesViewModel : ViewModel() {
        private val repository = SmsRepository()
        val countries = MutableLiveData<List<Country>>()
        val error = MutableLiveData<String>()
        fun loadCountries(serviceId: String) {
            viewModelScope.launch {
                try {
                    countries.value = repository.getCountries(serviceId)
                } catch (e: Exception) {
                    error.value = "Error loading countries: ${e.message}"
    }
    }

link to the entire repository:
https://github.com/Karakom/appd2/tree/master/app/src

[1]: https://i.sstatic.net/A2uJb5J8.png

Getting a error @esbuild/[email protected]: The platform “darwin” is incompatible with this module. error Found incompatible module

I have a project based in Typescript, using Quasar to create a chrome extension but when i try to run “yarn install” on my Intel Mac i get this:
error @esbuild/[email protected]: The platform “darwin” is incompatible with this module.
error Found incompatible module.

I can’t get to create the yarn-lock folder and I can’t figure out how to solve it. I’ve tried uninstalling every package, also doing a npm install and it won’t work. I also have a problem with the compiler not being able to recognize paths inside the same project folder. I have a line in the ts-configure where it says “extends: {path to an existing file}” and vscode underlines it as if the path does not exist.
what might be happening?
thanks in advance

Track changes in the Safari browser tab’s audibility property

I am writing a browser extension that allows user to control the playback of media content on a music service website. Unfortunately Safari does not support tracking changes to the audible property in an event tabs.onUpdated. Is there an alternative to this event? I’m looking for a way to track when the automatic inference engine interrupts playback on a music service website.

That you.

Javascript async click event issue

I’m bulding a website using Javascript to create some page transition effect to avoid reloading pages.

The interface of the website is divided in 2 parts. The first part is the menu that is present in all pages of the site. The second part is the main content that refreshs by loading the content of the page.

The issue is, when I have a link inside the main content main, the link doesn’t trigger the page transition. It only works with the links inside the menu.

const main = document.querySelector('.js-content');
const links = [...document.querySelectorAll('a')];

let isAnimating = false;

links.forEach(link => {
    link.addEventListener('click', async e => {
        e.preventDefault();
        if(isAnimating) return
        const url = e.target.href;
        console.log(url)
        startTransition(url);
        const pathname = new URL(url).pathname;
        history.pushState(null, '', pathname);
    })
})

window.addEventListener('popstate', e => {
    const url = window.location.pathname;
    startTransition(url)
})

const startTransition = async (url) => {
    isAnimating = true;
    const html = await fetch(url);
    const htmlString = await html.text();
    const parser = new DOMParser();
    const parsedhtml = parser.parseFromString(htmlString, 'text/html').querySelector('.js-content')

    transitionDiv.classList.add('is-animate-in');
    transitionDiv.addEventListener('transitionend', () => {
        main.innerHTML = parsedhtml.innerHTML;
        transitionDiv.classList.remove('is-animate-in');
        transitionDiv.classList.add('is-animate-out');
        setTimeout(() => {
            transitionDiv.style.transition = '0s';
            transitionDiv.classList.remove('is-animate-out');

            setTimeout(() => {
                transitionDiv.style.transition = '1s';
            }, 100)
            isAnimating = false;
        }, 1000)
    }, {once: true})
}

I tried targeting node a inside the main content, but it doesn’t seem to work neither.

main.addEventListener("click", function(e) {
    if(e.target && e.target.nodeName == "a") {
        if(isAnimating) return
        const url = e.target.href;
        console.log(url)
        startTransition(url);
        const pathname = new URL(url).pathname;
        history.pushState(null, '', pathname);
    }
});

You can reproduce the issue in this Sandbox.

How to testiampermissions with sufficient access token?

I am trying to use the GAPI to read a spreadsheet (through frontend JS) and am trying to make it so the permissions window doesn’t come up everytime the user logs in. To do this I am trying to use TestIamPermissions(), but it reponds with a 403 PERMISSION_DENIED with the reason ACCESS_TOKEN_SCOPE_INSUFFICIENT. From what I found on the web, I have to use something like https://www.googleapis.com/auth/cloudfunctions as a scope. I have done this and have authorized it on the google account, but it still returns an error.

This is the code relating to the request:

gapi.client.request({
    path: `https://cloudresourcemanager.googleapis.com/v1/projects/gamblingdatabase-455413:testIamPermissions`,
    headers: {"Authorization": "Bearer "+ACCESS_TOKEN},
    method: 'POST',
    body: {
        permissions: ["drive.files.get", "drive.files.update"]
    }
}).then(response => {
    if(response.result.permissions && response.result.permissions.includes("drive.files.get") && response.result.permissions.includes("drive.files.update")){
        SCOPES = "";
    }
});

And this is what the error repsonse is:

{
  "error": {
    "code": 403,
    "message": "Request had insufficient authentication scopes.",
    "status": "PERMISSION_DENIED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT",
        "metadata": {
          "method": "google.cloudresourcemanager.v1.Projects.TestIamPermissions",
          "service": "cloudresourcemanager.googleapis.com"
        }
      }
    ]
  }
}

All varaibles are correctly initialized and in scope. I’m very new to the Google API and networking in general and am not sure what to do.

How can I test my Django & React app with massive users efficiently?

I’m working on a Django backend and a React frontend, and I need to test my app with a large number of users.

I have used Cypress for UI testing, but it takes too much time to complete the tests I need. My goal is to test two different scenarios:

  1. First scenario (8,840 users)

    • Register a user

    • Modify user details

    • Create a contribution

  2. Second scenario (~300,000 users)

    Perform the same process as the first scenario but on a much larger scale

I’m looking for a faster and more efficient way to execute these tests.

What is the best way to filter a column containing a string array in MUI datagrid?

I have a mui datagrid with a column containing an array of strings. I want to compare this to an array of strings that the user selects from a filter list and show the row if any of the items in its array match any of the items in the selected filter array. The isAnyOf filter operator only works with an array and a single string and I’m struggling to create a new filter that works with two arrays. Is there an efficient way to compare the two arrays and apply this to the filtermodel?

How to handle the invalid date in Prime ng Calendar

After selecting the date from calendar picker, when editing/input the dates, need to handle some validation.

Below is the scenario:

Selected april 30 2025 from the picker.
Edited the date to 31st april, which is not a valid date. When doing this the value should be automatically change to May 1.
Is there any way to handle in Prime NG calendar or any customization needed.

<p-calendar [showOnFocus]="false" [(ngModel)]="newExpirationDate"(ngModelChange)="NewrowExpirationDateChange($event)" [showIcon]="true"

placeholder=”mm/dd/yyyy”>

  NewrowExpirationDateChange(event: any): void {
const formattedDate = this.datePipe.transform(event, 'MM/dd/yyyy');
 //need to handle the invalid date logic here
}

.NET MAUI WebView login – how to retrieve user email after login without external APIs

I’m building a .NET MAUI 8 app where, at startup, I show a WebView that loads an external login page (hosted on my own server). The user logs in with their email and password. After a successful login, I close the WebView and return to the main app UI.

What I need is to retrieve the email address used by the user during the login, and store it in a variable in my .NET MAUI app.

⚠️ Constraints:

I cannot use external authentication protocols like OAuth2.

I also cannot make an additional request to the backend after the login — the email must be passed directly from the WebView to the MAUI app.

The login page is under my control (I can change the frontend code).

Auto Y scale not working when zooming and panning with data update from server

I have a temperature chart, with X axis = time, and Y axis is temperature.

Because I have data collected every minutes since several years, I have a lot of data, and I don’t want to display all of them at once on the graph.

So I create a ChartJS line chart with the following characteristics :

  • By default, it displays data for the current year, aggregated per month : the chart contains a filled area between min and max values and a line for the average value during the month. So the chart contains only 12 points (one per month, with min / max / avg value).
  • when panning on the chart, the graph is updated with values coming from the server (Json data), according to the new time range.
  • when zooming, data are fetched again from the server, according to the new time range
  • if the zoomed time range is a month, data are aggregated on the server side, per days.
  • if the zoomed time range is a day, data are aggregated per hour
  • if the zoomed time range is a hour, raw data are returned without min/max aggregation.

This logic works fine, except the Y axis does not adapt the scale according to the data.

For example, yearly Y value oscillates from 7 to 33.
The chart adapt the Y scale from 5 to 35 (which is fine).
If I zoom to a day where a value is 10, without doing any panning, the scale Y adapt from 9 to 11. And zooming out from this point to the year will change the Y scale back to 5-35.

But if I zoom on a point, and I pan right/left/up/down (which is usefull to explore the graph), when I zoom out, the scale is not going back to the initial value.
So it often happens that the line is not displayed because out of range of the Y axis scale.

Is there a way to force the Y scale to adapt itself to display all data, and not having point outside of the scale ?

I tried to update chart.scales.y.min after fetching new data from the server, but after the chart.update(‘none’), the value is set again to the previous value, and scale is not changed.

Here is a sample code, with simulated data.

const PI = Math.PI;

function daysIntoYear(date) {
  return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000;
}

function secondsToDhms(seconds) {
  seconds = Number(seconds);
  var d = Math.floor(seconds / (3600 * 24));
  var h = Math.floor(seconds % (3600 * 24) / 3600);
  var m = Math.floor(seconds % 3600 / 60);
  var s = Math.floor(seconds % 60);

  var dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : "";
  var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
  var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
  var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
  return dDisplay + hDisplay + mDisplay + sDisplay;
}

function dataSimulation(from, to, grouping) {
  const timeDiff = (new Date(to) - new Date(from)) / 1000;
  console.log("fromDate=" + from + " toDate=" + to + " diff=" + secondsToDhms(timeDiff) + " group=" + secondsToDhms(grouping));
  datamapped = [];
  dataEvery = 60 * 20; // Data get every 20mn
  min = 999;
  max = -999;
  i = 0;
  sum = 0;
  for (x = new Date(from).getTime(); x <= new Date(to).getTime(); x = x + 1000 * dataEvery) {
    date = new Date(x);
    H = date.getHours();
    M = date.getMinutes();
    month = date.getMonth();
    day = date.getDate();
    nday = daysIntoYear(date);

    value = day + (H / 100) + (M / 10000); // simple simulation
    value = 20 + (10 * Math.sin(nday * (PI / 180))) + 3 * Math.sin(H * (360 / 24) * (PI / 180)); // more complex 

    sum = sum + value;
    if (value > max)
      max = value;
    if (value < min)
      min = value;
    if ((i * dataEvery) > grouping) {
      datamapped.push({
        x: new Date(x).toISOString(),
        min: min,
        max: max,
        avg: sum / i
      });
      i = 0;
      sum = 0;
      min = 999;
      max = -999;
    }
    i = i + 1;
  }
  return datamapped;
}

async function fetchData(from, to, group) {

  /**
            const response = await fetch(`data.php?from=${from}&to=${to}&sensor=OWM&grouptime=86400`);
            const data = await response.json();
            datamapped =  data.map(item => ({
                  x: item[0],
                min: item[1],
                max: item[2],
                avg: item[3]
            }));
            **/
  datamapped = dataSimulation(from, to, group);
  return datamapped;
}

var LASTUPDATETIME;
LASTUPDATETIME = new Date();
var LOCK;
LOCK = false;
async function updateData(chart) {
  difftime = (new Date().getTime() - LASTUPDATETIME.getTime());
  console.log("LOCK=" + LOCK + " difftime=" + difftime);
  if (LOCK == true) {
    if (difftime < 1000)
      return;
  }
  LOCK = true;
  //if (  difftime < 500)
  //{ // debounce
  //    console.log("too soon");
  //    return;
  //}
  const xmin = chart.scales.x.min;
  const xmax = chart.scales.x.max;
  const fromDate = new Date(xmin).toISOString();
  const toDate = new Date(xmax).toISOString();
  const timeDiff = (xmax - xmin) / 1000;
  group = 31 * 24 * 3600;
  if (timeDiff < 1 * 24 * 3600) { // <1 days, display per every minute
    group = 60;
  } else if (timeDiff < 4 * 24 * 3600) { // <4 days, display per every hours
    group = 3600;
  } else if (timeDiff < 33 * 24 * 3600) { // <1.1month, display per 4xday
    group = 4 * 3600;
  } else if (timeDiff < 4 * 31 * 24 * 3600) { // <4month, display per day
    group = 24 * 3600;
  }
  /**
            response = await fetch(`data.php?fmt=json&from=${fromDate}&to=${toDate}&sensor=OWM&grouptime=${group}`);
            data = await response.json();
            datamapped = data.map(item => ({
                  x: item[0],
                min: item[1],
                max: item[2],
                avg: item[3]
            }));
            **/
  datamapped = dataSimulation(fromDate, toDate, group);
  chart.data.datasets[0].data = datamapped;
  chart.data.datasets[1].data = datamapped;
  chart.data.datasets[2].data = datamapped;
  chart.scales.y.min = -100; // as a test, the Y axis should be at -100, but not working
  chart.update('none');
  LASTUPDATETIME = new Date();
  LOCK = false;
}

async function createChart(from, to, group) {
  const data = await fetchData(from, to, group);
  const ctx = document.getElementById('temperatureChart').getContext('2d');
  const temperatureChart = new Chart(ctx, {
    type: 'line',
    data: {
      datasets: [{
          data: data, // The three values are on the same data ? strange
          parsing: {
            yAxisKey: 'min'
          },
          fill: '+1',
          borderWidth: 0
        },
        {
          data: data, // this is strange to have the same data than the previous
          parsing: {
            yAxisKey: 'max'
          },
          borderWidth: 0
        },
        {
          data: data,
          parsing: {
            yAxisKey: 'avg'
          },
          borderColor: 'green',
          fill: false,
          borderWidth: 1
        }
      ]
    },
    options: {
      responsive: true,
      animation: false,
      elements: {
        point: {
          radius: 1
        }
      },
      scales: {
        x: {
          type: 'time',
          time: {
            tooltipFormat: 'yyyy-MM-dd HH:mm'
          },
          title: {
            display: true,
            text: 'Date/Time'
          },

        },
        y: {
          beginAtZero: false,
          title: {
            display: true,
            text: 'Temperature (°C)'
          },

        }
      },
      plugins: {
        legend: {
          display: true,
          position: 'top'
        },

        zoom: {
          pan: {
            // pan options and/or events
            enabled: true,
            onPanComplete: function({
              chart
            }) {
              updateData(chart);
            }
          },
          zoom: {
            wheel: {
              enabled: true,
            },
            pinch: {
              enabled: true
            },
            mode: 'x',
            onZoomComplete: function({
              chart
            }) {
              updateData(chart);
            }
          }
        }
      }
    }
  });
}

// Example usage
createChart('2024-01-01', '2024-12-31', 31 * 24 * 3600);
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Temperature Line Chart</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom"></script>
</head>


  <div style="width: 100%; margin: auto;">
    <canvas id="temperatureChart"></canvas>
  </div>

See the fiddle here : https://jsfiddle.net/1bnzsx5L/1/

How to make dynamic height for flatpick?

I use https://flatpickr.js.org/

My code

const datepicker = flatpickr("#datepicker", {
  inline: true,
  dateFormat: "Y-m-d",
  onMonthChange: function (selectedDates, dateStr, instance) {
    instance.set("disable", [
      function (date) {
        return date.getMonth() !== instance.currentMonth;
      }
    ]);
    updateCalendarDisplay(instance, false);
  },
  onReady: function (selectedDates, dateStr, instance) {
    updateCalendarDisplay(instance, false);
  },
  onChange: function (selectedDates, dateStr, instance) {
    updateCalendarDisplay(instance, true);
  }
});

function updateCalendarDisplay(instance, isDateChanged) {
  setTimeout(() => {
    const calendarContainer = instance.calendarContainer;
    if (!calendarContainer) return;

    const allDays = calendarContainer.querySelectorAll(".flatpickr-day");
    const rowsWithClass = calendarContainer.querySelectorAll(
      ".is-date-one-row"
    );

    let rowStart = 0;
    let rowEnd = 6;
    let isLastRowNextMonth = true;
    let totalRows = 0;

    for (let i = 0; i < allDays.length; i++) {
      const day = allDays[i];

      if (i >= rowStart && i <= rowEnd) {
        if (!day.classList.contains("nextMonthDay")) {
          isLastRowNextMonth = false;
        }
      }

      if (i === rowEnd) {
        totalRows++;

        if (isLastRowNextMonth) {
          for (let j = rowStart; j <= rowEnd; j++) {
            allDays[j].parentElement.classList.add("is-date-one-row");
          }
        } else {
          for (let j = rowStart; j <= rowEnd; j++) {
            allDays[j].parentElement.classList.remove("is-date-one-row");
          }
        }

        rowStart = i + 1;
        rowEnd = i + 7;
        isLastRowNextMonth = true;
      }
    }
  }, 10);
}
body {
  background: #000;
}

.is-date-one-row .prevMonthDay:nth-last-of-type(1),
.is-date-one-row .prevMonthDay:nth-last-of-type(2),
.is-date-one-row .prevMonthDay:nth-last-of-type(3),
.is-date-one-row .prevMonthDay:nth-last-of-type(4),
.is-date-one-row .prevMonthDay:nth-last-of-type(5),
.is-date-one-row .prevMonthDay:nth-last-of-type(6),
.is-date-one-row .prevMonthDay:nth-last-of-type(7),
.is-date-one-row .nextMonthDay:nth-last-of-type(1),
.is-date-one-row .nextMonthDay:nth-last-of-type(2),
.is-date-one-row .nextMonthDay:nth-last-of-type(3),
.is-date-one-row .nextMonthDay:nth-last-of-type(4),
.is-date-one-row .nextMonthDay:nth-last-of-type(5),
.is-date-one-row .nextMonthDay:nth-last-of-type(6),
.is-date-one-row .nextMonthDay:nth-last-of-type(7) {
  opacity: 0;
  display: none;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<input type="text" id="datepicker">

this datepicker always displays dates in 6 rows, because of this sometimes a whole row of dates of another month is displayed.

I’m trying to make it so that only the dates of the selected month are displayed. But when choosing a date (if the month consists of 5 rows instead of 6), the datepicker jumps.

Thank you, I will be glad for any help

RNEncryptedStorage is undefined in react-native-encrypted-storage

  1. Explain the Problem Clearly

I am working on a React Native project and trying to use react-native-encrypted-storage to save data securely. However, when I try to use it, I get the following error:

Error: RNEncryptedStorage is undefined

After researching, I found that Bridgeless Mode might be causing the issue. However, disabling Bridgeless Mode (export REACT_NATIVE_NO_BRIDGE=0) did not fix the problem.

As you can see in this image some error show in this import line.

enter image description here

Steps :-

Step – 1)
Installed the package using:

npm install react-native-encrypted-storage

Step – 2)
Imported it in my code:

import EncryptedStorage from "react-native-encrypted-storage";

use anywhere like:-

console.log("EncryptedStorage:", EncryptedStorage);

After completion of all step run project then show this :-

Error: RNEncryptedStorage is undefined

Here I Mention What I Tried:-

Reinstalled react-native-encrypted-storage

Ran npx react-native start --reset-cache

Rebuilt the app with npx react-native run-android

After the all my best tries stile this is not working Please give me some guidance to install and run this successfully

Simple delay(ms) in JavaScript, does it exist? [duplicate]

Surprisingly simple to word but apparently difficult to implement. Please write a function delay(ms) in JavaScript which waits given number of ms and returns control only after that.

function delay(ms) {
  // please write your code in this line, do not modify any code except this line
}

console.log("Waiting for 2 seconds...");
delay(2000); 
console.log("2 seconds have passed!");

I am aware of setTimeout but I do not want to end up with 20 opening curly brackets and 19 closing ones.

MySQL Update Query to modify a key-value in an array of objects [closed]

I have the following table:

SELECT * FROM sample;

enter image description here

In my NextJS application, I have an update API to change the visibility get of each widget in this table, which can toggle between TRUE/ FALSE.

After getting relevant details like the ‘id’ and ‘widget.id’ from the API payload, I’m struggling to update the table with the required query.

The problem/ challenge is to to update one key in the JSON type column ‘widgets‘, based on the key ‘id’, within the same JSON, for one particular row. Please note that the column ‘widget’ is an ‘ARRAY of OBJECTS’

For example, I would like to set “visibility” to FALSE in row with id=’d98a6e8v233a6qq8′, for the ‘widget’ with id=’cxvaekmjnbvkfymj’.

The key to be modified is highlighted in the image below.

enter image description here

Attempted Solution:

  1. Ran a SELECT query from my backend service to get all rows
  2. Isolated the required row using ‘id’
  3. Updated the ‘widgets’ data using standard JS array function, into a temporary variable
  4. Tried to run an update query, but failed.

Code-block given below, in my API function in my NextJS application:

try {
  const db = await pool.getConnection()
  const selectQuery = 'select * from boards where id= ?'
  const [selectRows] = await db.execute(selectQuery, [data.boardID])
  let widgetList = selectRows[0]?.widgets
  if (widgetList?.length) {
    let selectedIndex = widgetList.findIndex(
      (item) => item?.id === widgetID
    )
    widgetList[selectedIndex].visibility = false
    let widgetListString = JSON.stringify(widgetList)?.replaceAll(`"`,`'`)
    // const updateQuery = `update boards set widgets=${widgetListString} where id= ?;`
    const updateQuery = `update boards set widgets = JSON_MERGE_PATCH(COALESCE('data', "{}"), '${widgetList}') where id = ?;`
    const [updateRows] = await db.execute(updateQuery, [data.boardID])
    db.release()
    if (updateRows?.changedRows)
      return NextResponse.json({ response: { status: 'success' } })
  }

Any help/ suggestions would be really helpful.

How do I revise Ajax code from dropdown to text input?

First, apologies in advance as I am a newbie when it comes to Ajax…

I have looked at several coder sites for a working example of the code needed to process a simple text input and database response without refreshing the page. Failing to find one, I found a great example of a dropdown form that responds with a corresponding database value when I select a name from the dropdown. The sample code works great.

The problem is the number of possible selections has grown to the point the customer wants to change the field to a text input instead of a long-scrolling selection dropdown. So, I changed the input to a text input and the trigger from onchange and the code still works to bring in the value UNTIL you hit an enter key. If they hit the enter key after entering the text, the form then refreshes to a blank input field.

Here is the code example I started with:

https://www.w3schools.com/php/php_ajax_database.asp

I revised it (and the sample database table) to change from a “family” to “shipping zones”:


<html>
<head>
<script>
function showZone(str) {
  if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
  } else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("txtHint").innerHTML = this.responseText;
      }
    };
    xmlhttp.open("GET","zones.php?q="+str,true);
    xmlhttp.send();
  }
}
</script>
</head>
<body>

<form>
<select name="zipcode" onchange="showZone(this.value)">
  <option value="">Select a ZipCode:</option>
  <option value="00501">00501</option>
    <option value="00544">00544</option>
    <option value="01001">01001</option>
    <option value="01002">01002</option>
    </select>
</form>
<br>
<div id="txtHint"><b>Shipping Zone info will be listed here...</b></div>

</body>
</html>

Here is the “family.php” code:


$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123'); // Replaced with DB info
if (!$con) {
  die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE zipcode = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>ZipCode</th>
<th>Shipping Zone</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['zipcode'] . "</td>";
  echo "<td>" . $row['zone'] . "</td>";
  echo "</tr>";
}
echo "</table>";

mysqli_close($con);

The above all works perfectly. The issue is there are thousands of zip codes, and the client wants to use a text input field to allow people to type in the zip code.

So, I changed the form to this:


<form>
<input type="text" name="zipcode" onkeyup="showZone(this.value)">
</form>

The revisions work great while the user enters their zipcode, but then refreshes to a blank form (and clears the results) if the user presses their return/enter key after typing in their zipcode.

I instead need the form to process the entry, show the result and then allow the user to type another zipcode while still displaying the prior submission’s results in the DIV.

Once again, with my limited knowledge of Ajax and Javascript, I am struggling to come up with an elegant solution, and would truly appreciate either suggestions on revising the above code OR pointing me to a working example of a similar form that processes a text input without refreshing the page.

Thanks in advance!