javascript/html running too fast to get data from php scripts

I am working on an adobe captivate training course.  It uses javascript and is loaded via html with embedded javascript.  My company has developed jquery and javascript functions that call PHP scripts to pull employee information like employee number and name from the employee database. So that the employee does not have to type in their employee name and ID before a captivate course starts, I pull that information by calling the relevant javascript function that calls the appropriate php scripts to load several "global" javascript vaiables - these variables are displayed in the counsel "DOM" tab.  The problem I am running into is the html page continues to load before I can get the "global" variables.  For example.  I call a javascript function getEmpInfo() - which runs several php scripts to get lots of employee information - and then call alert(emp_id) and alert(emp_name); however, the html page is loaded so fast that the alert call runs before the php scripts finished - so I get nothing but blanks in the alerts.  I tried a javascript "sleep" but of course the html seems to ignore it and continues to load the page.  So interestingly enough.. sometimes the html gets the employee ID and name and runs fine, but other times gets nothing.  So is there a way I can be sure that my client side javascript gets the information it needs before starting the captivate training course - a call at the end of the html file.  I cannot do anything from the server side.

Oh.  the javascript calls for emp_id and emp_name do allow for a callback function.  So I added a callback function that contained an alert(emp_id).  It displayed a blank.  I also added a "sleep" javascript function call before the alert in the callback function to no avail.  I even set the "sleep" function to 10 seconds... did not work.
LVL 1
DCCoolBreezeAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Leonidas DosasCommented:
I think that your issue is the scope. What I mean.You fetch the database data via async function like $.get or $.ajax. You must set the html elements values inside their scope in the success method().Could you post a sample of your js script?
1
Julian HansenCommented:
I am guessing that you are using AJAX to call the server side scripts AND you are not waiting for those AJAX scripts to complete.

Your typical AJAX request looks like this

$.ajax({
   url: 'path/to/script',
   data: {some: 'value'},
   type: 'GET',
   dataType: 'JSON'
}).then(function(resp) {
   // Values are available here
})
// Values ARE NOT available here as script is still in progress

Open in new window


I would look at getEmpInfo() and see if it returns a promise that you can then wait on for the script to complete.
For example (this is for illustration I am not saying this will work for you - it depends on the implmentation)

var empinfo = getEmpInof();
empinfo.then(function(resp) {
   // runs when empinfo resolves (completes)
});

Open in new window

OR maybe getEmpInfo() provides the option for a callback
getEmpInfo(function(data) {
   // called when getEmpInfo() AJAX completes
});

Open in new window


You need to look at how getEmpInfo() is coded to determine what method to use.
1
DCCoolBreezeAuthor Commented:
Since the java functions and jqueries are company property I cannot provide those here.  That said, I can use similar examples.  So my .htm file that calls the captivate training module has a call to a company developed javascript and jquery (php) scripts.  The script I call is a getEmployeeID php script via a javascript function call before I load the captivate training module.  The javascript function call does have a callback function.  When I use the callback function, it still is not fast enough to hold off the html processing while processing the callback function so I captivate javascript does not always get the employee ID.  I have tried developing a "sleep" javascript function to slow it down, but it did not work.  That being said, sometime it does work.  Why?  who knows.  Perhaps the server is busy and slower so that the php script can complete in time for the captivate javascript to pick up the values.  So.  Is there anyway I can delay loading a html file while I wait for a php script to return a value - a php script that I cannot modify.  I have run the php script by itself - bypassing the javascript funtion and that php script will display the employee ID on a new html window.  However, I do not know how to grab that... moreover, would a javascript function grabbing that value without displaying it to a webpage still be to slow???  This I do not know!  :)

I admit I am new to javascript and php.  I do have 30 years programming experience in fortran, pascal, cobol, c, c++, oracle, sql server, visual basic, etc.  So I do understand programming but not so much web-based programming.

So teach me yodas!!!!!
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Leonidas DosasCommented:
As I understand you don't use ajax method.
0
DCCoolBreezeAuthor Commented:
Not that I know of, but I could be wrong.  The scripts I see in the shared functions/scripts are php.  I am able to load the latest jquery file, so I guess that means I can utilize ajax.  That being said, I guess I can utilize ajax if necessary, and I am more than willing to try!
0
Julian HansenCommented:
Not that I know of, but I could be wrong.
That's the only way for JavaScript to get a value from the server.

You say your lib function has a callback - if that is the case then I suspect that you are not using it as it should. Without seeing the code though we cannot really help you.

I still believe your problem is that you are processing before the AJAX completes - but to tell you how to fix that would require seeing the code. We would only need to see the JavaScript code - not the server code.
0
Olaf DoschkeSoftware DeveloperCommented:
I think that goes back to https://www.experts-exchange.com/questions/29093229/Javascript-Executing-a-PHP-function-Obtaining-the-PHP-return-value.html and now you're back to talk of PHP functions, maybe a thing of Adobe Captivate to put PHP into the mix, but it rather seems there are javascript functions wrapping the calls to the server-side PHP scripts or you indeed program something server side anyway.

Since you can't post code, it's hard to help, just two things might be of interest: A typical solution to timing problems when it comes to acting on DOM objects not there is to make use of the jQuery concept of a ready function, only starting to do code or binding events after the document state is becoming ready and what helps even without using that concept is putting Javascript code inside of the HTML body at the end of it, not
in the header part.

And actually the concept already was used in Julians and my examples within the other thread. Because the ready function is such a basic concept, that it's even not written out anymore:
$(function() {
  // Handler for .ready() called.
});

Open in new window

This is taken from https://api.jquery.com/ready/ 
My booksearch would also work without using that concept, as a) the HTML is very short and it's already sifficient the submit binding happens at the end of the body and b) the submit action only happens after you enter something and hit submit.

Doing something at first rendering always riscs DOM elements not to exist before you act on them, eg as in setting the isbn input to some ISBN number:

<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8">
	<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
	<script>$('form input[name=isbn]').val('0747532699');</script>
	<title>Book search</title>
  </head>
  <body> 
  <form name="book" action="" method="GET">
  <input type="text" name="isbn">
  <input type="submit" value="search">
  </form>
   
  <div id='bookinfo'></div>
  </html>

<script>$(function() {
  $('form').submit(function(e) {
    e.preventDefault();
    data = {
      q: 'isbn:'+this.isbn.value
    }
    $.get('https://www.googleapis.com/books/v1/volumes', data, function(resp, status, xhr) {
      //alert(status);
      if (xhr.status!=200) {
        alert('Oops something was wrong with your request, status code:'+xhr.status);
      }
	  
	  bookinfo = resp.items[0].volumeInfo;
	  $('#bookinfo').html('<p>Title: '+bookinfo['title']+'</p><p>Author(s): '+bookinfo['authors']+'</p>');
	  
    }, 'JSON');
  });
});</script>
</body>
</html>

Open in new window

This way the isbn field is kept empty, just put the following script to the end right before the </body>, and it likely works
<script>$('form input[name=isbn]').val('0747532699');</script>

Open in new window


Use this .val() call within the ready function and it surely works.

And of course you can put in the ISBN number directly into the HTML anyway.

If that turns out to be the reason or not, you'll surely stumble upon many such "mysteries", you can't just catch up with something completely new like web development, even with 30 years experience in programming overall.

As far as I understood you, you get Adobe Captivate training, or are you giving and preparing such training? If you get such training I wonder why you can't get the instructor to show a working example in conjunction with the interfacing towards your companies database query API, maybe with some PHP you or colleges prepare as example API call for that lesson, just returning a constant, for example.

Bye, Olaf.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DCCoolBreezeAuthor Commented:
Nice work Olaf.

Adobe Captivate training, documentation and support is horrible at best.  Unfortunately, it is what my company uses from creating training modules.

You are right in that I do not have web experience.  I do understand low level programming so I can to a certain extent pick up new languages with little training; however, I have found lately that most information on new languages does not really get into depth of the language but more into do this code to get that result and do that code to get this result.  For example I had to understand how to swap fortran functions into and out of 32K of memory while saving important values.  When I started programming there were no debuggers and there were NO word (16 bit at the time) boundaries for declaration statements.  One could literally declare a variable that was NOT aligned with a 16bit word boundary resulting in a invalid number - we used BYTE buffer fillers to keep variables on word boundaries!  So one had to really understand memory and processing capability of computers.  Fortunately, compilers and interrupters take care of these issues today.  That said, I learned a ton on how programs work low level.

Interestingly, I was able to figure out a solution on this issue.  I always look a ways to make code work somehow... outside the box I guess. The javascript function that calls the PHP script has a callback.  I used that callback to get DOM data loaded before the captivate page was loaded.  To do this, I put ALL of the code in the callback function!  Nothing in the HTML body...  So ALL of the adobe captivate html and javascript was moved from the HTML body to the callback.  This allows for the processing of the php scripts which loads the DOM data!

I really appreciate all the assistance all of the expert-exchange contributors have offered.

I appreciate the contributor's patience and assistance!
0
Olaf DoschkeSoftware DeveloperCommented:
The callback surely is the right place to process the result. That's the point the result arrived.

Julian explained here about a promise's .then() definition. Note promise is a term for a type of object representing the eventual completion of the asynchronous request, and that's not only a jQuery but already a JS topic, eg see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

Bye, Olaf.
0
Julian HansenCommented:
I always look a ways to make code work somehow... outside the box I guess. The javascript function that calls the PHP script has a callback.  I used that callback to get DOM data loaded before the captivate page was loaded.  To do this, I put ALL of the code in the callback function!

This is exactly what I highlighted in my posts - if you read them again you will see that I discussed the issue that you cannot use the data ANYWHERE until the AJAX request completes - which is why you have to put your processing in the callback.
1
Olaf DoschkeSoftware DeveloperCommented:
Let me also summarize a bit: In your earlier question gr8gonzo's first answer included usage of $ajax using the success attribute to set a function, Julian used .then and I used an anonymous function as the third parameter of the get call, so you've already seen three variants of callback usages and not noticed them being callbacks. On one side: Sorry for not pointing out, on the other side, once you have sample code it's easy to find reference/description at sites like https://api.jquery.com/ and https://developer.mozilla.org

You could have turned up your sleep time any way you want, the result only arrives in the callback, you're not calling a function in memory or within the same script, you're making an HTTP request and code immediately continues before a result comes back, so, for example, you can do calls in parallel and react to their results in the order they arrive in each ones callback. That's enabling parallelism in things independent from each other. Because an HTTP request does have a latency this model is chosen as the default, and that's different than in any normal code. You mainly have to get used to that "async thing".

So actually you moved to thinking inside the box, when using the callback to process the result, you were outside of the box with whatever you did first.

Bye, Olaf.
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTML

From novice to tech pro — start learning today.