executing javascript: link + refreshing. JS + PHP - php

OK, so how can i make this link:
"javascript:elements.setPercentage('element1','".$value."')"
execute on my page, when the page is loaded?

you can either put it in the body tag like this:
<body onload="function(){elements.setPercentage('element1','".$value."')}"
or in your javascript file:
window.onload = function(){elements.setPercentage('element1','".$value."')};
Or in jQuery
$(document).ready(function(){elements.setPercentage('element1','".$value."')});
You need to wrap it in a function because you are sending arguments

This example binds the window.onload event handler to an anonymous function. However, with this example, you can only have one handler (but as much code within it as you want).
jQuery, for example, has a more effective method called onDOMReady that you should consider.
<head>
... other stuff
<script>
window.onload = function(){
if (typeof elements == 'object' and typeof elements.setPercentage == 'function') {
elements.setPercentage('element1','<?php echo $value; ?>');
}
}
</script>
... other stuff
</head>

If you're using native JS:
<body onload="/*whatever*/">...</body>
If you're using JQuery (better cross browser support for the following):
$(document).ready(function(){/*do whatever*/})

Related

PHP Event Handlers

.net developer trying to do a php site for a friend, so far everything is going great but I was wondering if php has something like a textchanged event. Here is what I want to do, I want a drop down box to be appended with data retrieved from a database based on what the user enters in a textbox above(Using the text in the textbox as a parameter to retrieve data from a database and append it to the drop down without reloading the entire page.)
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
//Do stuff
}
The block off code above is in asp.net but i want to implement something similar in php.
That is not how php works. however you can make a ajax call like this with jquery:
<?php
//array, object or db result you use to fill your dropdown
$array = array('pipo', 'kees', 'klaas', 'klaas1', 'jan', 'meneerje', 'poep', 'hessel', 'kaas', 'ietsandersd', 'smit', 'cowoy', 'nog zo iets');
//if we want to search we search and only return the new found options
if(isset($_REQUEST['keyword'])){
$new_array = array();
foreach($array as $value){
if(strpos($value, $_REQUEST['keyword']) !== false){
$new_array[] = $value;
}
}
}
else{
$new_array = $array;
}
$options = '';
foreach($new_array as $key => $option){
$options .= "<option value='$key'>$option</option>";
}
$selectbox = "<select name='selectbox' id='drop_down'>$options</select>";
if(isset($_REQUEST['keyword'])){
echo $options;
}
else{
// with the \ we escape the "
echo "<html>
<head>
<title>ajax selectbox</title>
<script src=\"http://code.jquery.com/jquery-latest.min.js\" type=\"text/javascript\"></script>
<script type=\"text/javascript\">
$(document).ready(function () {
$('body').on('keyup', '.search', function(){
var data = $('.search').serialize();
$.post('ajax_selectbox.php', data, function (data){
$('#drop_down').html(data);
});
});
});
</script>
</head>
<body>
<input type='text' name='keyword' class='search' />
$selectbox
</body>
</html>
";
}
?>
explanation:
java script,
first we include the online jquery library, you can also download the library and include it from your own web server.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
// first we wait unit the html page is loaded
$(document).ready(function () {
//then we wait for a keyup event in the element with class="search" we use the css sector . for classes like .search
$('body').on('keyup', '.search', function(){
//when we type inside the .search textbox we serialize the element like a form would do. this takes the name and the value and puts it in a array.
var data = $('.search').serialize();
// then we post with ajax back to our php file or an other php file. its you own decision. the data variable is the serialized data form .search
$.post('ajax_selectbox.php', data, function (data){
// at least we use a calback for when the ajax event has finnest and we use the jquery html function to put the new options inside the drobbox with id="drop_down". we use the css id selector # to select the select box.
$('#drop_down').html(data);
});
});
});
</script>
note that I use jquery (and a lot of large players on the web use jquery) and if you know a little java-script the syntax can be disturbing.
In jquery we have a large set of methots we can use directly like:
$.post();
if you want to use the returned data from that function we create a calback function like:
$.post( function(param_ returned_by_parent_function){
//do stuf
});
An other way of using jquery and this is actually the idea behind it is query to a html element and then do stuff with it like this.
$('html_element_query').do_something_with_this();
of course this is just a basic basically explanation but maybe you get the idea.
You can use javascript onChange handler and send the current value to php via AJAX
https://developer.mozilla.org/en/docs/DOM/element.onchange
http://www.w3schools.com/ajax/
PHP does not know what happens on the client. If you want some events on the client to trigger actions, you have to code that yourself (usually in JavaScript).
PHP itself has no awareness of events happening on the front end. You can, however, plug the functionality (kind of) by using a mixture of Ajax and PHP. Ajax will watch for the events and PHP will process data sent to it from that Ajax.
I suggest using jQuery and checking out http://api.jquery.com/Ajax_Events/
I made a very simple PHP Event Dispatcher for myself, it is testable and has been used on my websites. If you need it, you can take a look.

executing jquery code from php

$("#bt-potrdi").click( function(e) {
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
when i click on button this jquery code is executed and works fine. Can i execute this code without click event?
I want to execute this code from php when some data is executed successfully like for example
if ($ok) {
?>
//execude ajax code
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
<?php
}
is this possible? PHP is server side code so i didn't find any good example if this is possible
Similar to the other suggestions, but this doesn't rely on having 2 copies of the same code...
if ($ok) {
?>
<script type="text/javascript">
$(function() {
$("#bt-potrdi").trigger("click");
});
</script>
<?php
If you ever change the click event handler, this will still work. This means that you won't need to make any future changes in 2 places.
If I understand the question, you want to execute some javascript on page load if $ok is true. To do that, you should be able to do something like:
if ($ok) {
?>
<script type="text/javascript">
//execute ajax code
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
EDIT: Also, e.stopPropagation(); is not going to work because e is not defined anywhere.
What happens is when your PHP script is executed, if $ok evaluates to true, then your jquery code is included in the generated document, and is omitted if it doesn't. But at this point, there is no event, so the following line will not work.
e.stopPropagation();
However, as jdwire suggested, you can wrap your javascript in a script tag, and have it executed that way, without being triggered by an event. So... like this:
<?php
if ($ok) {
?>
<script type="text/javascript">
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
?>
I would design my code so that i could add classes and set z-indexes straight up when html is rendered, but if you want to do those with jquery, jsut wrap them in <script> and $(document).ready(function({}); so they will be executed when dom is ready.
eg.
if ($ok) {
?>
//execude ajax code
<script>
$(document).ready(function{
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
</Script>
<?php
}
edit
Okay i assumed e.stopPropagation(); is set somewhere before since it was in questions example aswell. removed it for now.
You can echo out the code in <script/> tags and it will be run as JavaScript, or with the code you have, just place it between tags and it should be fine :)
But you cannot do this "live". Only when the page is requested ONCE.
You can also do it this way to pass PHP variables over to javaScript. I think it's a lot cleaner.
$check = 1;
?>
...
<script type="text/javascript">
var check = <?= $check; ?>;
...
if (check)
{
$("#bt-potrdi").trigger("click");
}

escaping greater-than and less-than in php echo inside server-side html

I'm trying to simply echo a function back to the client browser from a server php page after a selection has been made in a jQuery autocomplete box so that the function can process as needed (client-side) with the value of the autocomplete box. The autocomplete is in the php page as follows:
mypage.php
<html>
<head>
<title>Autocomplete</title>
<link href="../../jqSuitePHP/themes/redmond/jquery-ui-1.8.2.custom.css" id="skin" rel="stylesheet" type="text/css" />
<script src="../../jqSuitePHP/js/jquery-1.6.min.js" type="text/javascript"></script>
<script src="../../jqSuitePHP/js/jquery-ui-1.8.14.custom.min.js" type="text/javascript"></script>
<script>
$(function ac_boxes() {
$("#dlr").autocomplete({
source: "dlrAutocompleteSearch.php",
minLength: 2,
search : function(){$(this).addClass('ui-autocomplete-loading');},
open : function(){$(this).removeClass('ui-autocomplete-loading');},
select: function( event, ui ) {
// Here's my attempt at calling the client side 'test' function
<?php echo '<script>window[test](ui.item.value)</script>;' ?>
}
});
});
</script>
</head>
<body>
---------
</body>
</html>
But the < and > are causing a problem. If I remove the < and >, the page processes completely (without the 'select' function of course. If I add the < and >, the page does not process.
I have tried assigning the string using the php htmlentities() as such:
<?php
$val = htmlentities('<script>window[test](ui.item.value)</script>;');
echo $val;
?>
But this doesn't seem to work either.
Is my problem stemming from the php being inside of the jQuery script? If so, what is another method of calling the php from the 'select' method of autocomplete?
Thanks in advance.
I don't think this code is doing what you think it is doing; when you load the page the PHP is executed and you end up with something like this in the source code:
<script>
...
select: function( event, ui ) {
<script>window[test](ui.item.value)</script>;
}
...
</script>
Which is not correct (you don't need script tags within script tags; as you've seen it doesn't do anything but cause problems).
If you want to execute some PHP when the selection changes, you have to make another call to the server, via AJAX, submitting a form, or whatever. Something like this might be more like what you want:
select: function(event, ui) {
// send the selected value to the server for processing
$.get("processChange.php", {value: ui.item.value});
}
See the JQuery docs on $.get() for more on that.
On the other hand, if all you're trying to do is call another client-side javascript function (test, for example) with the selected value, you don't need PHP to echo anything. This ought to do the trick:
<script>
function test(args) {
// ...
}
$("#dlr").autocomplete({
// ...
select: function(event, ui) {
test(ui.item.value);
}
}
</script>
You can use < and > just like in HTML. You can also use the replace() function to find all the < and > and replace them.

PHP and jQuery function—only works once?

I have the following function. When I click the first time, it returns a random number, but all subsequent clicks always return the same number. How come it doesn't refresh?
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn-get-random-image').click(function () {
$('#my-img').attr('src', '<?php echo $pics[array_rand($pics, 1)]; ?>');
});
});
</script>
It's because you're using PHP to generate the random number, and it can't possibly be refreshed across calls to the JS function -- it's embedded in the HTML by that point.
May be you can also use live like instead of click
$(document).ready(function(){
$('#btn-get-random-image').live("click", function () {
// your works here
}
});
also check out jquery live
As others have said, you are using PHP, which is executed once on the server and sent as raw output, so the image will not change. Try this!
Edit: modified code to make it suck less.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var myPics = <?php echo json_encode($pics); ?>;
$(document).ready(function() {
$('#btn-get-random-image').click(function () {
var index;
do {
index = Math.floor(Math.random() * myPics.length);
} while ( typeof myPics[index] == 'undefined' );
$('#my-img')
.attr('src', myPics[index]);
});
});
</script>
This uses PHP's JSON encoder to dump your array to the javascript, then your function randomly selects an image from that array to display. The do/while loop might not be necessary, my testing shows a pretty good near-uniform distribution over thousands of iterations, but there it is nonetheless.
Your PHP is creating JS code, which gets sent to the browser once when the page is rendered. Each call to the JS function runs the function as it existed when the page was rendered.

javascript wont parse php html tags

php sends html strings to html via ajax wrapped in <p class="select"></p> tags, css reads class perfectly. javascript/jquery does not. javascript/jquery wont even parse <p onclick="function()"></p>. What am i doing wrong?
heres my php (sends data via ajax fine)
echo "<p class='select' onclick='populate();' >{$row['song_name']} </p>";
heres my css (works fine)
p.select{color:#fff;padding: 5px;margin:0}
p.select:hover{color:#fff;background:#f60;cursor:pointer;}
heres my javascript
method 1 jquery.
$("p .select").click(function(){
var str = $(this).val();
alert(str);
});
method 2 onclick function.
function populate()
{
alert('here')
}
neither of the two methods respond at all. Guru why is this?
$("p .select").live ( "click" , function(){
var str = $(this).text();
alert(str);
});
See
Events/live
Binds a handler to an event (like
click) for all current - and future -
matched element.
Two things:
p .select will choose <p> tags containing an element with class select. p.select selects <p class="select">.
Why not move the populate function to within the live? I suspect the jquery live (or click) removes any explicit handlers.
Try this:
$("p.select").live("click",function()
{
var str = $(this).text();
alert(str);
populate();
});
I posted a working(in Firefox) example below. I think you forgot to put the jquery method inside the onload event. Beside the other (small) bugs...
<html>
<head>
<style>
p.select{color:#fff;padding: 5px;margin:0}
p.select:hover{color:#fff;background:#f60;cursor:pointer;}
</style>
<script src="jquery-1.3.2.min(2).js" type="text/javascript"></script>
<script type="text/javascript">
function bodyOnLoad() {
//instead of "p .select" "p.select"
$("p.select").click(
function(){
//changed val() into text()
var str = $(this).text();
alert(str);
});
}
</script>
</head>
<body onload="bodyOnLoad()">
<p class='select'>Songname</p>
</body>
</html>

Categories