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() :)
Related
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?
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 need help with two things.
First: if I hit empty submit button. It should show me a error.
Second: If there is 0 results, it will give an error.
$(document).ready(function(){
$(".search").click(function(){
$.post("search.php", { keywords: $(".keywords").val() }, function(data){
$("div#search").empty()
$.each(data, function(){
$("div#search").append("- <a href='#?id=" + this.id + "'>" + this.title + "</a><br>");
});
}, "json");
});
});
--
$query = $db->prepare("SELECT `media`.`id`, `media`.`title` FROM `media` WHERE `media`.`title` LIKE :keywords");
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
$error = 'error';
echo json_encode( $error );
} else {
$query->bindValue(':keywords', '%' . $keywords . '%', PDO::PARAM_STR);
$arr = array();
$query->execute();
while( $row = $query->fetch(PDO::FETCH_ASSOC) ) {
$arr[] = array( "id" => $row["id"], "title" => $row["title"]);
}
echo json_encode( $arr );
}
OK I have painstakingly recreated (jsfiddle does not let you copy/paste) this on my local machine. Your html/js code should look like this:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<input type="text" name="search" class="keywords">
<input type="submit" name="submit" class="search">
<div id="search"></div>
<script>
$(document).ready(function(){
$(".search").click(function(){
$.post(
"search.php",
{ keywords: $(".keywords").val() },
function(data){
$("div#search").empty()
$("div#search").append(data);
},
"json"
);
});
});
</script>
</body>
</html>
And for the PHP search.php page:
<?php
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
echo json_encode( "error" );
}
else {
// run mysql commands
// if resultset == empty
// echo json_encode( "error" );
echo json_encode( "actual data" );
}
?>
To parse json data in javascript do this:
$.post(
"search.php",
{ keywords: $(".keywords").val() },
function(data) {
$("div#search").empty();
obj = JSON.parse(data);
$("div#search").append(obj.id + " " + obj.title);
},
"json"
);
try using $(this) instead of this
I have a form that using ajax to post the comment to video_comment.php then show up the comment live on video page.
This is my jquery code:
$("input[id*='post_video_playallcomment_']").livequery('click', function(event) {
event.preventDefault();
var video_msg = $("#post_message");
var input_id = $(this).attr('id');
var id_split = input_id.split('_');
var video_id = id_split[3];
var comment = $("textarea[id='video_comment']").val();
var response_messages = '#video_response';
if ( comment == '' ) {
video_msg.fadeIn();
return false;
}
video_msg.hide();
user_posting(response_messages, '<?php echo $lang['600']; ?>', 1);
reset_chars_counter();
$.post(base_url + '/video_comment.php', { video_id: video_id, comment: comment },
function(response) {
if ( response.msg != '' ) {
$(response_messages).hide();
user_posting(response_messages, response.msg);
$("textarea[id='video_comment']").val('');
} else {
$(response_messages).hide();
user_response(response_messages, '<?php echo $lang['587']; ?>');
$(".no_comments").hide();
$("textarea[id='video_comment']").val('');
var bDIV = $("#comments_delimiter");
var cDIV = document.createElement("div");
$(cDIV).html(response.code);
$(bDIV).after(cDIV);
}
}, "json");
});
On video_comment.php, this is the response.code to show up the comment live on video page.
echo 'text...
echo '<div id="commentplayer"></div>';
echo '<script type="text/javascript">';
echo 'jwplayer("commentplayer").setup({';
echo 'file: "...url",';
echo 'width: "300",';
echo 'height: "225",';
echo 'provider: "http",';
echo 'startparam: "start",';
echo 'wmode: "transparent",';
echo 'controls: "true",';
echo 'stretching: "uniform",';
echo 'primary: "flash",';
echo 'autostart: "false",';
echo 'ga: {}';
echo '});';
echo '</script>';
echo 'text...
I have no problem to get 'text...', but i can't get '<script type="text/javascript">function...</script>' to show up live on video page.
Help please...
instead of placing javascript code in the php return, why dont you place it in the .post response?
$("input[id*='post_video_comment']").click(function() {
$.post('video_comment.php', function(response) {
$('#comment').html(response.code);
//place javascript code here
}, "json");
});
or placing a onload before your js code
$str = '<div id="commentplayer"></div>
<script type="text/javascript">
window.onload=(function() {
jwplayer("commentplayer").setup({
file: "...url",
width: "300",
height: "225",
provider: "http",
startparam: "start",
wmode: "transparent",
controls: "true",
stretching: "uniform",
primary: "flash",
autostart: "false",
ga: {}
});
});
</script>';
echo $str;
i want to allows users to sort table rows derived from database and save the new location in database
the problem is that the postion is not updated in the interface nither in the database
mysql table: id int primary key auto_increment, sort int, author_affliation varchar, author_email varchar
script:
$('#myTable tbody').sortable({
start: function (event, ui) {
//fix firefox position issue when dragging.
if (navigator.userAgent.toLowerCase().match(/firefox/) && ui.helper !== undefined) {
ui.helper.css('position', 'absolute').css('margin-top', $(window).scrollTop());
//wire up event that changes the margin whenever the window scrolls.
$(window).bind('scroll.sortableplaylist', function () {
ui.helper.css('position', 'absolute').css('margin-top', $(window).scrollTop());
});
}
},
beforeStop: function (event, ui) {
//undo the firefox fix.
if (navigator.userAgent.toLowerCase().match(/firefox/) && ui.offset !== undefined) {
$(window).unbind('scroll.sortableplaylist');
ui.helper.css('margin-top', 0);
}
},
helper: function (e, ui) {
ui.children().each(function () {
$(this).width($(this).width());
});
return ui;
},
scroll: true,
update: function (event, ui) {
serial = $(this).sortable('serialize');
$.ajax({
url: "sort_coauthors.php",
type: "POST",
data: serial,
success: function(response) {
alert(response);
},
error: function(){
alert("theres an error with AJAX");
}
});
}
}).disableSelection();
sort-coauthors:
#mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
if (isset($_POST['menu']) && is_array( $_POST['menu'])) {
$menu = $_POST['menu'];
for ($i = 0; $i < count($menu); $i++) {
$q = mysql_query("UPDATE `co_authors` SET `sort`=" . $i . " WHERE `id`='" . intval($menu[$i]) . "'") or die(mysql_error());
if($q) {
echo "success";
}
}
}
else {
echo "fail";
}
main page:
while ($row = mysql_fetch_assoc($co_authors)) {
echo "<tbody><tr id='menu_" . $row['id'] . "'><td>{$row['author_email']}</td>
<td>{$row['coauthor_affliation']}</td>";
?><td><button class='remove' id='remove' name='remove' email="<?php echo $row['author_email'] ?>"
paper="<?php echo $row['paper_id'] ?>">Remove</button></td>