Figuring out to pass variables from one page to another

I am going through the following code of PeopleReviewPage.js file where an Ajax request is made and data is populated in the jqxgrid as shown below.
Passing url to the webservice for getting data and many other things are happening behind the scenes which I believe are not relevant to my question and hence not mentioning that. I am trying to relate the onclick
event defined in PeopleReviewPage.js page with the DocumentDetailsDialog.js page where I am performing more data related operations.

PeopleReviewPage.js

// This object is responsible for the "People review" page.
function PeopleReviewPage() {

    var self = this;

    // This maintains state after a cell is clicked and prevents double clicks from triggering an event twice.
    this.cellClicked = false;

    
    this.urlKey = "showIDNumber";
     
	// Get data related to IDNumber 
    this.getData = function (IDNumber_) {

        if (isEmpty(IDNumber_)) { alert("Invalid IDNumber in getData()"); return false; }

        // Lookup the AJAX web service URL
        var url = regman.getWebServiceURL(self.urlKey);
        if (isEmpty(url)) { alert("Invalid URL in getData()"); return false; }
       

        var ajaxRequest = jQuery.ajax({
            //beforeSend: TODO: show spinner!
            data: {
                registry_id: regman.registry.id,
                IDNumber: IDNumber_
            },
            dataType: "json",
            method: "GET",
            url: url
        })
        .done(function (data_, textStatus_, jqXHR_) {

            // Validate the web service and retrieve the status.
            if (typeof (data_) === "undefined" || data_ === null) { alert("Invalid data returned from web service"); return false; }
            if (isEmpty(data_.webservice_status) || isEmpty(data_.webservice_status.status)) { alert("Invalid web service status"); return false; }
            if (data_.webservice_status.status != "SUCCESS") { alert(data_.webservice_status.message); return false; }

			// Process and display data document data
            self.processdataDocuments(data_.data_document_list);

          

        })
        .fail(function (jqXHR_, textStatus_, errorThrown_) {
            alert("Error in getData(): " + errorThrown_);
            return false;
        });
    };


    // Initialize the page
    this.initialize = function () {

        // An IDNumber should've been provided by the page that called this page.
        var IDNumber = regman.selectedData["IDNumber"];

        if (isEmpty(IDNumber)) { alert("Invalid IDNumber provided by calling page"); return false; }

        self.getData(IDNumber);

        
    };


     // Process data document data and dynamically populate the UI.
    // Note that the "collection" parameter should correspond to data_.data_document_list. 
   
    this.processdataDocuments = function (collection_) {

       var source =
        {
            localdata: collection_,
                datatype: "array"
            };
     var dataAdapter = new $.jqx.dataAdapter(source, {
                loadComplete: function (data) { },
                loadError: function (xhr, status, error) { }
            });
     $("#dataDocumentPanel").jqxGrid(
            {
            source: dataAdapter,
            width: '1000',
                height: 150,
                columns: [
                      {
                          text: 'Type', datafield: 'nc_type'
                      },
                      {
                          text: 'SubType', datafield: 'nc_subtype'
                      },
                      {
                          text: 'Concept', datafield: 'concept_text'
                      },
                      {
                          text: 'Date', datafield: 'nc_dos'
                      }
                  ]
             });

      $("#dataDocumentPanel").on('rowclick',function(event){

           var row = event.args.rowindex;
                   
           var datarow = $("#dataDocumentPanel").jqxGrid('getrowdata', row);
           var jsonStringify = JSON.stringify(datarow,null,10);
           alert(jsonStringify); // This alert displays the JSON data in a formatted manner 
         });

    };
};

DocumentDetailsDialog.js

function DocumentDetailsDialog() {


	 var self = this;

    // This maintains state after a cell is clicked and prevents double clicks from triggering an event twice.
    this.cellClicked = false;

    this.urlKey = "showdocument";

   var peopleReviewPage = new PeopleReviewPage();

   alert(peopleReviewPage.data[5]); // this doesn't works

    // get data for second url

     this.getData = function (IDNumber_) {

        if (isEmpty(IDNumber_)) { alert("Invalid IDNumber in getData()"); return false; }

        // Lookup the AJAX web service URL
        var url = regman.getWebServiceURL(self.urlKey);
        if (isEmpty(url)) { alert("Invalid URL in getData()"); return false; }
       

        var ajaxRequest = jQuery.ajax({
            //beforeSend: TODO: show spinner!
            data: {
                registry_id: regman.registry.id,
                IDNumber: IDNumber_,
                nc_type: peopleReviewPage.data[5].nc_type
        },
            },
            dataType: "json",
            method: "GET",
            url: url
        })
        .done(function (data_, textStatus_, jqXHR_) {

            // Validate the web service and retrieve the status.
            if (typeof (data_) === "undefined" || data_ === null) { alert("Invalid data returned from web service"); return false; }
            if (isEmpty(data_.webservice_status) || isEmpty(data_.webservice_status.status)) { alert("Invalid web service status"); return false; }
            if (data_.webservice_status.status != "SUCCESS") { alert(data_.webservice_status.message); return false; }


            // Process and display data document data
           //self.processNlpDocuments(data_.nlp_document_list);
           var doc_contents = data_.note_content;
            //console.log(doc_contents);

	    })
        .fail(function (jqXHR_, textStatus_, errorThrown_) {
            alert("Error in getData(): " + errorThrown_);
            return false;
        });
    };

}

My question:

When I click on one of the row of jqxgrid, I am able to see all the information of that row in the dialog (alert(jsonStringify); defined in the PeopleReviewPage is doing that). I am getting the following information using the alert dialog (in JSON) as shown below:

"data_document_list" : [ {
    "webservice_status" : null,
    "IDNumber" : "3567973",
    "concept_id" : null,
    "concept_text" : "Multiple Distress",
    "nc_dos" : "2015-07-10",
    "nc_subtype" : "BMT",
    "nc_type" : "HTH"
    
  }

Is there a way from PeopleReviewPage.js, I can pass the nc_subtype and IDNumber related information to the DocumentDetailsDialog.js page?

For this, I created an object named peopleReviewPage in DocumentDetailsDialog.js and was trying to test using the alert(peopleReviewPage.data[5]); but it doesn’t work. Is my approach okay or do I need to follow something else? Please advise.

Do you have any suggestion related to my question?

well, JS files are not pages, so the question makes no sense. if you want to pass data to a function, you would use parameters and that function would have to use them somewhere.

Can you tell me what’s wrong with the approach I used by creating object of PeopleReviewPage.js in DocumentDetailsDialog,js ?

So the two scripts are running on separate pages, which are supposed to be opened simultaneously? In this case you could write the (stringified) data to the local storage, and listen to storage changes on that other page. Like

// script1.js
localStorage.foo = jsonStringify;

// script2.js
window.addEventListener('storage', function(event) {

  // Only respond to changes of localStorage.foo
  if (event.key === 'foo') {
    console.log(event.newValue);
  }
});

This requires both pages to be on the same domain though. Here’s a demo:

http://m3g4p0p.bplaced.net/storage1.html
http://m3g4p0p.bplaced.net/storage2.html

And as always, have a look at the MDN for details! :-)

Thanks for your reply. I will explain how the two scripts are supposed to work. Right now, 1st script is working and before writing any further code in script 2, I am trying to test in script 2 whether values from first script is arriving on script 2 or not. To be more specific about the values that I want to receive in script 2 from script 1, I must write the following in script #1 just below the alert(jsonStringify); to grab the exact values.

obj = jQuery.parseJSON(jsonStringify);
//alert("display Subtype "+obj.nc_subtype) // Works fine

So, basically, I want to show the value of obj.nc_subtype in the alert of script #2

How both scripts are supposed to work:

Script #1 has a jqxgrid with multiple rows and columns. When a user clicks on a particular row, I am grabbing all the information of that row as mentioned in the jqxgrid documentation here.

Out of all the information selected from the row , I just want to send the value of obj.nc_subtype to script 2’s alert function. I would like to make sure whether I am receiving the value in script 2 or not and hence now trying to check it with something like this :

 var peopleReviewPage = new PeopleReviewPage();
 alert (peopleReviewPage.obj.nc_subtype);

But above approach doesn’t works.

so both scripts are on the same page?

Both scripts are in same folder and are two separate files. Both are included in HTML page.

Ah okay, well this won’t work because the alert doesn’t wait until that click handler in peopleReviewPage got called. But why don’t you process the data from within the click handler in the first place?

(Whether those functions are in different files doesn’t matter BTW.)

Thinking about it, if you really have to pass data from one module to the other based on a click event (or generally access it from outside), you might use a Promise. Like (I omitted all the other stuff):

function PeopleReviewPage() {

    // Instead of assigning the data to a property of `this` directly
    // within the click handler, we'll use a Promise, so that you 
    // can wait for the data elsewhere
    this.data = new Promise(function(resolve) {

        // Within the promise we have the usual click handler
        $("#dataDocumentPanel").on('rowclick',function(event){
           var row = event.args.rowindex;
           var datarow = $(this).jqxGrid('getrowdata', row);
           var jsonStringify = JSON.stringify(datarow,null,10);
           
           // Resolve the promise when the data is available
           resolve(jsonStringify);
         });
    });
}

// Then, somewhere else
var peopleReviewPage = new PeopleReviewPage;

// Here we access the `data` property of `peopleReviewPage`
// and wait for the Promise to resolve
peopleReviewPage.data.then(function(response) {
    alert(response);
});

Disclaimer: Note that this is ES6 and may not work in every browser.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.