Change ondblclick to onclick event when using IOS/Android etc - php

How can I change the ondblclick event to onclick event when page detects that its on IOS/Android etc. What makes it difficult is I cannot just call the ID of the element since it carry data from database to Javascript function.
Check it out.
Server-side:
<?php
echo '<table>';
while($row=mysql_fetch_array($query)){
echo '<tr><td ondblclick="sampFunc("'.$row[0].'","'.$row[1].'")">';
echo $row[0];
echo '</td></tr>';
}
echo '</table>';
?>
Client-side:
<script>
$(document).ready(function(){
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){
/* ?????????????????? */
}
});
function sampFunc(data1,data2){
//-- Something
}
</script>

I think you should re-write some of you code to make it easier to achieve what you want.
Trying to sniff the user agent isn't a great idea. Devices can change, new OS's can be launched and it requires more maintenance on your end. Feature detection is a much better approach as it covers devices now and in the future as well as minimising false positives.
The updated PHP now uses the HTML5 data-* attribute and removes the inline event:
<?php
echo '<table class="myclass">';
while($row=mysql_fetch_array($query)){
echo '<tr><td data-a="'.$row[0].'" data-b="'.$row[1].'">';
echo $row[0];
echo '</td></tr>';
}
echo '</table>';
?>
The new JS checks whether it's a touchscreen device and defines a variable touchDevice as true or false depending on which it is. This var is then used to define the event. If it's true (device is touch capable) then click is the event, otherwise it's dblclick.
The event handler now uses .on() instead of being defined inline and it makes use of the .data() function.
<script>
var touchDevice = !!('ontouchstart' in window) || !!('onmsgesturechange' in window);
$(document).ready(function(){
var dblevent = touchDevice ? 'click' : 'dblclick';
$('.myclass td').on(dblevent, function(){
var data1 = $(this).data('a'), data2 = $(this).data('b');
//-- Something
});
});
</script>
or simply use the updated PHP and the doubletap event:
$('.myclass td').on('dblclick doubletap', function(){
var data1 = $(this).data('a'), data2 = $(this).data('b');
//-- Something
});

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}
});

JQuery effect doesnt work for ajax content

I've got a table which is listing orders and I want to add the possiblity to filter results. Therefore I created a select field and an onchange effect in Jquery which is loading the same table with those filtered results into my Div. Therefore I used Ajax to update this "new Content" to my div. The problem is, that this table has several JQuery effects (for example a slide down when you click on a row) which doesn't work when the Content got created by the AjaxRequest. I have read some things already here in Stackoverflow and in other boards, but there was so many specific cases that I couldn't use any. I've heared something about a "init-function" which I need to call somewhere, so the JQuery things will also work on my Ajax generated content.
This is my Ajax Request:
$('.category').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
$.ajax({
type: "POST",
url: "includes/listorders.php",
data: "filter=" + valueSelected,
success: function( data ) {
$( "#latestOrders" ).html(data);
}
});
});
This is what my listorders.php basically returns (probably not necessary to know to fix my issue):
$filter = $_POST['filter'];
//Prepare Queries
$lastOrders = "SELECT * FROM Orders ORDER BY dateAdded DESC LIMIT 0,48";
$ps_orders = $db->query($lastOrders);
$data = $ps_orders->fetchAll();
foreach($data as $row)
{
$orderid =$row['id'];
$username = $row['name'];
$done = $row['refsDone'];
$quantity = $row['quantity'];
$running =$row['refsRunning'];
$untouched = $quantity - ($done+$running);
?>
<tr class="header mySlideToggler" data-id="<? echo $orderid ?>">
<td class="align-center">TEST<? echo $username ?></td>
<td>0 %</td>
<td>22 Aug 2014</td>
<td><? echo $done . " / " . $quantity ?></td>
<td><? echo $running ?></td>
<td><? echo $untouched ?></td>
<td>
</td>
</tr><tr style="padding: 0"><td colspan="7" style="padding: 0">
<div class="accounts" style="display: none">
</div>
</td></tr>
<?
}
?>
My Slide effect including another Ajax request for the content which should be displayed into the slided div:
// Slide effect for listing account information to an order
$('.mySlideToggler').click(function( event ){
event.preventDefault();
event.stopPropagation();
var id = $(this).data('id');
var div = $(this).closest('tr').next().find('.accounts');
$.ajax({
type: "POST",
url: "includes/listaccounts.php",
data: "orderid=" + id,
success: function( data ) {
div.html(data);
}
});
$(this).closest('tr').next().find('.accounts').slideToggle();
});
You need to make sure to use the new live version of event listeners, to work with content loaded asynchronously
$('body').on('click', '.my-class', function(){
//handle click event for .my-class here
});
The above code is not specific to your situation, since you have not posted the js code that is not working on async content. It's just a sample of how you manage live event listeners.
Specific answer after reviewing your code update:
$('body').on('click', '.mySlideToggler', function(event){
//do toggle stuff here
});
Why?
The jQuery .click does not support events happening on content loaded asynchronously. The same problem applies to using the following code:
$('.mySlideToggler').on('click', function(event){
//THIS WONT WORK WITH ASYNC CONTENT
});
This is why jQuery has allowed us to register the event on a parent element that was not loaded asynchronously and the provide a second argument to .on that tells us which child of that element to listen for as a target or said event. This works with all events, click|change|focus|blur|etc...
Why $('body')
I generally attach these live handlers to the body of the html document because the body is rarely reloaded via async content, as reloading the entire content would probably warrant a new page load, however it's not necessary to use body. You can attach to any parent element that is static on the page, including document or window
Nice to know
jQuery formerly used the method .live() which has been deprecated for a while now, I think since 1.7
I suggest you read more about the change to .live here: http://api.jquery.com/live/
I hope this has sufficiently answered your question. Let me know if you're still having trouble.
Performance Concern
Attaching the parent object of the .on event as close to the child element as possible will increase performance if you are using a large number of these events, as jQuery doesn't have to traverse as far down the DOM Tree to find the child element.
More info here: http://api.jquery.com/on/#event-performance

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

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.

Javascript function only outputs value of first check box from a PHP for loop

I have a for loop that forms a list of check boxes based on information received from a mySQL database. Below is the for loop that forms the check boxes (unnecessary code removed).
for ($i = 1; $i <= count($descriptionIDsArray); $i++) {
$statuses = mysql_fetch_assoc(mysql_query(sprintf("SELECT status, description FROM status_descriptions WHERE description_id='$i'")));
$status = $statuses["status"]; ?>
<input type="checkbox" value="<?php echo $status ?>" <?php if ($check == 1) {echo "checked='checked'";} ?> onchange="checkBox()" /><?php echo $description ?><br />
<?php } ?>
Checking or unchecking a box calls the following function:
<script type="text/javascript">
function checkBox() {
var status = $("input:checkbox").val();
document.getElementById("test").innerHTML = status;
}
</script>
The only value that I can get to appear in "test" is the value of the first check box. If I echo $status throughout the initial for loop all the values appear correctly so the problem seems to arise when the Javascript code is retrieving the corresponding value.
If you still want to keep the inline event handlers, change it to:
onclick="checkBox(this);"
And change the function to:
function checkBox(chk) {
var status = chk.value;
document.getElementById("test").innerHTML = status;
}
Note that onclick is better supported with checkboxes and radio buttons than is onchange. Also, the reason for this change I provided is because passing this to the checkBox function references the element that the click was applied to. That way, you know that inside of checkBox, the parameter chk will be the specific checkbox that just changed. Then just get the value with .value because it's a simple DOM node.
Anyways, I'd suggest using jQuery to bind the click event. Something like:
$(document).ready(function () {
$("input:checkbox").on("click", function () {
var status = this.value;
document.getElementById("test").innerHTML = status;
});
});
But you can obviously use $(this).val() instead of this.value, but why bother? If you use jQuery to bind the events, just make sure you take out the onchange/onclick inline event handler in the HTML.
You can look at why to use input:checkbox and not just :checkbox as the jQuery selector here: http://api.jquery.com/checkbox-selector/
When you do
$('input:checkbox').val();
it is returning the first input of type checkbox on your form, not necessarily the one that is clicked.
To return the one that was actually clicked, you need to do something like this:
$(document).ready(function() {
$('input:checkbox').bind('click', function() {
clickBox($(this));
});
});
function clickBox(field) {
$('#test').html(field.val());
}
if you use a jquery, why bother with inline events?
You could write that like:
$(':checkbox').change( function(){
$('#test').html( $(this).val() );
//`this` is the checkbox was changed
//for check if item is checked try:
$(this).is(':checked') // boolean
});
If you pass that code before your checkboxes are placed make sure you invoke that code when document is loaded;
$( function(){
//code from above here
});
jQuery is well documented with lots of samples.
I think you'll like it docs.jquery.com

Categories