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?
Related
custom.js file:
$(document).ready(function() {
$("#company_name").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/capms_v2/ca_autocomplete/getcompanyName",
data: {
keyword: $("#company_name").val()
},
dataType: "json",
success: function(data) {
//alert(data);
if (data.length > 0) {
$('#DropdownCompany').empty();
$('#company_name').attr("data-toggle", "dropdown");
$('#DropdownCompany').dropdown('toggle');
} else if (data.length == 0) {
$('#company_name').attr("data-toggle", "");
}
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCompany').append('<li role="displayCountries" ><a role="menuitem DropdownCompany" id=' + value['company_id'] + ' Address1=' + value['company_address1'] + ' Address2=' + value['company_address2'] + ' city=' + value['company_city'] + ' state=' + value['company_state'] + ' pincode=' + value['company_zip'] + ' class="dropdownlivalue">' +
value['company_name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#company_name').val($(this).text());
$('#company_id').val($(this).attr("id"));
// $('#company_address1').val($(this).text());
$('#tableCityID').html($(this).attr("id"));
$('#tableCityName').html($(this).text());
$('#Address1').html($(this).attr("Address1"));
$('#Address2').html($(this).attr("Address2"));
$('#city').html($(this).attr("city"));
$('#state').html($(this).attr("state"));
$('#pincode').html($(this).attr("pincode"));
});
});
I was getting id in span id="tableCityID" but if I store the value and pass the value to mysql it was not fetching the value
$com = '<span id="tableCityID">';
and if I echo the select query
echo $sql="select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '".$com."'";
I get the result with not completed single codes
select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '15
If anybody faces this problem, please help me. Thanks in advance.
just use the </span>
like this
$com = '<span id="tableCityID"></span>';
My function seems to return nothing for the destination element when the link is referred to from Instagram. It works fine if I directly visit the page.
function getTeamsByLeague(league) {
//console.log("League Set: " + league);
$.ajax({
url: "<?php echo SITE_BASE_URL; ?>json.php",
data: {method: "getteamsbyregion", league: league},
success: function (data) {
if (data && data.length > 0) {
$("#destination").empty();
var selected = "";
$.each(data, function (index, item) {
if (item.team == teamSelected) {
selected = " selected";
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
} else {
selected = "";
}
$("#destination").append('<option ' + selected + ' value="' + item.lat + ',' + item.lng + '">' + item.team + '</option>');
if (index == 0) {
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
}
});
}
},
type: "GET",
dataType: "json"
});
}
Below is the ajax request.
$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(deleted, undeleted){
if(undeleted == 0) {
alert('All ' + deleted + ' files delted from the server');
} else {
alert(deleted + ' files deleted and ' + undeleted + ' files could not be deleted');
}
}, 'json');
and here goes the delete.php
<?php
if(isset($_POST['deletearray'])) {
$files = $_POST['deletearray'];
$dir = $_POST['dir'];
$deleted = 0;
$undeleted = 0;
foreach($files as $file) {
if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {
$deleted ++;
} else {
$undeleted ++;
}
}
echo json_encode($deleted, $undeleted);
}
return;
?>
Up on running the code it deletes the files successfully but no message displays.
I also tried changing the ajax request as:
$.post('delete.php', {deletearray:deletearray, dir:dir}, function(deleted, undeleted){
alert("php finished");
}, 'json');
still it does not display the message. So i guess something is wrong in the delete.php file. Please help.
First thing-
Use $_POST['deletearray'] instead of $_POST[deletearray]
Second thing-
You cannot return different variables from the PHP scrtipt, every thing you print there is returned in the ajax callback, so just write this-
PHP
json_encode(array('totalDeleted' => $deleted, 'totalUndeleted' => $undeleted));
AJAX
...
function(response){
response=JSON.parse(response);
console.log(response);
}
The best way to do jquery + ajax + php is as next:
jquery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function do_ajax() {
//set data
var myData = new Array();
myData.push({name:'deletearray',value:'deletearray'});
myData.push({name:'dir',value:'dir'});
//ajax post
$.ajax({
dataType: 'json',
url: 'delete.php',
type: 'post',
data: myData,
success: function(returnData) {
if(returnData.undeleted == 0) {
alert('All ' + returnData.deleted + ' files delted from the server');
} else {
alert(returnData.deleted + ' files deleted and ' + returnData.undeleted + ' files could not be deleted');
}
}
});
}
</script>
PHP:
<?php
$myData = $_POST;
if(isset($myData['deletearray']) AND isset($myData['dir'])) {
$files = $myData['deletearray'];
$dir = $myData['dir'];
$deleted = 0;
$undeleted = 0;
foreach($files as $file) {
if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {
$deleted ++;
} else {
$undeleted ++;
}
}
print(json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted)));
exit();
}
?>
You should use json_encode like following:
json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted));
And you have to get vars with data.undeleted and data.deleted
$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(data) {
if(data.undeleted == 0) {
alert('All ' + data.deleted + ' files delted from the server');
} else {
alert(data.deleted + ' files deleted and ' + data.undeleted + ' files could not be deleted');
}
}, 'json');
I am using the code bellow of foxycomplete to get some results from my db with images.
With local files works great but i cant do it with mysql.
Here is my code that i am using..
<form id="autocompleteForm" name="autocompleteForm" action="" method="post">
<input type="text" name="s" id="s" value="Search" style="border:none;" />
</form>
The Javascript Code:
(function($) {
$(document).ready(function() {
$( '#s' ).each( function(){
$(this).attr( 'title', $(this).val() )
.focus( function(){
if ( $(this).val() == $(this).attr('title') ) {
$(this).val( '' );
}
} ).blur( function(){
if ( $(this).val() == '' || $(this).val() == ' ' ) {
$(this).val( $(this).attr('title') );
}
} );
} );
$('input#s').result(function(event, data, formatted) {
$('#result').html( !data ? "No match!" : "Selected: " + formatted);
}).blur(function(){
});
$(function() {
function format(mail) {
return "<a href='"+mail.permalink+"'><img src='" + mail.image + "' /><span class='title'>" + mail.title +"</span></a>";
}
function link(mail) {
return mail.permalink
}
function title(mail) {
return mail.title
}
$("#s").autocomplete(completeResults, {
width: $("#s").outerWidth()-2,
max: 5,
scroll: false,
dataType: "json",
source: "video_search.php",
matchContains: "word",
parse: function(data) {
return $.map(data, function(row) {
return {
data: row,
value: row.title,
result: $("#s").val()
}
});
},
formatItem: function(item) {
return format(item);
}
}).result(function(e, item) {
$("#s").val(title(item));
//location.href = link(item);
});
});
});
})(jQuery);
And the php code to retrieve my data:
<?php
require "connectiondb.php";
if(isset($_REQUEST['s']))
{
$queryString = mysql_real_escape_string($_REQUEST['s']);
echo'var completeResults = [{';
$ss = mysql_query ("SELECT title, image FROM users WHERE title LIKE '$queryString%' LIMIT 7");
while($result = mysql_fetch_assoc($ss)) {
echo '
"permalink": "index.html",
"image": "'.$result['image'].'",
"title": "'.$result['title'].'"
},';
}
echo '}];';
}else{
}
?>
Thank you Guys!!!
Whats inside the $result['image']? If it contains the image file itself(binary data) and not just the path, then you need to create one more file (image.php?s=id) which would retreive just that binary data with adequate header.. ie
<?php
header('Content-Type: image/jpeg');
// sql stuff
echo $result['image'];
?>
In your main file you'll then call just
"image": "'.image.php?id='.$result['id'].'",
also, dont torture yourself and use json_encode() :)
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.