jquery autocomplete sends empty get value to php - php

i am very new to jquery n javascript. I am trying to make an autocomplete feature. I am using a sample code from a diff page to do this. but the 'term' it passes to the php page is empty. so the autocomplete doesnt work. I dont understand why, can someone take a look? I didnt change the labels but i am just trying to test it to see if it works. the issue is with the php page, the request 'term' is empty.
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(function() {
$( "#txtLanguage" ).autocomplete({
source: "source.php",
minLength: 1 // how many character when typing to display auto complete
});
});
</script>
</head>
<body>
<label for="Language">Language: </label>
<input id="txtLanguage" class="txtLanguage"/>
</div>
</body>
</html>
<?php
include 'dbconnect.php';
$q=$_REQUEST['term'];
echo $q;
$return = array();
$stat="SELECT email FROM users WHERE email LIKE '$q'";
$query = sqlsrv_query($conn,$stat);
while ($row = sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC)) {
array_push($return,array('label'=>$row['email'],'value'=>$row['email']));
}
echo(json_encode($return));
?>

I think you need this:
$stat="SELECT `email` FROM `users` WHERE `email` LIKE '$q%'";
You forgot for % symbol and LIKE without % is equal to email = '$q'

Are you sure, the file path is correct? Is there any javascript error in the console?
Try console $( "#txtLanguage" ).
Remove source.php and add an array
Hope this helps you.

Use $_GET['term'] instead of $_REQUEST['term']

Related

Store jQuery click count in a cookie, and then echo it.

I'm trying to use jQuery to count clicks, store them in a cookie and then echo them back out.
I've found some code online that allows me to do it, but I dont seem to be able to make it work. It's creating the cookie file and storing '0' in it, but it does not update on clicking of links. Any guidance as to whats going wrong with this code would be great. :
clickCount.js
jQuery(function(){
$("a").click(function{
var cookiename = 'linkcounter';
if($.cookie(cookiename) == null){
$.cookie(cookiename, 0);
}
$.cookie(cookiename, $.cookie(cookiename)+1);
});
});
index.php
<?php
session_start();
$counter_file = 'counter';
if(!file_exists($counter_file)){
file_put_contents($counter_file, 0);
}
$counts = (int)file_get_contents($counter_file);
file_put_contents($counter_file, $counts++);
// you can use $counts if you want to display it on the page.
?><!DOCTYPE html>
<html>
<head>
<title>Link Click Counter Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript" src="countdetect.js"></script>
</head>
<body>
<br />
<br />
Link clicks: <?php echo $counts; ?>
</body>
</html>
In you PHP code, you're not storing the click count into a cookie, but into a file.
You either have to update the counter file by by making an AJAX request from your JavaScript to your server, or actually write a cookie within your PHP file:
<?php
$cookieName = 'linkcounter';
$count = isset($_COOKIE[$cookieName]) ? (int)$_COOKIE[$cookieName] : 0;
$count++;
setcookie($cookieName, $count);
?>
Link clicks: <?=$count?>
Make sure you use the same cookie name in both JavaScript and PHP.

can ckeditor update database content?

can you give me a way to save the contents of the ckeditor to the database?
i have 0% idea on how to make things work for this would be the first time to be use one. i've searched on google but it always shows the fckeditor(are they the same?). also, i've tried some codes with AJAX on it but still couldn't make it work because it requires some plugin and i don't actually understand it.
anyway, i'am using the 4.0 version of ckeditor and would prefer php or javascript code because i don't really know AJAX. here's my trial code:
<!DOCTYPE html>
<!--
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
-->
<?php
include('global.php');
?>
<html>
<head>
<script>
var type = 'Admin';
<!-- editableContent -->
window.onload = function (){
if(type=='Admin'){
document.getElementById('opener').contentEditable= true;
document.getElementById('main').contentEditable= true;
// We need to turn off the automatic editor creation first.
CKEDITOR.disableAutoInline = true;
var editor = CKEDITOR.inline( 'opener' );
var editor = CKEDITOR.inline( 'main' );
}
else{
document.getElementById('opener').contentEditable= false;
document.getElementById('main').contentEditable= false;
}
}
function showHTML () {
document.getElementById('textpad').textContent = textEditor.document.body.innerHTML;
return;
}
</script>
<title>Inline Editing by Code — CKEditor Sample</title>
<meta charset="utf-8">
<script src="ckeditor/ckeditor.js"></script>
<link href="ckeditor/samples/sample.css" rel="stylesheet">
<style>
#editable
{
padding: 10px;
float: left;
}
</style>
</head>
<body>
<div id="opener">
<?
$result= mysql_query ("SELECT * from text_tb WHERE categoryName='index'");
while($row = mysql_fetch_array($result)){
echo $row[1];
}
?>
</div>
<div id="main">
<?
$result= mysql_query ("SELECT * from text_tb WHERE categoryName='about'");
while($row = mysql_fetch_array($result)){
echo $row[1];
}
?>
</div>
</body>
</html>
thank you very much for your time and help.
This may not be 100% on target but it is what I've used and it works well. TinyMCE uses the HTML textarea tag and some JavaScript to allow the client to format the information. Then an ordinary "submit" sends the content of the textarea to the server, where you receive it in a POST-method request and you can store it in the data base.
Sample JS for TinyMCE:
<script language="javascript" type="text/javascript" src="scripts/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "advanced",
plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,|,bullist,numlist,|,copy,paste,pastetext,pasteword,|,undo,redo,|,link,unlink,anchor,image,cleanup,|,removeformat,|,forecolor,backcolor,|,formatselect,charmap,emotions,iespell,",
theme_advanced_buttons2 : "",
theme_advanced_buttons3 : "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true
});
</script>
Link here: http://www.tinymce.com/
The ckeditor documentation offers a very simple and easy way:
<form method="post">
<p>
My Editor:<br>
<textarea name="editor1"><p>Initial value.</p></textarea>
<script>
CKEDITOR.replace( 'editor1' );
</script>
</p>
<p>
<input type="submit">
</p>
# http://docs.ckeditor.com/#!/guide/dev_framed-section-4
On the server side then you only have to
mysql_query("insert into yourtable (yourtextfield) VALUES ( '".mysql_real_escape_string($_POST['editor1'])."')");
though I strongly suggest you to use prepared statements as offered by the PHP PDO Extensions. Prepared statements are much more secure.
[...] would prefer php or javascript code because i don't really know AJAX.
In fact, AJAX is a mix of PHP and JavaScript :P You can't update database content without a server side language(PHP), but using a client side language (JavaScript) you can "talk" to a server side script, that's what we call AJAX..
Anyway, as Ray Paseur said, usually you post a form containing textarea with the value of edited content but in your case you seems to be using the new Inline editing feature of the 4.0 version ?
So in this case, to access the value of the edited content you'll have to get the content of the div you've edited like this :
var opener_content=document.getElementById("opener").innerHTML;
var main_content=document.getElementById("main").innerHTML;
This will gives you the HTML code generated by the editor. Just do this in a function you call from maybe a "save changes" button in your page, then send those variables to your server with AJAX... (I would really suggest you to learn more about AJAX, it's more simple than it seams.)
But, if you don't want to learn AJAX right now, you can add an hidden form on your page with empty textareas, when the save button is clicked you fill these textarea with the 2 variables above, then you post this form via JavaScript and save data in PHP using the $_POST variable ! Its gonna work, even if it's an ugly and lazy solution :)

php / jquery autocomplete from mysql table

After referencing many previous questions and answers on this topic, I am still stumped. I am attempting to reference the database that stores a user's contact list. As an initial start, I'm keeping things simple and only allowing reference by email (rather than email, first and last names, etc).
I have the following linked:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$( ".emaillist" ).autocomplete({
source: "contacts.php"}); });
</script>
contacts.php: [UPDATED]
<?php
session_start();
include "scripts/sqlconnect.php";
$id = $_SESSION['id'];
$csql = mysql_query("SELECT * FROM db WHERE id='$id' AND email LIKE '%".mysql_real_escape_string($_GET['term'])."%'");
$contactlist = array();
while($row = mysql_fetch_assoc($csql)){
$contactlist[] = $row['email'];
}
$contactlist = json_encode($contactlist);
header('Content-Type: application/json');
echo "$contactlist";
?>
And finally the relevant HTML snippet:
<input name="semail" type="text" class="emaillist" id="semail"/>
Any suggestions on what I've done wrong? I can't seem to pinpoint the issue.
2 things that I notice:
You never output the contents of $contactlist
You aren't setting the appropriate Content-Type header.
So you want to do this:
$contactlist = json_encode($contactlist);
header('Content-Type: application/json');
echo $contactlist;
According to the documentation, the value passed to the AJAX source is called term, so you should be using that in your query, not semail:
... AND email LIKE "%'. mysql_real_escape_string($_GET['term']) .'%"');
^^^^-- Here

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.

Help with jQuery select menu styling

I'm trying to use the jQuery UI to style my HTML select menu but I'm having a little trouble getting it working... I'm still relatively new to using jQuery so the answer to this may be fairly simple.
My full code segment (using jQuery v1.6.2):
<link rel="stylesheet" type="text/css" href="css/ui-darkness/jquery.css">
<label for="favorite">Select favorite team</label>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jqueryui.js"></script>
<script type="text/javascript" src="js/selectmenu.js"></script></script>
<script type="text/javascript">$(function() {
$('select[name=favorite]').selectmenu();
});
</script>
<select name='favorite'>
<?php
while ($temp = mysql_fetch_assoc($query)) {
echo "<option value=" . $temp['id'] . ">" . htmlspecialchars($temp['teamname']) . "</option>";
}
?>
</select>
But it doesn't seem to do anything. My select menu appears as a normal, boring HTML select menu. I'm really not sure at all if what I'm doing is completely retarded or what, but let me know if you know how to get this working properly.
EDIT Console gives error Uncaught TypeError: Object [object Object] has no method 'selectmenu'
$('select[name=favorite]').selectmenu();
You must set the name of the element you want to use. In this case, a select box with the name favorite.
You must also place the code within jQuery's document ready function
$(document).ready(function() {
$('select[name=favorite]').selectmenu();
});
or use the shorthand
$(function() {
$('select[name=favorite]').selectmenu();
});
why don't you try to give an id or class to the select.
then you can call it from jquery by using it id or class.
i don't know it will work or not, but worth it a try.

Categories