Delivery address validator using postcode

Hi, I’m using Wix Editor to add a function to my website where potential customers can enter their postcode and it will return a response letting them know if home delivery is available in their area. I’m not going to try and link it to the shopping cart yet as it seems a step above my ability for the moment.

I’ve setup the following:
input box I’ve set to text #input
submit button #button
text field to display #message

I’ve uploaded a csv files to make a collection with all our delivery locations and called that “cool2”. It has two columns - #posctode (4 digit number that’s set to a text field) and #avail - “Yes” or “No” depending on the availability of delivery.

I keep running into errors where it says my Collection doesn’t exist yet. I tried using backend code to execute the query then pull it into the front end with code on the page. This got around the collection not existing error but now I just get every postcode coming up as not available.

Any suggested code on this would be really helpful. I’ve exhausted my abilities and ChatGPT isn’t helping me much on this one…

Thanks.

What’s the current code you have written?

Are your database permissions set to Everyone?

Post a screenshot of your database field IDs from the dev side panel, like so:

The code is getting pretty complex (for me). I’ve been on google, forums and ChatGPT trying to debug it for ages and it’s getting a bit ridiculous.

Current Code Front End (Shop Wagyu page):

import { checkPostcode } from 'backend/data.jsw';

$w.onReady(function () {
    $w("#button").onClick(() => {
        let userPostcode = $w("#input").value.trim();

        if (!userPostcode) {
            $w("#message").text = "Please enter a postcode.";
            return;
        }

        checkPostcode(userPostcode)
            .then((message) => {
                $w("#message").text = message;
            })
            .catch((err) => {
                console.error("Error calling backend:", err);
                $w("#message").text = "An error occurred. Please try again later.";
            });
    });
});

Back end:

import wixData from 'wix-data';

export function checkPostcode(postcode) {
    console.log("Checking postcode:", postcode);
    
    // Clean the input postcode
    const cleanedPostcode = postcode.trim().toLowerCase();  
    console.log("Cleaned input postcode:", cleanedPostcode);  // Log cleaned input

    return wixData.query("cool2")
        .eq("postcode", cleanedPostcode)  // Match the cleaned postcode
        .limit(1)  // Limit to one result
        .find()  // Run the query
        .then((results) => {
            console.log("Query results:", results.items);  // Log query results

            if (results.items.length > 0) {
                const storedPostcode = results.items[0].postcode;  // Get the raw stored postcode
                console.log("Raw stored postcode:", storedPostcode);  // Log raw stored postcode

                // Clean the stored postcode
                const cleanedStoredPostcode = storedPostcode.trim().toLowerCase();  
                console.log("Cleaned stored postcode:", cleanedStoredPostcode);  // Log cleaned stored postcode

                let avail = results.items[0].avail.trim().toLowerCase();  // Check availability
                console.log("Availability:", avail);  // Log availability field

                // Return the appropriate message based on availability
                return avail === "yes"
                    ? "Home delivery available in this area."
                    : "Home delivery unavailable in this area. Local pickup from Sapphire City Butchery, Inverell.";
            }
            return "Postcode not found. Please check your input.";  // No matching postcode found
        })
        .catch((err) => {
            console.error("Error querying database:", err);
            return "An error occurred. Please try again later.";  // Error handling
        });
}

Thanks for your help.
Mat

Rightly so. And here’s why:

Turns out your Field ID is incorrect.

And that is just the reason why I asked for that screenshot of your fields.
If you look at it closely:

cool2 ("cool2")
    postcode ("title")
    avail ("avail")

postcode (“title”) <<< THIS RIGHT HERE is the flaw.

“postcode” is your field label. However your Field ID is still “title”.

Whereas for avail, the label and ID is the same.
And for the database itself too, i.e. cool2

This is because Title is the default column in all databases. And you have renamed it to postcode. But the way it works in Wix CMS is, when a new column is created, it’s ID remains the same. So even after renaming the column label to postcode, the field ID for that column is still title. And in Velo code, you are required to refer to fields by their ID. And since there is no such field with the ID postcode, hence the error.

Now here’s a really simplified version of it which you can call directly from the frontend. Try it out:

import wixData from 'wix-data';

$w.onReady(function () {

    $w("#button").onClick(() => {
        let userPostcode = $w("#input").value.trim().toString();
        if (userPostcode) {
         $w("#button").disable();
         $w("#message").text = "Checking postcode..."
         wixData.query("cool2")
        .eq("postcode", userPostcode) 
        .find() 
        .then((results) => {         
            $w("#button").enable();   
            if (results.items.length > 0) {              
              if (results.items[0].avail.toLowerCase() == "yes") {
                 $w("#message").text = "Home delivery available in this area.";
              } else {
                 $w("#message").text = "Home delivery unavailable in this area. Local pickup from Sapphire City Butchery, Inverell.";
              }              
            } else {
              $w("#message").text = "Home delivery unavailable in this area. Local pickup from Sapphire City Butchery, Inverell.";
            }
        })
        .catch((err) => {
             $w("#message").text = "Error checking postcode. Please try again later.";
        });        
        } else {
             $w("#message").text = "Please enter a postcode.";
        }
    });
});

P.S. Make sure there are no red lines in your code and your collection read permissions are set to Everyone.