?
Solved

Need Help with onUnload=js() in php script

Posted on 2011-10-21
11
Medium Priority
?
252 Views
Last Modified: 2012-05-12
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>
0
Comment
Question by:kbios
  • 5
  • 5
11 Comments
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37006151
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
 
LVL 17

Expert Comment

by:sonawanekiran
ID: 37006226
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
 

Author Comment

by:kbios
ID: 37006253
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:kbios
ID: 37006378
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37006714
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
 

Author Comment

by:kbios
ID: 37006910
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37006925
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
 

Author Comment

by:kbios
ID: 37007143
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
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 37007696
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
 

Author Comment

by:kbios
ID: 37007927
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37007991
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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Originally, this post was published on Monitis Blog, you can check it here . Websites are getting bigger and more complicated by the day. Video, images and custom fonts are all great for showcasing your product or service. But the price to pay in…
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses
Course of the Month13 days, 18 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question