PHP Event Handlers - php

.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.

Related

PHP - If div has certain class then

My question is simple.
I have the following code:
<div class="last"
<?php
if hasClass(last){
echo " style='width:100%;' ";
}
?>
></div>
I know the if statement is wrong, but the idea is there. I want to know how can I check if this div has the .last class then echo something.
I've been searching around but didn't work anything (didn't find much though).
Best regards.
As already in the comments told it's possible with PHP with DOM parsers.
I'm gonna give you 2 very simple solutions which will save you a lot of work:
CSS:
<style>
.last {
width:100%;
}
</style>
jQuery:
<script type="text/javascript">
$(document).ready(function(){
if($('div').hasClass('last')){
$('div').css('width', '100%');
}
});
</script>
PHP runs on server, so it generates HTML. If you have that class="last" you don't need to check - it's part of the code....hard-coded.
But you can have some PHP variable and depending on it's place print out class and also style for that other element:
<?php
$print_last = true;
?>
...
<div <?php if ($print_last) echo 'class="last" ';
<?php
if ($print_last){
echo " style='width:100%;' ";
}
?>
></div>
But if you want to check on html element you have to do it on client side (browser) from JavaScript and jQuery can be helpful too.
It is possible to check that using PHP, however that couldn't be done easliy (you'll need to parse buffered HTML using DOM parser, then look up for divs, etc...).... Much better solution is to do that with Javascript/jQuery, using Document.getElementsByClassName() function.
Sample solution:
var elements = document.getElementsByClassName("last");
for(var i = 0; i < elements.length; i++)
{
var element = elements[i];
element.style.width = "100%";
}
#azhpo
Obviously the HTML being the front end language you have to pass the elements either through some submit button or via ajax request.
Using submit button: select the class name of div using either javascript
var className = document.getElementById("myDIV").className
document.getElementById("myHiddenField").value = className;
Now on clicking the submit button it would get submitted
Using ajax:
Again take the classname either through javascript / jquery
var className = jQuery("#myDiv").attr("class");
Now fire ajax query and send the class name to your script
jQuery.ajax({
url: 'file.php',
type: 'POST',
data: 'class='+className,
success: function(data){//do whatever you want},
error:function(){//do whatever you want}
});

get increasing variable from php to jquery

how to pass a variable to jquery with php ?
i have to call the jquery from html this is what is confusing me:
jquery:
$(document).ready(function() {
$('#pre-info').click(function() {
$('#hide').slideToggle("fast");
});
});
now i want a $i after #pre-info and after #hide.
im calling the jqueryScript like this :
thank you.
Okay, here is more code :
<?php
$i =0;
//Make some querys nd stuff
foreach ($all as $one) {
//Here the event 1 is createt but the pre info gets increased with each event listet
echo "<div class='EVENT'><div id='pre-info$i'>";
// get som other tables nd stuff
echo"</div><div id='hide$i' style='display:none;'>";
//now this part is hidden until i click on the pre-info
//hidden Stuff
$i++;
}
?>
<script type="text/javascript">
$(document).ready(function() {
$('.pre-info').click(function() {
var hiddenid=$(this).data('hiddenid');
$('#'+hiddenid).slideToggle();
});
});
</script>
it does still not work, did i miss anything?
for me it looks like pre-info in this javascript needs a reference ( $i) as well ?
maybe i just dont understand the jquery completly..
Ok so you have several hidden divs and for each one you also have a listener to toggle their visibility. The original list comes from php which in turn gets the data from a query.
You could use data attributes to link pre-infos to hidden elements:
$i =0;
foreach ($all as $one) {
echo "<div class='pre-info' data-hiddenid='hide$i'>click me</div>";
echo "<div id='hide$i' style='display:none;'> hidden stuff </div>";
$i++;
}
then you just need one listener on jQuery
jQuery(document).ready(function() {
jQuery('.pre-info').click(function() {
var hiddenid=jQuery(this).data('hiddenid');
jQuery('#'+hiddenid).slideToggle();
});
});
Hope it helps (edit, I wrapped the listener in the document ready event)
By the way, it seems to me you're reinventing the wheel. You could use jQuery UI's accordions or Bootstrap collapsibles with nice, crossbrowser transitions.
If the JS is in .php file, you can just use:
$(document).ready(function() {
$('#pre-info<?php echo $x; ?>').click(function() {
$('#hide<?php echo $x; ?>').slideToggle("fast");
});
});
Your question does not contain enough information to give you more detailed answer, I'm afraid.
you could embed the php variable you require into a hidden html attribute or a data attribute
Hidden Element HTML
<input type="hidden" id="someId" name="someName" value="<?php echo $someVariable?>"/>
Javascript
var someVar = $('#someId').val()
Data HTML
<div id="someId" data-some-var="<?php echo $someVariable?>"></div>
Javascript
var someVar = $("#someId").data("some-var")
Note that if you use data you must include the keyword "data" before whatever you decide to name the attribute

How to execute PHP code within JavaScript

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
function funk(){
alert("asdasd");
<?php echo "asdasda";?>
}
</script>
When the button is pressed I want to execute PHP code (at this point to echo asadasda)
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result class.
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser)
and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere,
then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for
applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access
to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded
into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals
var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with:
// using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
the webpage to be modified MUST be a phtml or some php file
the first thing in that file MUST be the < ? php to get the dynamic data ?>
the php data MUST contain its own css styling (if content is in a frame)
the javascript to use the dynamic data must be in this same file
and we drop in/outof PHP as necessary to access the dynamic data
Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
To be resolved: calling updateContent() with a filename and
using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
We can use php in JavaScript by creating a form element and put the action as a .php page.
Then we use JavaScript to submit that form.
EX:
<!doctype html>
<html>
<head>
<title>PHP Executed with JS</title>
</head>
<body>
<form action="phpCode.php" id="phpCode">.
</form> <!-- This is the form-->
<script>
function runPhp() {
var php =
document.getElementById("phpCode")
php.submit() //submit the form
}
</script>
</body>
The PHP file name would be phpCode.php.
In that file would be your PHP code.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Use ajax to send request and echo the response
when successfully executed. Like this:
$.get("site.com/ajax", function(status,data){
alert(status);
});
This can be achieved with jquery library.
You could run PHP at the start of the Page and grap the results from inputs
<?php
c = a * b;
?>
<input type="hidden" name="c" value="<?php c ?>"/>
<button type="submit">Submit</button>
</form>
<script>
let cValue = $('input[name="c"]').val();
alert(cValue);
</script>

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.

Submit Value With Javascript

I'm a stuck with the following function:
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
parent.removeChild($child);
}
}
</script>
x
This function deletes a child element, and its content, which works great client-side! But I am wanting to pass a value to the server, in the same instance, so the content of the element can be deleted from the mysql database too. I have no idea how to do this, so any suggestions will be very appreciated!
Notes: $child, and $parent are strings generated within the php file, that I use to give each element a unique ID.
To make your life easier, use jQuery or similar framework. Here's how you would do it in jQuery:
$(function() {
$('.delete').click(function() {
var link = $(this);
var id = link.attr('id').replace('element_', '');
$.ajax({
url: 'handler.php',
data: {
element: id
},
type: 'post',
success: function() {
link.remove();
// Or link.closest('tr').remove() if you want to remove a table row where this link is
}
});
return false;
});
});
The HTML:
Remove
And handler.php:
mysql_query("DELETE FROM `table` WHERE id = '".mysql_real_escape_string($_POST['element'])."'");
Always remember to escape database input!
If you're a total noob as you said, you probably won't understand all of this so I suggest you read something about jQuery's AJAX capabilities and about overall development using jQuery or similar JavaScript framework.
Lets say I want to delete an entity using a ID
JQUERY - $.post()
This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). Jquery post docs
On the server assuming you have an open database connection.
mysql_query("DELETE FROM TABLE WHERE ID = ".$_POST['ID']);
more on mysql_query found here
EDIT:
So the following will only remove the element when the ajax post is complete. Note the first arg is the url to the script that will take the action , second is the data to be sent, in this case the ID post value will be {child.id} and the third is a anon inline callback function that will take action to remove the element client side.
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
$.post('{URLTOSCRIPT}', 'ID=$child.id',function () { parent.removeChild($child); });
}}
</script>
When you call the function, you'd want to put your PHP variables in tags like so:
<?php echo $parent; ?>
and
<?php echo $child; ?>
In the function definition, you will want to get rid of the PHP style variables and use something like:
function removeElement(parentDiv, childDiv) {
//CODE
}

Categories