i'm trying to create a simple autocomplete textbox that takes the suggestions from an array.the code i'm using(based on this) is :
call.php
<?php
$list = array(
"Autocomplete",
"Metapher",
"Metatag");
for($i=0; $i<count($list); $i++){
if(strpos($list[$i], $_GET['str']) !== FALSE && strlen($_GET['str']) >= 2){
echo str_ireplace($_GET['str'], '<b style="color: red;">'.$_GET['str'].'</b>', $list[$i]) . '<br>';
}
}
?>
index.php
<!DOCTYPE html>
<html>
<head>
<title>AJAX - 03</title>
<script type="text/javascript">
var ajax = new XMLHttpRequest;
function t(){
ajax.open("GET", "call.php?str=" + document.getElementById("test").value, false);
ajax.send();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
document.getElementById("container").innerHTML = ajax.responseText;
}
}
}
</script>
</head>
<body>
<div id="container" style="border: 3px; border-style: solid; font-size: 42pt; border-radius: 7px;">
Text
</div>
<br><br>
<input id="test" type="text" onkeyup="javascript:t()">
</body>
</html>
but nothing comes up at the suggestion box.I can't find any syntax errors so i suppose there is something wrong with the logic?
UPDATE:
after the advice from PLB and FAngel i added the onreadystatechange and the checks.However it still doesn;t work properly.Actually i just found that if you type a compination of letters that are inside one of the 3 words the suggestions come up properly.It just doesnt work if you type the starting letters of a word.For example if i give "com" as input the word Autocomplete comes up.However if i give "Aut" then nothing.So i guess the actual problem is here:
if(**strpos($list[$i], $_GET['str']) !== FALSE** && strlen($_GET['str']) >= 2)
From what i read here http://php.net/manual/en/function.strpos.php the problem could be the use of != but i use !== as i should.Any thoughts?
You are missing that your request is asynchronous. So when you run this line: document.getElementById("container").innerHTML = ajax.responseText;, request is not done yet. Take a look at this . onreadystatechange is what you need. Or make that call synchronous
You can also work it like this.
http://jsfiddle.net/qz29K/
All you need is you just replace the json array with php jsonencoding like this
$list = array(
"Autocomplete",
"Metapher",
"Metatag");
<script>
var availableTags = <?php echo json_encode($list) ?>
</script>
Hope this will help.
It totally WORKS!
I tried it.
I had input : Met
and it gave me Metaphor and one more word.
However, for advanced usage. Check this out, you gonna love it.
http://jqueryui.com/demos/autocomplete/
Related
Probably i didnt explain very well, i updated the code to turn more easy to see what i want.
I need to load a external html file in that "div external_page....", i thing that the best way is to load a file in the php file(External PHP content), tell me if im wrong :)
This is the demo: http://vasplus.info/demos/load_and_refresh_div_every_10_seconds/index.php
(UPDATE)
<script language="javascript" src="js/jquery_1.5.2.js"></script>
<div id="external_page_content_displayer">External page contents will be here</div>
<!-- EXTERNAL PHP CONTENTS-->
<?php
srand((float) microtime() * 10005224);
$lines = file('ajax/rssatom/rss-atom.html');
$This_Page_Content = array($lines,
"teste","teste","teste");
$This_Page_Content_Rand_Keys = array_rand($This_Page_Content, 2);
$This_Page_Content_Displayer = $This_Page_Content[$This_Page_Content_Rand_Keys[0]] . "\n";
echo strip_tags($This_Page_Content_Displayer);
?>
<!-- LOAD FUNCTION-->
<script>
function Load_external_content()
{
$('#external_page_content_displayer').load('external_content.php').hide().fadeIn(3000);
}
setInterval('Load_external_content()', 10000);
</script>
Regards
You can try with this:
$lines = file('ajax/rssatom/rss-atom.html');
I experience the following problem. By clicking the button in start.php the file fakten02.php is called with the parameter DE2 . This parameter is used as a variable variable to convert the array $DE2 into a string and display it in start.php. Unfortunately, this does not happen. If fakten02.php is directly called with the parameter, it works. If the parameter is hard-coded in fakten02.php the content of $land is shown in start.php. However, if $land is filled from $text2, $land is empty in start.php.
start.php
<!DOCTYPE HTML>
<html>
<head>
<title>Start</title>
</head>
<body>
<div id="spalten">
<button type="submit" id="land1">Klicken</button>
</div>
<?php
include("fakten02.php");
print_r($land);
?>
</body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#spalten > button").click(function() {
$.get("fakten02.php", {sland:'DE2'});
<?php echo $land; ?>;
})
})
</script>
</html>
fakten02.php
<?php
$parameter = $_GET['sland'];
//$parameter=$_REQUEST['sland'];
//print_r($_REQUEST);
$DE2 = array("ich", "bin", "groß");
//echo "Text $text";
//$text2 = "$".$parameter;
$param2 = $parameter;
$text2 =$$param2;
for ($i=0; $i < count($text2); $i++) {
$land.="$text2[$i] "; //Does not work
$land.= "daten[$i] = '$DE2[$i]';"; //Returns expected data
}
//print( "aus 2 $land, $param2");
?>
I don't understand this behaviour. I did a lot of searching here and on Google, but I could not find a similar problem. How can I resolve this issue?
My PHP code is:
<?php
class Sample{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) ){
echo "Starting to read ";
$req = $_GET[ 'request' ];
$result = json_decode($req);
if( $result->request == "Sample" ){
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}else{
echo "Not Supported";
}
}
?>
Is there anything wrong
I want to send a JSON to this php and read the JSON that it returns using java script , I can't figure out how to use JavaScript in this , because php creates an html file how Can I use $_getJson and functions like that to make this happen ?!
I tried using
$.getJSON('server.php',request={'request': 'Sample'}) )
but php can't read this input or it's wrong somehow
thank you
try this out. It uses jQuery to load contents output from a server URL
<!DOCTYPE html>
<html>
<head>
<title>AJAX Load Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(event) {
$('#responce').load('php_code.php?request={"request":"Sample"}');
});
});
</script>
</head>
<body>
<p>Click on the button to load results from php_code.php:</p>
<div id="responce" style="background-color:yellow;padding:5px 15px">
Waiting...
</div>
<input type="button" id="button" value="Load Data" />
</body>
</html>
Code below is an amended version of your code. Store in a file called php_code.php, store in the same directory as the above and test away.
<?php
class Sample
{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) )
{
echo "Starting to read ";
$req = $_GET['request'];
$result = json_decode($req);
if( isset($result->request) && $result->request == "Sample" )
{
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}
else
{
echo "Not Supported";
}
}
Let me know how you get on
It would be as simple as:
$.getJSON('/path/to/php/server.php',
{request: JSON.stringify({request: 'Sample'})}).done(function (data) {
console.log(data);
});
You can either include this in <script> tags or in an included JavaScript file to use whenever you need it.
You're on the right path; PHP outputs a result and you use AJAX to get that result. When you view it in a browser, it'll naturally show you an HTML result due to your browser's interpretation of the JSON data.
To get that data into JavaScript, use jQuery.get():
$.get('output.html', function(data) {
var importedData = data;
console.log('Shiny daya: ' + importedData);
});
I'm learning some web programming programming right now and I'm a little stuck.
I'm trying to move a character around an array (like a simple rogue-like game) using the WASD keys but I can't seem to figure it out.
So I was wondering if someone could explain to me what I'm doing wrong exactly?
heres the code:
<html>
<body style="font-family: Courier" onkeydown="move(event)">
<p id="game" >
<?php
// php functions regarding movement
$map = array(
"XXXXXXXXXX",
"X........X",
"X...XX...X",
"X...XX...X",
"X........X",
"XXXX..XXXX",
"X........X",
"X..X..X..X",
"X........X",
"XXXXXXXXXX",
);
$player = new Player(2,2,"T");
initMap($map);
makePlayer($player);
displayMap($map);
?>
</p>
<script type="text/javascript" src="jquery.js">
function move(ev){
var key = (ev) ? ev.which : event.keyCode;
var c = String.fromCharCode(key);
$("#game").html('function move is working')
switch(c){
case "w":
<?php
moveUp();
?>
$("#game").empty();
break;
// keys ASD all share same code
default:
break;
}
}
</script>
</body>
</html>
/* output, no changes when key is pressed:
XXXXXXXXXX
X........X
X.T.XX...X
X...XX...X
X........X
XXXX..XXXX
X........X
X..X..X..X
X........X
XXXXXXXXXX
*/
Pressing any of the keys should clear the html from the #game div, but it does not. Any suggestions?
I think i can help you with your problem. Just try my example below about movements:
1. HTML
<div id="map"></div>
2. CSS
#map {position:relative; width:600px; height:300px; border:1px solid gray;}
.ball {position:absolute; width:50px; height:50px;
-moz-border-radius:35px; border:1px solid red;}
3. JS
<script type="text/javascript">
$(function(){
var ball = $("<div class='ball'></div>");
$("#map").append(ball);
$(document).keydown(function(e){
//alert(e.keyCode);
var position = $(".ball").position();
switch(e.keyCode){
case 37: //left
$(".ball").css("left", position.left - 50 + "px");
break;
case 38: //up
$(".ball").css("top", position.top - 50 + "px");
break;
case 39: //right
$(".ball").css("left", position.left + 50 +"px");
break;
case 40: //down
$(".ball").css("top", position.top + 50 +"px");
break;
}
});
});
</script>
Hope this will help.tnx
<?php } elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) { ?>
<?php $_NAME = urlencode($_NAME); ?>
<?php $_MGT_NAME = urlencode($_MGT_NAME); ?>
</div>
<?php } ?>
I am getting this error expected ';'
The horror. The horror.
Here's the actual error, in the onclick attribute value:
lpButtonCTTUrl = 'http:...Ad%20Source=somesite.com& ='+escape(document.location); imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&referrer
That is, there should be a +' instead of ; after the document.location inclusion, and there should be a closing quote after the imageURL inclusion, and referrer is in the wrong place (it should be just before the document.location inclusion.
It also has problems like the use of escape (never use escape. For URL-encoding you actually want encodeURLComponent); the unescaped ampersands all over the place; and the lack of HTML- and URL-encoding of values output from PHP, potentially causing cross-site scripting risks.
Writing a value inside a URL component inside a URL inside a JavaScript string literal inside an attribute value inside HTML is utter insanity so it's no surprise there are mistakes. Let's try to bring some maintainability to this madness. Break out the JavaScript and URL creation into separate steps where getting the escaping right is possible.
function urlencodearray($a) {
$o= array();
foreach ($a as $k=>$v)
array_push($o, rawurlencode($k).'='.rawurlencode($v));
return implode('&', $o);
}
function h($s) {
echo htmlspecialchars($s);
}
With these utility functions defined, then:
<?php } elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) { ?>
<?php
$lpbase= 'http://server.iad.liveperson.net/hc/84152841/?';
$linkurl= $lpbase.urlencodearray(array(
'cmd'=>'file',
'file'=>'visitorWantsToChat',
'site'=>'84152841',
'byhref'=>'1',
'skill'=>'somesiteILS',
'SESSIONVAR!skill'=>'somesiteILS',
'SESSIONVAR!Management Company'=>$_MGT_NAME,
'SESSIONVAR!Community'=>$_NAME,
'SESSIONVAR!Ad%20Source'=>'somesite.com',
'imageUrl'=>"http://{$_SERVER['SITENAME']}/images/"
));
$imgurl= $lpbase.urlencodearray(array(
'cmd'=>'repstate',
'site'=>'84152841',
'channel'=>'web',
'ver'=>'1',
'skill'=>'somesiteILS',
'imageUrl'=>"http://{$_SERVER['SITENAME']}/images/"
));
?>
<div id="caller_tag">
<a id="_lpChatBtn" target="chat84152841" href="<?php h($url); ?>">
<img src="<?php h($imgurl); ?>" name="hcIcon" alt="Chat" border="0">
</a>
<script type="text/javascript">
document.getElementById('_lpChatBtn').onclick= function() {
var url= this.href+'&referrer='+encodeURIComponent(location.href);
if ('lpAppendVisitorCookies' in window)
url= lpAppendVisitorCookies(url);
if ('lpMTag' in window && 'addFirstPartyCookies' in lpMTag)
url= lpMTag.addFirstPartyCookies(url)
window.open(url, this.target, 'width=475,height=400,resizable=yes');
return false;
};
</script>
</div>
With an unformatted mess like that it's no wonder you can't find the error.
I tried running it through HTML Tidy but it doesn't like anything between the comments.
mesite.com& ='+escape(document.location); imageUrl=<?php print "ht
I'm not good at reading long lines like that but shouldn't this be
mesite.com& ='+escape(document.location) +'imageUrl=<?php print "ht
First of: why are you opening and closing PHP so many times, you could write it like:
<?php
} elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) {
$_NAME = urlencode($_NAME);
$_MGT_NAME = urlencode($_MGT_NAME);
?>
<div id="caller_tag">
<!-- BEGIN LivePerson Button Code --><a id="_lpChatBtn" href='http://server.iad.liveperson.net/hc/84152841/?cmd=file&file=visitorWantsToChat&site=84152841&byhref=1&SESSIONVAR!skill=somesiteILS&SESSIONVAR!Management%20Company=<?php print $_MGT_NAME; ?>&SESSIONVAR!Community=<?php print $_NAME; ?>&SESSIONVAR!Ad%20Source=somesite.com&imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>' target='chat84152841' onClick="lpButtonCTTUrl = 'http://server.iad.liveperson.net/hc/84152841/?cmd=file&file=visitorWantsToChat&site=84152841&SESSIONVAR!skill=somesiteILS&SESSIONVAR!Management%20Company=<?php print $_MGT_NAME; ?>&SESSIONVAR!Community=<?php print $_NAME; ?>&SESSIONVAR!Ad%20Source=somesite.com& ='+escape(document.location); imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&referrer lpButtonCTTUrl = (typeof(lpAppendVisitorCookies) != 'undefined' ? lpAppendVisitorCookies(lpButtonCTTUrl) : lpButtonCTTUrl); lpButtonCTTUrl = ((typeof(lpMTag)!='undefined' && typeof(lpMTag.addFirstPartyCookies)!='undefined')?lpMTag.addFirstPartyCookies(lpButtonCTTUrl):lpButtonCTTUrl);window.open(lpButtonCTTUrl,'chat84152841','width=475,height=400,resizable=yes');return false;" ><img src='http://server.iad.liveperson.net/hc/84152841/?cmd=repstate&site=84152841&channel=web&&ver=1&imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&skill=somesiteILS' name='hcIcon' alt='Chat Button' border=0></a><!-- END LivePerson Button code -->
</div>
And also: the error must be somewhere else, I can't see a missing ";" in php in the code you pasted, unless the error is in javascript.