How do I trigger a Javascript function AFTER the page loads? - php

** EDIT **
I'm afraid I wasn't in the right direction - the problem isn't what I asked about.
the Javascript works as it should, it's the PHP that doesn't show what I want it to
on the first "run" - and I'm stil not sure why.
Sorry for somewhat wasting your time...
**
I have a form that might or might not already contain data in its fields.
If a user reaches the form and he already has some data in the system,
his ID number, for instance, will appear in the ID field - and a JavaScript function running
onLoad will disable the input field and change its style:
<body onload="runFunction()">
the problem is that it seems to run before the PHP does its part,
and only if I refresh the page, the JS function does everything I want it to
(it disables and styles some other form fields that depend on a PHP condition).
Is there a way to have this JS function run AFTER the page was rendered?
I tried running this before closing the page:
<body>
...
...
<script>
runFunction();
</script>
</body>
</html>
but to no avail.
any ideas?
Thanks!
some of the relevant PHP code: [I removed id attributes to make reading easier]
<?php if ($h_phone != '' && $h_phone_pre != '') {
echo "<td class=\"input\"><input type=\"text\" id=\"new_user_home_tel\" value=\"$h_phone\" size=\"8\" maxlength=\"7\" disabled=\"disabled\" /> -
<select id=\"new_user_home_tel_pre\" disabled=\"disabled\">
<option value=\"$h_phone_pre\" selected=\"selected\"></option>";
} else {
echo '<td class="input"><input type="text" id="new_user_home_tel" size="8" maxlength="7" /> -
<select id="new_user_home_tel_pre">
<option value=" " selected="selected"></option>';
}?> <option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="08">08</option>
<option value="09">09</option>
</select>
</td>
the Javascript code just changes the style if the field isn't empty and that works,
but the PHP works only after a refresh.

Your Javascript does run after the page is loaded, the problem is elsewhere.
It must be that your server sends different HTML before and after refresh. I suggest that if you save the source of the page you get first time and compare it with the source you get after refresh. I bet you will spot the difference and that will tell you what is wrong.

JQuery does this. Anything inside the following will execute once the page is rendered:
$(document).ready(function() {
//Call your function here
});

Try the "defer" attribute.

One way is to output-buffer the page in PHP. That means everything generated goes into memory until the script finishes running and then it's all sent out at once.
Take a look at http://uk.php.net/ob_start

the non JS library answer is:
<script>
window.onload = function(){
/* do stuff */
}
</script>
However using a JS library like JQuery will take care of all those niggle cross browser bug/problems.
Your right to place your <script> blocks at the end of you body. This improves page load performance as the browser blocks when it hits a <script> block.

Definitely hacky, but you could always put a 2x2 transparent image below your form and run the function using it's onLoad. I did a similar thing on a conditionally included file so there were no errors in the case that the file wasn't included.

I'd suggest that you add your content to an output variable and than echo it at the end of the file. Ex:
...
$output .= '<body onload="runFunction();">';
while(...)
{
$output .= '...';
}
$output .= '</body>';
...
echo $output;

I'm afraid I wasn't in the right direction - the problem isn't what I asked about. the Javascript works as it should, it's the PHP that doesn't show what I want it to on the first "run" - and I'm stil not sure why. Sorry for somewhat wasting your time...

I know this is really late for this post, but the reason this isn't working is that PHP renders HTML and then you can't interact with it again (unless you can do some snazzy AJAX stuff). Point being that the JS works fine bc it is client side, PHP doesn't work bc it is server side. Hope that helps anyone else who comes here!

Related

jQuery is messing with my PHP

I have a registration form that I'm working on and it's turning out to be a pain.
I'm very new to PHP, so please cut me some slack - haha.
I installed a jQuery plugin that allowed me to make inline labels for my textboxes. I also created an error box for any errors that occur during the registration process (invalid email, etc.). Here's some of my HTML/PHP code.
<?php
if($_POST['submit'])
{
$signuperror = "Hello World";
?>
<?php if($signuperror != "") { ?>
<span id="signuperror"><?= $signuperror; ?></span>
<?php } ?>
The problem was that the "error" of "Hello World" was not displaying when I clicked the submit button on my form. I copied and pasted this code onto a test.php document and it worked fine. So I knew that it had to be from my other html code. After troubleshooting almost every line of code, I found the culprit. It turns out that the jQuery plugin initialization for the inline labels was the problem.
$(function(){
$.fn.formLabels();
$("form").submit(function(){
var formVal = $("form").serialize();
parent.$("#default div.results").html(formVal);
return false
})
});
When I deleted this, it worked just fine (without my inline labels, of course).
What could I do to make BOTH the PHP and jQuery work.
Thanks.
- Ryan
Notice the return false at the end of the $("form").submit() function. That means the jQuery function is taking the place of your form's POST action. You're not reloading the page synchronously, so you don't have any value for $_POST["submit"]. Get rid of the return false line, and see if the page reloads as you're expecting.
There are lot of things here that are going on. Need to do this step by step.
Your PHP should either use <?php format or use <? short form but to be sure i would code all in <?php so its compatible everywhere
When you need to echo or output something use <?php echo $variable; ?> rather than <?=. Not that its no good or so but it will take out any php config issues with asp style output.
First test php output then check if statement.
Jquery is not messing with your PHP. That title is just as random as my answer.

jquery to signify if an option is not selected

I would like to add a small code snip to check out whether an option is selected
This usually is easily done if the page is html, now my code snip looks something like this
echo "<td>Language</td>";
echo "<td><select id='language' name='language'>
<option value=''>Select...</option>
<option value='en_US'>English(US)</option>
<option value='en_AU'>English(AU)</option>
<option value='en_UK'>English(UK)</option>
</select><span id="info"></span>
</td>";
if it is html
<script>
$('#language').change()
{
if('Select...'==$('#language').text())
{
$('#info').html("Please select a value...");
}
}
</script>
[UPDATE]
I would like to add that the above php source code used to generate html code is put in a form tag that is
echo "<form action='checkdb.php' method='POST'>
// all above and more
</form>"
the page checkdb.php used the posted data to update database.
How can I add in the jquery code piece as mentioned in the current file (the file with the html code is being generated) ? I am thinking as people once told me that javascript can't be called in the middle of the php execution and I wonder if I may need to use ajax get function. Please offer some help. Thank you.
// Listen, and respond to, the change even on our select
$("#language").on("change", function(e){
// Set the html content of our info element
$("#info").html(function(){
// If the selected option has no value, ask to select a value
return e.target.value === "" ? "Please select a value." : "" ;
});
// Trigger upon page load
}).trigger("change");
Demo: http://jsbin.com/owaqaz/2/edit
Note the last line, $.trigger("change") - this will cause the page to immediately populate the #info element if the select element currently has no value.
Change your jQuery to:
$('#language').change(function() {
if ('Select...' == $('#language option:selected').text()) {
$('#info').html("Please select a value...");
}
});​
jsFiddle example.
Update: Or a more brief version:
jQuery:
$('#language').change(function() {
$('#info').html(('Select...' == $('#language option:selected').text()) ? "Please select a value...":"");
});​
jsFiddle example.
Sorry but what was your question?
A PHP page turns into a HTML Page after processing (a user never sees the PHP source code), and you can easily use javascript to check for the value.

How do I get dropdowns in a PHP script to submit the form on change?

Ok... First off, I know this isn't a new question.
But, for some reason none of the suggestions Google has found for me (dating back to the begining of time even) are working. So, please bear with me.
Let's say, I have a script structured something like this:
<?php
try {
print "<table><form id='menu' action='index.php' method='POST'><tr>";
print "<td>Select A Fruit</td><td><select name=fruit>
<option value=''></option>
<option value='apple'>Apple</option>
<option value='orange'>Orange</option>
<option value='pear'>Pear</option></select></td></tr>";
print "<tr><td><input type='submit' name='submit' value='Submit'></td></tr></form></table>";
if (isset($_POST['submit'])){
if (!empty($_POST['fruit'])){
//Do whatever the form is supposed to trigger.
}
else {
//Nothing selected; handle however makes sense.
}
}
}
catch(Exception $e) {die( print_r( $e->getMessage() ) );}
?>
And instead of using the button, I want it to submit the form as soon as an option is selected.
Based on my searches, the textbook answer appears to be to modify the Select tag with an onchange attribute calling a JavaScript method like so:
<select name='fruit' onchange='document.getElementById('menu').submit()'>
or the short form:
<select name='fruit' onchange='this.form.submit()'>
But here is where I'm stuck...
None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
What am I missing here?
I would get away from the dom level 0 handler and set the select's onchange handler to a function that grabs your form, and calls submit on it.
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
I'm showing you a more robust way of adding event handlers to dom elements. Instead of saying onchange="blah()" you can set up a body onload function that'll run when your dom is ready, then you can use JavaScript to add your handlers:
<body onload="init()">
function init() {
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
}
Or, you can skit the ugly <body onload="init()"> altogether and just put the code
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
in a regular script block at the bottom of your body
Your markup isn't valid, a table-element cannot have a form as child-element(wrap the form around the table)
Choose another name for the submit-button, otherwise you will receive an error in IE when calling submit()
I would suggest using an event listener rather than adding the attribute to your code. Also, it is recommended to have the static page display the submit button, and simply remove it via javascript after the page loads.
element.addEventListener Example
<script type="text/javascript">
document.getElementById("yourSelectId").addEventListener("change", function(){document.forms["yourFormId"].submit();});
</script>
To read more about element.addEventListener (esp. to see why it's important to use it), check out the article on element.addEventListener at MDN.
How javascript works in onchange attribute
But here is where I'm stuck... None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
Attributes such as onchange, onclick, etc (notice "on" at the beginning) parse the value as javascript. Ergo, that is where you are telling the browser to use javascript to make it work :)

How to transfer select value to php?

I want to display the photos according to the album selected. But, I don't want to post the page, I want to just change the div.
This is my script:
<script type="text/javascript">
function replaceContent(divName, contentS) {
document.getElementById(divName).innerHTML = <?php echo get_pictures_from_album($fb, $albums, contentS); ?>;
}
</script>
And this is the select tag that invokes it:
<select name="album" size= "1" style="width:210;" onchange="replaceContent('photos', this.options[this.selectedIndex].value);">
<?php get_albums_select_list($albums); ?>
</select>
<div id = "photos">
<?php echo get_profile_pictures($fb, $albums); ?>
</div>
I understand from a reading that I have done that the problem might be connected to javascript Vs php variable types.
Please advise.
Looks like you are looking for an AJax call to an PHP script that retrives the data for the appropriate album selected and THEN update the div with the callback function.
Ajax + PHP basics
You are mixing Clientside and Serverside Code here. The function replaceContent is called after the page (and the php code) was loaded. You would need an Ajax Call for that if you need more information about that:
Ajax Tutorials on Google
What you are doing is not possible because PHP code runs before (on the server because PHP is server-side language) javascript code.
You will have to resort ot AJAX for that.

Problem with keeping selected value in form after reloading page

I'm trying to populate a second dropdown in a dynamic way based on a previs selected dropdown.
However, I've managed to write get the page to reload when I choose anything in the dropdownbox but the chosen value isnt passed after reloading.
I have register_globals turned off (and prefer to) and i'm using the GET function to submit the form. However when I try setting values in the URL I cant get it to work.
Example: dropdown.php?area=1 still gives me a value in the dropdownbox with the default value.
What am I doing wrong? Running on a LAMP server. Apache 2.2, php 5.3.
Note: I found the php code here on the web wwich is suppose to help me pass the GET variable and select the option in the selectbox.
This is my code:
<html>
<head>
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.area.options[form.area.options.selectedIndex].value;
self.location='dropdown.php?area=' + val ;
}
</script>
</head>
</body>
<? #$area=$HTTP_GET_VARS['area']; ?>
<form action="" method="get">
<select name="area" id="area" onchange="reload(this.form)">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</form>
</body>
</html>
Also, if this could be done with POST (or equivalent function) it would be even better.
Regards.
I think you're not specifying anywhere which one of the options should be selected on page load. Depending on the value of $area, you should add something like
<option selected>1</option>
You could easily do this with a couple of lines of PHP when rendering the option nodes:
<? if $area == 1
print '<option selected>1</option>';
?>
etc.
Alternatively, you could just populate the second combo using client-side javascript eliminating the need for a page reload. If you need to do some sensitive server-side processing to calculate the value of the second combo, do it in a background AJAX call using jQuery (examples here). Postbacks for this kind of thing are kind of undesirable and old-fashioned these days.
Regarding the GET issue, if submitting the form has any side effects (eg. a change in state in the user's account, deleting something, creating a new entity) then it should definitely be a POST. Discussion here for example.

Categories