Tips for transferring information from a search page to a hotel result display page

I am facing an issue while transferring data from the search page to the result display page: I'm in the process of developing a web application for booking hotels. It consists of two pages - hotel search and hotel result. After the user searches for a hotel on the search page, the results are supposed to be displayed on the hotel result page.

Hotel Search:

  <form >
                        <input type="text" ng-model="Cityin" required="required" placeholder="Where do you want to go?" class="input-large">
                        <input type="date" ng-model="CheckIn"  required="required" placeholder="Check In">
                        <input type="date" ng-model="CheckOut" required="required" placeholder="Check Out" >
                        <div class="selector">
                            <select class="guests-input">
                                <option value="1">1 Guests</option>
                                <option value="2">2 Guests</option>
                                <option value="3">3 Guests</option>
                                <option value="4">4 Guests</option>
                                <option value="5">5+ Guests</option>
                            </select>
                            <span class="custom-select">Guests</span>
                        </div>
                        <input type="submit" ng-click="GetHotel();" value="Search">
                    </form>

Controller JavaScript:

 $scope.GetHotel= function () {  
        alert("in");
        var date = new Date($scope.CheckIn);
        var mnth = ("0" + (date.getMonth() + 1)).slice(-2);
        var day = ("0" + date.getDate()).slice(-2);
        var CheckIn = [date.getFullYear(), mnth, day].join("-");
        var datej = new Date($scope.CheckOut);
        var mnthk = ("0" + (datej.getMonth() + 1)).slice(-2);
        var dayl = ("0" + datej.getDate()).slice(-2);
        var CheckOut = [datej.getFullYear(), mnthk, dayl].join("-");
        alert(CheckIn);
        alert(CheckOut);
        try {
      
            $http({
                method: 'POST',
                data: { CheckInCity: $scope.Cityin, CheckInDate: CheckIn, CheckOutDate: CheckOut },
                url: '/Admin/FlightDisp',
                timeout: httpTimeout,
            }).then(function successCallback(response) {              
                var json = angular.fromJson(response.data.myJsonResponse);
                if (json != null || json != "") {
                   
                    $window.location.href = '/Admin/HotelResult';
                    var hoteldat = json.data;
                    $scope.HotelDeat = hoteldat;
                  
                }               
            }, function errorCallback(response) {
                alert("error");

            });

        } catch (ex) { alert(ex); }
    }

Hotel Result Page :

<div ng-repeat="hotels in HotelDeat">
                                <div class="list-block main-block room-block">
                                    <div class="list-content">
                                        <div class="main-img list-img room-img">
                                            <a href="#">
                                                <img src="~/Content/Hotel_Result/images/available-room-1.jpg" class="img-responsive" alt="room-img">
                                            </a>
                                            <div class="main-mask" ng-repeat="prices in hotels.offers">
                                                <ul class="list-unstyled list-inline offer-price-1">
                                                    <li class="list-inline-item price">{{prices.price.total}}<span class="divider">|</span><span class="pkg">7 Nights</span></li>
                                                    <li class="list-inline-item rating">
                                                        <span><i class="fa fa-star orange"></i></span>
                                                        <span><i class="fa fa-star orange"></i></span>
                                                        <span><i class="fa fa-star orange"></i></span>
                                                        <span><i class="fa fa-star orange"></i></span>
                                                        <span><i class="fa fa-star lightgrey"></i></span>
                                                    </li>
                                                </ul>
                                            </div><!-- end main-mask -->
                                        </div><!-- end room-img -->

                                        <div class="list-info room-info">
                                            <h3 class="block-title"><a href="#">{{hotels.hotel.name}}</a></h3>
                                            <p class="block-minor">Max Guests:02</p>
                                            <p>{{hotels.hotel.description.text}}</p>
                                            <a href="#" class="btn btn-orange btn-lg">View More</a>
                                        </div>
                                    </div>
                                </div><!-- end room-block -->
                            </div>

Question: The value from var hoteldat = json.data; is supposed to appear on the hotel result page, but the data doesn't show up on the page after $window.location.href = '/Admin/HotelResult';. I'm a beginner, so any help would be greatly appreciated. Thanks in Advance

Answer №1

Check out this helpful guide on sharing data between controllers:

  1. Storing the shared data in a factory or service
  2. Keeping the shared data in the root scope
  3. Using events to update other controllers about changes to the data

In your situation, option 1 is the most likely scenario.

To implement this, create a factory service (which acts as a singleton with only one instance):

app.factory('DataHolder', function() {
  return {
    value: 0
  };
});

Inject this into both controllers. The first controller sets the data while the second retrieves it.

app.controller('ControllerOne', function($scope, DataHolder) {
  $scope.DataHolder = DataHolder;
  $scope.increment = function() {
    $scope.DataHolder.value++;
  };
});

app.controller('ControllerTwo', function($scope, DataHolder) {
  $scope.DataHolder = DataHolder;
  $scope.increment = function() {
    $scope.DataHolder.value++;
  };
});

It's important to note that we are discussing a Single Page Application (SPA). Avoid using href for navigation within the SPA; instead, utilize routing mechanisms like this, as the solution mentioned above may not work otherwise.

Answer №2

Hello Everyone, I wanted to thank you all for your input. I recently found a way to pass values from the Search page to the result page using local storage. Here is the JavaScript function I used: $scope.GetHotel = function () {

        **window.localStorage.removeItem('data');**
       
        try {

            $http({
                method: 'POST',
                data: { CheckInCity: $scope.Cityin, CheckInDate: CheckIn, CheckOutDate: CheckOut },
                url: '/Admin/FlightDisp',
                timeout: httpTimeout,
            }).then(function successCallback(response) {

            **localStorage.setItem("data", response.data.myJsonResponse);**
               $window.location.href = '/Admin/FlightResult';

            }, function errorCallback(response) {
                alert("error");

            });

In my Hotel Disp Controller, I accessed the data using the key value:

app.controller('HotelDispController', ['$scope', '$window', '$rootScope', '$http', '$location', function ($scope, $window, $rootScope, $http, $location) {
   
    **var myData = localStorage.getItem('data');**   
    var json = angular.fromJson(myData);   
    var hoteldat = json.data;  
    $scope.HotelDeat = hoteldat; 
   
}]);
  
            } catch (ex) { alert(ex); }
        }
    }]);

By deleting the data when the GetHotel function starts, it helps prevent duplicate data from being generated.

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

Having trouble getting my Sequelize model to export properly

For my school project, I am developing an e-commerce website and encountering an issue with connecting my GoogleStrategy to my SQLite database. The goal is to store user data in a table, but whenever I try to call the variable in my passport-setup file, an ...

What is the best way for a client to showcase a constantly fluctuating server-side variable's value?

On my website's homepage (index.html), I want to show a dynamic server-side global variable called serverVariable. This variable is always changing based on the node.js server-side code. However, since the client doesn't know what serverVariable ...

Using the power of jQuery, execute a function only once when the element is clicked

My goal is to use jQuery's .one method to change the color of an element only once, even if clicked again. However, I am having trouble getting it to work properly. Here is my HTML: <!DOCTYPE html> <head> <meta charset="UTF-8"& ...

Exploring the world of Django: Using model formsets with the power

I am struggling to use Ajax for submitting my zipped formsets. The code functions flawlessly without Ajax, but as soon as I try to incorporate Ajax, I encounter a ValidationError: [u'ManagementForm data is missing or has been tampered with'] Thi ...

Styling a table based on specific conditions using Angular and JavaScript

I am trying to conditionally style the text in the table based on the time elapsed since the last ping. Specifically, I want to change the color of the text from green to red once 5 minutes have passed and vice versa. <form name="myform" data-ng-submit ...

Error encountered in Jest mockImplementation: Incompatible types - 'string[]' cannot be assigned to 'Cat[]' type

Recently, I've been writing a unit test for my API using Jest and leveraging some boilerplate code. However, I hit a snag when an error popped up that left me scratching my head. Here is the snippet of code that's causing trouble: describe(' ...

Scrolling through a list of objects in a React component to display a vertical lineup of items including the name and logo

Currently, I am working on developing a vertical scrolling ticker/item list that showcases both the name and logo of each item within an array. Initially, I had set up a scrolling ticker solely with names using webkit animations on styled components. Howev ...

Issue with AngularJS form not binding to $http request

<form novalidate class="form-horizontal"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="text-capitalize"> </ ...

ng-repeat running through each digest iteration

I've been delving into the inner workings of angular 1 digest cycles and their impact on scope. In my setup, I have two controllers - one using angular material with a repeater, and the other simply responding to button clicks. To track what's ha ...

Large header picture

Instead of tiptoeing around the issue, let me just be blunt and ask: I'm curious about how they created this image header. Even after removing all javascript code and css using Chrome's property inspector, the image continued to stretch. The sty ...

Error: 'concurrently command not recognized' even though it was installed globally

I am currently facing an issue on my macOs system. Even though I have installed concurrently globally through npm, whenever I set it as a start script in my package.json file and try running npm start, I encounter the following error. concurrently - k ...

Can state be controlled by both the parent and children within the same element?

I am facing a situation where I have a component that requires updating the value from its parent, but also needs to handle user input changes without having to pass them back to the parent. See this scenario in action with this example: https://codesandbo ...

Refresh the vue-chart component in a nuxt.js application

I'm currently working on a nuxt project and I need to incorporate some charts into it. I'm using vue-chartjs as a plugin for this purpose. However, the issue I'm facing is that the chart data is fetched after the chart has already been drawn ...

Having trouble saving CustomProfile?

I have developed a unique class that extends ProfileBase: public class CustomerProfile : ProfileBase { public int CustomerID { get; set; } public string CustomerName { get; set; } public static CustomerProfile GetProfile() { ret ...

Embedded UpdatePanels trigger complete page refresh

I am encountering a problem with nested, custom user controls that are causing full page postbacks despite being enclosed within an UpdatePanel. Here is the code for the update panel: <asp:Content ID="mainContentPane" ContentPlaceHolderID="mainContent ...

Jquery ajax failing to fetch data

There is a problem with Ajax not returning any data. http://jsfiddle.net/w67C4/ $.ajax({ dataType:'jsonp', url: url, async:false, success: function(data){ getUsername = data.user.id; }, }); The data being returned i ...

Utilize a promise or await statement with a dynamically generated string variable

Currently, I am constructing a mongoose query and saving it in a variable named query. Below is the snippet of code showcasing this: let query = "Product.find(match)"; if (requestObject.query.sortBy) { query = query.concat(".", &quo ...

What is the best way to pinpoint the initial and final elements in a row of variable entries within a grid?

These are the tools currently in use: Vuejs Jquery Packery with masonry layout The project involves creating a page that pulls content from JSON and fills the homepage with posts, products, and pages in a single loop. Each object in the loop is arranged ...

Troubleshooting ASP.NET Postback Problems When Loading Dynamic Data in JQuery Dialog

I am aware that similar issues have been discussed on SO before, but none of the solutions provided have helped me with my specific problem. My project involves working with Visual Studio, ASP.NET, and C#. What I need to accomplish is as follows: I have a ...

Ways to prevent a single element from being included in the selection of the entire

Here is my question: I am facing an issue with a context menu that should only disappear when clicking outside of a specific row within that menu. The element I want to exclude, with the id "except", is buried deep within multiple parent elements in my co ...