Page with mutable checkbox - php

I have a page with 12 check boxes one ever hr, the display OK, Trying to on change event to run on each
I can add 24 of them but looking for a better way this is what I have tried and does not work.
<script>
$(document).ready(function(e) {
var i = 0;
while ( i < 23)
{
$('#' + i).change(function(){
if( $('#'+ i).prop('checked') )
{checkboxstatus = "YES";}
else
{checkboxstatus = "NO";}
$.ajax({
type: "POST",
url: "timepost.php",
data: {checkbox: i ,user: <?php echo $iduser; ?>, checkboxstatus: checkboxstatus},
})
//.done(function(data, textStatus, jqXHR){alert(textStatus);})
//.fail(function(jqXHR, textStatus, errorThrown){alert(jqXHR+"--"+textStatus+"--"+errorThrown);});
});//end change
i++;
}
});//end ready
</script>
<?php include 'footer.php'; ?>
</body>
</html>
<?php
function tr($row,$hr)
{
if ($row)
{
$checked = "checked";
}
else
{
$checked = "";
}
print ("<td><input type=\"checkbox\" id=\"" . $hr . "\" name=\"" . $hr . "\" " . $checked . "></td>\r\n");
}
?>

There is no need to do a while loop here, jQuery can find all elements for you. Attached code should work
<script>
$(document).ready(function(e) {
// jQuery will find all elements with class checbox-class
$('.checkbox-class').on('change', function(){
if ($(this).prop('checked')) {
checkboxstatus = "YES";
} else {
checkboxstatus = "NO";
}
$.ajax({
type: "POST",
url: "timepost.php",
data: {checkbox: $(this).attr('id') ,user: <?php echo $iduser; ?>, checkboxstatus: checkboxstatus},
})
//.done(function(data, textStatus, jqXHR){alert(textStatus);})
//.fail(function(jqXHR, textStatus, errorThrown){alert(jqXHR+"--"+textStatus+"--"+errorThrown);});
});//end change
});//end ready
</script>
<?php include 'footer.php'; ?>
</body>
</html>
<?php
function tr($row,$hr)
{
if ($row)
{
$checked = "checked";
}
else
{
$checked = "";
}
print ("<td><input type=\"checkbox\" class=\"checkbox-class\" id=\"" . $hr . "\" name=\"" . $hr . "\" " . $checked . "></td>\r\n");
}
?>

Related

Add PHP IF statement inside dynamic php stylesheet

I have some checkboxes, that when checked adds their respective classes to the <body> element via Ajax:
<input type="checkbox" name="<?php echo $opt;?>" class="onoffswitch-checkbox" id="myonoffswitch-<?php echo $n;?>" value="true"<?php echo (dh_switch_setting_get($opt, '0') == '0' ? "" : " checked='checked'");?> />
<label class="onoffswitch-label" for="myonoffswitch-<?php echo $n;?>" data-class="<?php echo $obj['class'];?>"></label>
(function($) {
$(function() {
$("LABEL[for^=myonoffswitch]")
.each(function() {
// ---Which label was clicked? ---
var which = $(this).attr("for");
var cls = $(this).data("class");
if ( $("INPUT[id=" + which + "]").is(":checked") ) {
$("BODY").addClass(cls);
} else {
$("BODY").removeClass(cls);
}
$(this).parents(".onoffswitch").on("click", function() {
if (!$("INPUT[id=" + which + "]").is(":checked")) {
$("BODY").addClass(cls);
} else {
$("BODY").removeClass(cls);
}
var val = $("INPUT[id=" + which + "]").is(":checked") ? "1" : "0";
console.info("Set " + which + " to " + val)
$.ajax({
url: './',
type: "POST",
data: $("INPUT[id=" + which + "]").attr("name") + "=" + val + "&<?php echo MD5("DH");?>=1",
success: function (response) {
},
error: function (jqXhr, e, responseText) {
console.log(arguments);
alert("Oops. Something went wrong: " + responseText);
}
});
});
});
});
})(jQuery);
I also have a dynamic PHP stylesheet style.php as below:
<?php
header("Content-type: text/css;charset: UTF-8");
require('styles1.php');
require('styles2.php');
require('styles3.php');
?>
I'm trying to get some IF statements to work where if the body has a class, then require() the specified styles.
I tried variations of this, but nothing is working:
<?php
header("Content-type: text/css;charset: UTF-8");
$classes = get_body_class();
if (in_array('class1',$classes)) {
require ( 'styles1.php' );
}
if (in_array('class2',$classes)) {
require ( 'styles2.php' );
}
if (in_array('class3',$classes)) {
require ( 'styles3.php' );
}
?>
Can anyone help me out here?

Calling an Ajax function based on button class name click

I have created several image buttons in php. I have assigned a common class to all of them. When I call a jquery function based on button class name click. This works fine but when I try calling an ajax function it doesn't work. There is no error seen.
PHP to create a button
function printpic($name, $picpath, $category, $pic)
{
$style = " margin=0px; background-color=transparent; border=none;";
//$functionname= "selectedpic(this.id)";
$functionname= "myCall(this.id);";
$styleimage = "HEIGHT= 120 WIDTH= 120 BORDER=0";
$eventimage1= "zoomin(this)";
$eventimage2= "zoomout(this)";
$btnclass="btnclass";
$j=0;
$spa=0;
$i=0;
for($k=0; $k<4; $k++)
{
echo "<tr>";
for($j=0; $j<4; $j++)
{
echo"<td>";
$btn= "btn".$category[$i];
echo "<span id='" . $spa. "'>";
echo "<button name='" . $btn. "'
margin ='".$style."'
class='".$btnclass."'
onClick='".$functionname."'
>";
echo "<img src='". $picpath[$i]."/".$name[$i]."'
id ='".$pic[$i]."'
alt ='".$name[$i]."'
.$styleimage.
onMouseMove='".$eventimage1."'
onMouseOut='".$eventimage2."'
>";
echo "</button >";
$spa++;
echo"</span>";
echo"</td>";
$i++;
} // wfor
echo "</tr>";
}// for
} // end function
?>
Jquery + Ajax
$(document).ready(function(e) {
$('.btnclass').click(function() {
event = event || window.event;
var target = event.target || event.srcElement;
var id = target.id;
var but = document.getElementById(id).parentNode.name;
var datastring = '&id='+ id;
$.ajax({
url: "indexverification.php",
type: "POST",
data: datastring,
success: function(responseText) { // get the response
if(responseText == 1) { alert ("hi");}
else { alert (datastring); }
} // end success
}); // ajax end
});
});
indexverification.php
<?php
session_start();
$picno=$_SESSION['picno']; // picno from db
$answer=$_SESSION['answer']; // answer from db
$id=$_POST['id']; // id of picture clicked
$ans=$_SESSION['ans']; // answer type
if (($id==$picno) && ($answer==$ans))
{
echo '1';
}
else
{
echo '2';
}
?>
I think you use the wrong syntax. Try this:
//AJAX request
$.ajax({
url: "indexverification.php",
type: "POST",
data: datastring,
})
//Success action
.success(function( html ) {
if(responseText == 1) { alert ("hi");}
else { alert (datastring); };
})
//Error action
.fail(function() {
alert("Request failed.");
});

comment bar mysql php and ajax

I am trying to create a simple comment bar using PHP, AJAX, MySQL and json coding.
I've got two files written in php, the first one being a controller with a following code:
<?php
require("../includes/config.php");
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$comments = query("SELECT comments.comment, comments.author, comments.time FROM comments WHERE workid = ?", $_GET["workid"]);
echo json_encode($comments);
}
else if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_SESSION["userid"])) {
throw new Exception("Login");
}
else {
$result = query("INSERT INTO comments (comment, author, time, workid) VALUES(?, ?, ?, ?)", $_POST["text"], $_SESSION["userid"], date("Y-m-d H-i-s"), $_POST["workid"]);
if ($result !== false) {
echo "success";
}
}
}
?>
The second one is purported to display the records from MySQL, based on the data from the controller:
<script>
//loads the comments
$(document).ready(function(){
var comment;
$.ajax({
type: "GET",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>
},
dataType: "json",
success: function(e) {
var lis = "";
for (var i = 0; i < e.length; i++) {
comment = e[i];
lis +=
"<li class='comment'>" +
"<div class='well'>" +
"<p>" +
"<a class='username' href='#'>" + comments.author + ": " + "</a>" +
comments.comment +
"</p>" +
"<small class='pull-right'>" + comments.time + "</small>" +
"</div>" +
"</li>";
}
$("#comments").html(lis);
},
error: function(e) {
$("#comments").html(
"<li class='comment'> Couldn't load comments </li>"
);
}
});
});
</script>
<script>
$(document).ready(function(){
$("#comment-button").click(function(){
$.ajax({
type: "POST",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>,
text: $("#comment-textarea").val()
},
dataType: "text",
success: function(e) {
var comment;
$.ajax({
type: "GET",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>
},
dataType: "json",
success: function(e) {
var lis = "";
for (var i = 0; i < e.length; i++) {
comment = e[i];
lis +=
"<li class='comment'>" +
"<div class='well'>" +
"<p>" +
"<a class='username' href='#'>" + comments.author + ": " + "</a>" +
comments.domment +
"</p>" +
"<small class='pull-right'>" + comments.time + "</small>" +
"</div>" +
"</li>";
}
$("#comments").html(lis);
$("#comment-textarea").val("");
},
error: function(e) {
$("#comments").html(
"<li class='comment'> Couldn't load comments </li>"
);
}
});
}
});
});
});
</script>
Everything works pretty fine, except of the final step; when displaying the data from the database, the only thing displayed is a statement 'undefined' instead of the corect data. Except of this, the amount of comments and form display correctly. I am using a Apache server with a php installed.
In your JavaScript code, you need to replace comments.<xxx> with comment.<xxx>, since comments is indeed an undefined object in your JaveScript.

PHP concatenation

I am trying to get into some PHP and I can't seem to figure out the following.
I can create a string by means of PHP with concatenation:
echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";
But what if you want to do this with a variable? (I am guessing WP's functions can be called variables.) I am quite lost here. The following does not work. Or at least, my text editor throws an unknown error.
<?php
if ( is_404() ) {
echo "<script src='" . get_stylesheet_directory_uri(); . "/sm/script/soundmanager2-nodebug-jsmin.js'></script>
<script>
soundManager.setup({
url: '" . get_stylesheet_directory_uri(); . "/sm/swf/',
onready: function() {
var mySound = soundManager.createSound({
id: 'aSound',
url: 'http://www.mysite.com/sound.mp3',
volume: '25'
});
mySound.play();
},
ontimeout: function() {
}
});
</script>"
}
?>
It goes wrong here:
rc='" . get_stylesheet_directory_uri(); . "/s
You have a ; in the middle of your sentence. Also at the end of your string you don't have a ;
Correct syntax
<?php
if ( is_404() ) {
echo "<script src='" . get_stylesheet_directory_uri() . "/sm/script/soundmanager2-nodebug-jsmin.js'></script>
<script>
soundManager.setup({
url: '" . get_stylesheet_directory_uri() . "/sm/swf/',
onready: function() {
var mySound = soundManager.createSound({
id: 'aSound',
url: 'http://www.mysite.com/sound.mp3',
volume: '25'
});
mySound.play();
},
ontimeout: function() {
}
});
</script>";
}
?>
You can also change your approach to avoid such problems. Instead of embeding HTML into PHP you can embed PHP into HTML closing and opening PHP tags:
<?php if ( is_404() ) { ?>
<script src="<?php echo get_stylesheet_directory_uri(); ?>/sm/script/soundmanager2-nodebug-jsmin.js"></script>
<script>
soundManager.setup({
url: "<?php echo get_stylesheet_directory_uri(); ?>/sm/swf/",
onready: function() {
var mySound = soundManager.createSound({
id: 'aSound',
url: 'http://www.mysite.com/sound.mp3',
volume: '25'
});
mySound.play();
},
ontimeout: function() {
}
});
</script>
<?php } ?>
Try this
if ( is_404() ) {
echo "<script src='" . get_stylesheet_directory_uri(). "/sm/script/soundmanager2-nodebug-jsmin.js'></script>
<script>
soundManager.setup({
url: '" . get_stylesheet_directory_uri(). "/sm/swf/',
onready: function() {
var mySound = soundManager.createSound({
id: 'aSound',
url: 'http://www.mysite.com/sound.mp3',
volume: '25'
});
mySound.play();
},
ontimeout: function() {
}
});
</script>";
}
you are adding ; in between the code which is incorrect.
Try this:
<?php
if ( is_404() ) {
echo "<script src='" . get_stylesheet_directory_uri() . "/sm/script/soundmanager2-nodebug-jsmin.js'></script>
<script>
soundManager.setup({
url: '" . get_stylesheet_directory_uri() . "/sm/swf/',
onready: function() {
var mySound = soundManager.createSound({
id: 'aSound',
url: 'http://www.mysite.com/sound.mp3',
volume: '25'
});
mySound.play();
},
ontimeout: function() {
}
});
</script>";
}
?>
You can save yourself a lot of headache if you simply save the return value of the function:
<?php
if ( is_404() ) {
$temp = get_stylesheet_directory_uri();
echo "<script src='$temp/sm/script/soundmanager2-nodebug-jsmin.js'></script>
<script>
soundManager.setup({
url: '$temp/sm/swf/',
onready: function() {
var mySound = soundManager.createSound({
id: 'aSound',
url: 'http://www.mysite.com/sound.mp3',
volume: '25'
});
mySound.play();
},
ontimeout: function() {
}
});
</script>"
}
?>

Correct syntax to get my Ajax function to work

The following code will not do what I hoped, that is run the Ajax function when the div ="dist" li
created by the PHP code's is clicked.
Guidance please.
<?php
// ...
$result = mysql_query($sql);
echo "<div class=\"dist\">";
echo "<ul>";
while ($row = mysql_fetch_array($result)) {
echo "<li><a href=\"devplan.php?search-n=" . $row['NAME'] .
"&" . rawurlencode($row['PLAN']) . "\"" . ">" .
$row['PLAN'] . "</a></li>";
};
echo "</ul>";
echo "</div>";
?>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
});
});
</script>
Here is a starter for ten - I've corrected some additional braces and added error handling. If you still get an error, at least you#ll be able to tell us what it is.
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I'd add a console.log(urlplan) right after the click event handler. make sure that returned value works if you manually enter
php/dpdetails.php?q=test&anotherVar=5
into the address bar.
What does console.log(urlplan) return?
Here is a sample piece of code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>What</title>
</head>
<body>
<?php
$anchorList = "";
$rows = array(
array(
'NAME' => 'me1'
, 'PLAN' => 'thePlan1'
)
, array(
'NAME' => 'me2'
, 'PLAN' => 'thePlan2'
)
);
$anchorList .= "<div class=\"dist\">";
$anchorList .= "<ul>";
foreach ($rows as $row) {
$anchorList .= "<li>";
$anchorList .= createAnchorTag($row['NAME'], $row['PLAN']);
$anchorList .= "</li>";
}
$anchorList .= "</ul>";
$anchorList .= "</div>";
echo $anchorList;
function createAnchorTag($name, $plan) {
return "" . $plan . "";
}
?>
</body>
</html>
<script type="text/javascript" src="../scripts/jquery-1.4.2.modified.js"></script>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>
In your click function you need to return false in order to override the anchor tags wanting to redirect.
[EDIT]
I believe your actually looking to parse the href attribute of the anchor tag and pass it to the Ajax, right? If so use this script:
<script type="text/javascript">
$(document).ready(function() {
$('.dist a').click(function() {
var urlquery = $(this).attr('href').val();
// regex would be better than split, could create a more generic function
var urlparts = urlquery.split('&');
var urlplan = urlparts[1];
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>

Categories