Need Help with onUnload=js() in php script

I need to run a javascript function after some php code without using any onclick or submit button. I am trying to use the onUnload in the body of the php program but am not having any luck. Please view the snipet. Any help would be greatly appreciated.

Note: I am harcoding the localStorage variable for testing. The plan is to capture a php $var and use it in the javascript code.

<body onUnload="vload()">
    <?php

          ... php stuff here ....

    ?>
    <script type="text/javascript" language="javascript">
       function vload(){
           localStorage.vCtr="5";
       }  
   </script>
</body>
kbiosAsked:
Who is Participating?
 
Ray PaseurConnect With a Mentor Commented:
There may be some cart-and-horse issues here, or it may just be a syntax error.  Let me try to explain.

Client server systems work like this...  A client makes a request of the server.  The request is atomic and complete.  The server prepares and sends a response that is also atomic and complete, and usually instantaneous.  Once the server response has been sent, nothing else happens on the server until it receives another request from the client.   This is called a "stateless" protocol because the server has no idea what the client is doing between requests.

In a normal HTML form processing workflow, the client makes a GET request to the server for a web page.  The web page contains the form.  The user fills in the form and clicks "submit", and the browser sends a POST request to the server with the contents of the form.  The server does whatever the form called for (maybe update a shopping cart) and sends a response page to the client.  End of round-trip.

Let's examine that first GET request.  Usually that comes about because a user typed a URL into a browser address bar.  The response from the server will be an HTML web page, perhaps containing JavaScript that will run in the client browser.  By the time that the web page is sent to the client, the PHP program script on the server has run to completion and all the information, including any PHP variables that were injected into the JavaScript are fixed values.

Now enter the JavaScript (AJAX, jQuery, whatever)... The JavaScript can take external input from the client and modify the DOM, thus changing the appearance of the information on the user's screen.  The JavaScript can make a "background" request to the server, sending an AJAX request to a script on the server.  The server treats this request just like any other client request, receiving input in the $_POST array and producing browser output that goes back to the client.  The AJAX "listener" captures the browser output and uses it to modify the DOM.  In this way, a request occurred without the apparent page load that normal HTML form submit actions show.

The original HTML string that was sent in response to the GET request is still unchanged, however the DOM has been changed by the background request.  Since I cannot do a chain-of-custody study on your data elements, I cannot know for sure where things are breaking.  But I can suggest this strategy for getting to a good design pattern.  Reduce the number of variables and the number of control structures to an absolute minimum.  Make up a simple "Hello World" exercise.  It would have a one-line form that takes user input, and that input would be a number, either 1 or 2.  The AJAX processing would send this number to the background script, and the server would reply with either "cat" or "dog."  The AJAX listener would change a <div> on the page to show 1=cat or 2=dog, and maybe issue an alert().  If you can get that working you will be well on the way to getting the whole AJAX thing under control.

Does that make sense to you?
0
 
Ray PaseurCommented:
If you want to run JS after the PHP has completed, why not just run it onLoad()?  By that time PHP has already rendered the HTML.
0
 
Kiran SonawaneProject LeadCommented:
Try

<html>
<head>
<meta http-equiv="Content-Language" content="en-gb">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Kiran Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>

<script>
$(document).ready(function(){
     
      localStorage.vCtr="5";
  });
</script>
</head>


<body onUnload="vload()">
    <?php

          ... php stuff here ....

    ?>
   
</body>

</html>

Open in new window

0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
kbiosAuthor Commented:
Perhaps it's my linear thinking that is the problem. I'm somewhat new to JS and PHP. Within the php code I am writing data to a mysql table. Within the php code I will capture the record count of the number of items loaded ($vcount).

When the PHP code is finished I want to launch the JS to load the $vcount into a localStorage variable. I am doing this very thing in another PHP, BUT the JS is getting launched via a submit button. I'm looking for a way to automatically launch the JS.
0
 
kbiosAuthor Commented:
sonawanekiran:

I tried the code but it didn't work.

Question: In this test I hardcoded the value. In your example would I be able to use the following?localStorage.vCtr = '<?php echo $vcount; ?>';

I want to put into localStorage a value from the PHP logic.
0
 
Ray PaseurCommented:
See http://www.laprbass.com/RAY_temp_kbios.php

Follow the $num variable in this script.  Is that something that helps with the design pattern?
<?php // RAY_temp_kbios.php
error_reporting(E_ALL);

// SIMULATE GETTING A NUMBER OF RECORDS FROM A DATA BASE
$num = rand(3,9);


?>
<html>
<head>
<title>kbios</title>
<script type="text/javascript" language="javascript">
function vload(){
    localStorage.vCtr="<?php echo $num; ?>";
    alert("We got <?php echo $num; ?> records!");
    return TRUE;
}
</script>
</head>
<body onLoad="vload()">
<h2>Hello World</h2>

<?php
echo "<p>This confirms that the number of records shown in the JS alert is really $num.</p>";
?>

</body>
</html>

Open in new window

0
 
kbiosAuthor Commented:
Ray:

I implemented your suggestions but it's still not working. Yes, $num helps, I am capturing $vcount that represents the number of records loaded. I had only hardcoded a vlaue for quick testing.

I am not getting any of the display messages to appear. I know the mysql code within the PHP is working because the table is getting updated but neither of the messages appear and the localStorage variable is still not getting set.

Any quick suggestions/ideas as to why the messages do not appear?
0
 
Ray PaseurCommented:
Can you echo $vcount into a JS alert like on line 15 of the snippet above?  If so you can see if the number is getting from PHP into the DOM
0
 
kbiosAuthor Commented:
Ray: No echo or alert works. Let me ask this, keep in mind I'm somewhat new to this, does it matter HOW the PHP is launched? I am using some AJAX code to pass data to the PHP in question. The code below is how the PHP is loaded and it's this PHP that I cannot get the display to work. Does this not work due to the asynchronous nature of AJAX?

Here is the code that loads the PHP. The PHP is loaded for every item in my shopping cart.

/* process localStorage items and create itemdtl*/
  for( var i = 1; i<= val; i++)
    {
        if ( localStorage["item" + i] != "X" )
           {
               $.ajax({  
                  type: "POST",  
                  url: "sendcartitem.php",
                  data: "ukey="+ localStorage.ukey + "&item="+ localStorage["item" + i] +
            "&showserver="+ localStorage.ShowServer,  
                  success: function(){
                                  $('#progress').remove();
                     $('body').append('<div id="progress">Cart Sent - Verify</div>');
                   $('body').append('<div id="rightbutton"><a    href="javascript:vupload )">Verify</a></div>');
                   $('#leftnav').remove();
                   }
             });
       }
    }
0
 
kbiosAuthor Commented:
Ray:

I appreciate the time taken to offer the detailed explanation. Parts of it make sense and other parts need to be digested more thoroughly. I will need to read and try some testing.

As I mentioned earlier I'm calling JS from PHP and writing to localStorage from a different PHP. The only differences that I see are a) the JS is being launched via a submit button and b) the PHP is not being called via ajax. One or both of those things are not allowing this to work. I'm going to have to rethink my approach. I was trying to go this route to eliminate a user step.

Anyway, Thanks for sharing your expertise.
0
 
Ray PaseurCommented:
Thanks for the points.  Are you using jQuery?  If not, have a look.  It implements many of the good parts of JavaScript.
http://docs.jquery.com/Tutorials

All the best, ~Ray
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.