Image Preview of search via JSON

Screenshot

Reference Code

jQuery(document).ready(function ($) {
// Define constants for URLs and Ajax 
let WPCCP_URL = wpc_courier_please_ajax_obj.WPCCP_URL;
let ajaxUrl = wpc_courier_please_ajax_obj.ajaxurl;

// Variable to hold JSON data
let postcodeData;

// Get restricted origin and destination values
var restricted_origin = wpc_courier_please_ajax_obj.restricted_origin;
var restricted_destination = wpc_courier_please_ajax_obj.restricted_destination;

// Define JSON path
let file_path = "file/australian_postcodes.json";

// Load JSON file
$.getJSON(WPCCP_URL + file_path, function (data) {
  postcodeData = data;

  // Origin input event handler
  $("#origin").on("input", function () {
    let inputElement = $(this);
    let inputText = $(this).val().toUpperCase();

    let filteredSuggestions;

    if (inputElement.val().trim() === "") {
      // Clear predictions list if input is empty
      let predictionsList = $("#citiesList");
      if (predictionsList) {
        predictionsList.remove();
      }
      return;
    } else {
      // Filter suggestions based on input and restricted origins
      filteredSuggestions = postcodeData.filter((item) => {
        return (
          item.postcode.startsWith(inputText) ||
          item.locality.startsWith(inputText)
        );
      });
      // Filter Restriction
      filteredSuggestions = filteredSuggestions.filter(
        (item) => !restricted_origin.includes(item.id.toString())
      );
      // Display filtered suggestions
      displaySuggestions(filteredSuggestions, inputElement);
    }
  });

  // Destination input event handler
  $("#destination").on("input", function () {
    let inputElement = $(this);
    let inputText = $(this).val().toUpperCase();

    if (inputElement.val().trim() === "") {
      // Clear predictions list if input is empty
      let predictionsList = $("#citiesList");
      if (predictionsList) {
        predictionsList.remove();
      }
      return;
    } else {
      // Filter suggestions based on input and restricted destinations
      let filteredSuggestions = postcodeData.filter((item) => {
        return (
          item.postcode.startsWith(inputText) ||
          item.locality.startsWith(inputText)
        );
      });
      // Filter Restriction
      filteredSuggestions = filteredSuggestions.filter(
        (item) => !restricted_destination.includes(item.id.toString())
      );
      // Display filtered suggestions
      displaySuggestions(filteredSuggestions, inputElement);
    }
  });

  // Function to display suggestions
  function displaySuggestions(suggestions, inputElement) {
    let id = inputElement.attr("id");
    let predictionsList = $("#citiesList");
    if (predictionsList) {
      predictionsList.remove();
    }

    // Hidden Input elements
    let post_code = $("#post_code_" + id);
    let selected = $("#selected_" + id);
    let state_input = $("#state_" + id);

    if (suggestions.length > 0) {
      // Create and append a new predictions list
      let newPredictionsList = document.createElement("ul");
      newPredictionsList.id = "citiesList";

      suggestions.forEach((suggestion) => {
        // Create list item for each suggestion
        let listItem = document.createElement("li");
        let icon = document.createElement("i");
        icon.className = "fas fa-map-marker";
        listItem.appendChild(icon);
        listItem.appendChild(
          document.createTextNode(
            suggestion.postcode +
              " - " +
              suggestion.locality +
              ", " +
              suggestion.state
          )
        );

        // Add click event to populate input fields
        listItem.addEventListener("click", function () {
          inputElement.val(
            suggestion.postcode + ", " + suggestion.locality
          );
          // Populate hidden input fields
          post_code.val(suggestion.postcode);
          selected.val("Australia");
          state_input.val(suggestion.state);
          newPredictionsList.remove();
        });

        newPredictionsList.appendChild(listItem);
      });

      inputElement.after(newPredictionsList);
    } else {
      predictionsList.text("No suggestions available");
    }
  }
});

    }

Image Preview of location restriction via JSON

restriction

// Event handler for input in origin postcode field
$("#origin_postcode").on("input", function () {
  let inputElement = $(this);
  let inputText = $(this).val().toUpperCase();

  let filteredSuggestions;

  if (inputElement.val().trim() === "") {
    // Clear predictions list if input is empty
    let predictionsList = $("#citiesList");
    if (predictionsList) {
      predictionsList.remove();
    }

    return;
  } else {
    // Filter suggestions based on input
    filteredSuggestions = postcodeData.filter((item) => {
      return (
        item.postcode.startsWith(inputText) ||
        item.locality.startsWith(inputText)
      );
    });

     // Display suggestions for the origin 
    displaySuggestionsRes(filteredSuggestions, inputElement);
  }
});

// Event handler for input in destination postcode field
$("#destination_postcode").on("input", function () {
  let inputElement = $(this);
  let inputText = $(this).val().toUpperCase();

  if (inputElement.val().trim() === "") {
    // Clear predictions list if input is empty
    let predictionsList = $("#citiesList");
    if (predictionsList) {
      predictionsList.remove();
    }

    return;
  } else {
    // Filter suggestions based on input
    let filteredSuggestions = postcodeData.filter((item) => {
      return (
        item.postcode.startsWith(inputText) ||
        item.locality.startsWith(inputText)
      );
    });

    // Display suggestions for the destination
    displaySuggestionsRes(filteredSuggestions, inputElement);
  }
});

// Function to display suggestions for both origin and destination
function displaySuggestionsRes(suggestions, inputElement) {
  let id = inputElement.attr("id");
  let predictionsList = $("#citiesList");
  if (predictionsList) {
    predictionsList.remove();
  }

  if (suggestions.length > 0) {
    // Create and append a new predictions list
    let newPredictionsList = document.createElement("ul");
    newPredictionsList.id = "citiesList";

    suggestions.forEach((suggestion) => {
      // Create list item for each suggestion
      let listItem = document.createElement("li");
      let icon = document.createElement("i");
      icon.className = "fas fa-map-marker";
      listItem.appendChild(icon);
      listItem.appendChild(
        document.createTextNode(
          suggestion.postcode +
            " - " +
            suggestion.locality +
            ", " +
            suggestion.state
        )
      );

      // Add click event to save suggestion and clear input
      listItem.addEventListener("click", function () {
        // Save function
        SaveToOption(suggestion.id, id);
        newPredictionsList.remove();
        inputElement.val("");
      });

      newPredictionsList.appendChild(listItem);
    });

    inputElement.after(newPredictionsList);
  } else {
    predictionsList.text("No suggestions available");
  }
}

// Function to save suggestion to option via AJAX
function SaveToOption(ID, elementId) {
  let ajaxData = {
    action: "restricted_location",
    DataID: ID,
    elementId: elementId,
  };
  $.ajax({
    method: "post",
    url: ajaxUrl,
    data: ajaxData,

    success: function (response) {
      console.log(response);
      window.location.reload();
    },
  });
}

// Click event handler for deleting a location via AJAX
$(this).on("click", ".delete-location", function (e) {
  e.preventDefault();
  let ID = $(this).data("id");
  let elementId = $(this).closest("div").attr("class");
  let deleteElement = $(this).attr("class");

  if (elementId) {
    let ajaxData = {
      action: "restricted_location",
      DataID: ID,
      elementId: elementId,
      delete: deleteElement,
    };
    $.ajax({
      method: "post",
      url: ajaxUrl,
      data: ajaxData,

      success: function (response) {
        console.log(response);
        window.location.reload();
      },
    });
  }
});

// Click event handler for removing a location via AJAX
$(this).on("click", ".remove-location", function (e) {
  e.preventDefault();

  let div = $(this).parent();
  let elementId = div.attr("class");
  let table = div.find("table");
  let checkElement = table.find(
    "input[type='checkbox']:checked:not(#wpc_all_location)"
  );
  let data = [];

  checkElement.each(function () {
    let value = $(this).attr("val");
    data.push(value);
  });

  let ajaxData = {
    action: "bult_delete_location",
    elementId: elementId,
    dataIDs: {
      data: data,
    },
  };

  $.ajax({
    method: "post",
    url: ajaxUrl,
    data: ajaxData,

    success: function (response) {
      console.log(response);
      window.location.reload();
    },
  });
});

// Change event handler for selecting/deselecting all locations
$(this).on("change", "#wpc_all_location", function (e) {
  e.preventDefault();
  let table = $(this).closest("table");
  let checkElement = table.find("input[type='checkbox']");

  if ($(this).is(":checked")) {
    checkElement.prop("checked", true);
  } else {
    checkElement.prop("checked", false);
  }
});
*****************************************  AJAX ****************************************************
 
// Callback function for adding or removing a location to/from the restricted list 
function restricted_location_callback() {
    $ID = $_POST["DataID"];
    $elementID = $_POST["elementId"];
    $deleteElement = $_POST["delete"];
    $updated_data = array();

    $data_id = array(
        $ID => $ID
    );

    // Check if the option exists
    if (false === get_option('restricted_location_'.$elementID.'')) {
        // If the option doesn't exist, create it and add the current data ID
        add_option('restricted_location_'.$elementID.'', $data_id);
    }

    // Retrieve the existing serialized data
    $retrieved_data = get_option('restricted_location_'.$elementID.'');

    if (!in_array($ID, $retrieved_data)) {
        // If the ID is not in the list, add it
        $updated_data = array_merge($data_id, $retrieved_data );
        
        // Update the option with the updated data
        update_option('restricted_location_'.$elementID.'', $updated_data);

        wp_send_json($ID." update successfully");
    } 
    else {
        // If the ID is already in the list
        $index = array_search($ID, $retrieved_data);
        if ($index !== false && $deleteElement == "delete-location") {
            // Remove the ID if it's in the list and delete-action is specified
            unset($retrieved_data[$index]);

            // Update the option with the updated data (ID removed)
            update_option('restricted_location_'.$elementID.'', $retrieved_data);

            wp_send_json($ID." successfully removed");
        } else {
            // ID is already in the list, and no delete-action specified
            wp_send_json($ID." already in the list");
        }
    }

    wp_die();
}

// Hook to handle AJAX requests for adding or removing locations
add_action( 'wp_ajax_nopriv_restricted_location', 'restricted_location_callback' );
add_action( 'wp_ajax_restricted_location', 'restricted_location_callback' );

// Callback function for bulk deleting locations
function bult_delete_location_callback() {
    $dataIDs = $_POST["dataIDs"];
    $elementId = $_POST["elementId"];

    // Retrieve the existing serialized data
    $retrieved_data = get_option('restricted_location_' . $elementId); 

    // Remove elements in $dataIDs from $retrieved_data
    if(!empty($retrieved_data)) {
        $filteredData = array_values(array_diff($retrieved_data, $dataIDs['data']));

        // Update the option with the filtered data (IDs removed)
        update_option('restricted_location_' . $elementId, $filteredData);

        wp_send_json("Remove successfully");
    } else {
        wp_send_json("Failed removing data");
    }

    wp_die();
}

// Hook to handle AJAX requests for bulk deleting locations
add_action( 'wp_ajax_nopriv_bult_delete_location', 'bult_delete_location_callback' );
add_action( 'wp_ajax_bult_delete_location', 'bult_delete_location_callback' );