I'm trying to add an auto-complete function to a text field.
This used to work, but then I switched to an MVC structure and now I can't get it back to work.
PHP/HTML:
echo '<br><br>Add member:<br>'
. '<form method="post"><input type="text" name="username" oninput="findUsers(this.value)" list="livesearch">'
. '<datalist id="livesearch"></datalist>'
. '<input type="submit" value="Add">'
. '</form>';
JavaScript:
<script>
function findUsers(str) {
if (str == "") {
document.getElementById("livesearch").innerHTML = "no suggestions";
xmlhttp.send();
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","/user/search/?q="+str,true);
xmlhttp.send();
}
}
</script>
/user/search opens a function called search in the class User in the UserController.php file
class UserController extends Controller
{
public function search()
{
$response = "hello";
echo $response;
}
}
So this should put the "hello" message in the livesearch datalist.
But for some reason just nothing is happening.
If I replace the xmlhttp.open by window.open, the page does load normally and shows the hello message. But that is obviously not what I want.
Figured out the exact problem:
My xmlhttp.responseText is also returning the header of my website, which is already loaded in the MVC structure.
How would I work around this?
Is it an option to just edit the string and get the last part in javascript?
Or are there better solutions?
Used JavaScript to grab the last part of the string (so without the header)
It does what it's supposed to do now, but feels like a pretty "dirty" solution.
Also had to add the <option value=""> tag, which was in my code, but not in my testcode.
Related
<form action='' method='post'>
<input type='text' name='username' onkeyup='findUsers(this.value)'>
<input type='submit' value='Add Member'>
<div id='livesearch'></div>
<script>
function findUsers(str) {
if (str == "") {
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","/classes/livemembersearch.php?q="+str,true);
xmlhttp.send();
}
}
</script>
$q = $_GET["q"];
When getting the value in the findUsers function, everything works fine, except when I empty the textfield, it keeps showing the last value before I emptied the field.
Examples:
I type "ffff", it updates, I remove one f at a time, it keeps
updating, until I remove the last f and get an empty field, it just
keeps showing an f as value passed.
I type "hello", it updates, when I remove the entire string at once,
the value passed stays at hello.
I think the function is just not being called when the field is empty.
How would I fix this?
You state within your function:
if (str == "") {
return;
}
This means the function won't complete and the issue you're presenting will indeed happen. I assume you're emptying the livesearch element?
Since document.getElementById("livesearch").innerHTML = xmlhttp.responseText; is to be found in the else statement, it will never be executed.
Then it should be this:
if (str == "") {
document.getElementById("livesearch").innerHTML = "";
}
while leaving the rest as is.
So you empty it when str is empty, but you fill it when the ajax call is made.
p.s. the return; statement within the if statement is redundant. Since the if statement rings true, the else won't be executed either way.
edit: Also note that onkeyup might not trigger on someone copying text in instead of typing it. Although it's unlikely with a username, I thought it'd be a good thing to let you know, just in case.
-- the one that does catch this would be the oninput function.
More information here
I am relatively new to PHP and I am (trying to) developing my first AJAX code...
I am trying to pass an attribute from a select with several options, each option with its very own unique attribute "values" that is a String.
The PHP file GETs the value and does something with it (for instance prints it out). And the generated file is then returned to my main HTML page.
Here is the source code...
Here is my javaScript:
function showUser(myElement) {
var str = myElement.options[myElement.selectedIndex].getAttribute("values");
if (str == "") {
document.getElementById("myResponse").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myResponse").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
}
My HTML is as following:
<form>
<select name="users" onchange="showUser(this)">
<option values="">Select a person:</option>
<option values="Rasmus Lerdorf">Creator of PHP</option>
<option values="Linus Torvalds">Developed Linux</option>
<option values="Dennis Ritchie">Developper of C</option>
</select>
</form>
<br>
<div id="myResponse"><b>Person info will be listed here...</b></div>
My PHP is:
<?php
$q = intval($_GET['q']);
echo $q;
?>
I get 0 instead of the text string, what is wrong with my code?
Silly me,
I copied and pasted a basic example from a tutorial and I did not realize that the PHP code was casting the string that was sent over the GET to an integer.
$q = intval($_GET['q']);
The code should be :
$q = $_GET['q'];
On my earlier stage of the development I was indeed passing an integer, so the code was working.
The code returned 0 instead of an error because the intval of a string is 0 on failure.
Writing down the question here I realized the mistake...
Below is my textbox code
<input id="society_name" onBlur="showsociety(this.value)" />
<input id="societyid" name="society" />
Below is my javascript which call addressdata.php page...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showsociety(str)
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();}
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("societyid").value = data[i].societyid;
}
}
}
xmlhttp.open("GET","addressdata.php?q="+str,true);
xmlhttp.send();
}
</script>
Addressdata.php page
<?php
require_once('includes/config.php');
$q = $_GET['q'];
$city = $database->getRows("SELECT SM.id AS societyid,SM.society from societymaster SM WHERE SM.society = :society", array(':society'=>"$q"));
$info = array();
foreach($city as $row)
{
$cID = $row['societyid'];
$info[] = array('societyid' => $cID);
}
echo json_encode($info);
?>
I need to fetch id in multiple textbox like above given ex...in my form.
So is this possible to convert all php code to function in addressdata.php and call this function only from javascript...
FOR EX - i need to make whole php code of addressdata.php file as it is in function and call tis with below javascript on textbox blur event..
If I understood you correctly you want to add more text input elements into your page and be able to use this whole process of showing society on each of this elements.
The problem is not converting php code into a function (which would bring nothing).
What you want is to be able to tell showsociety() function which input element should it work on.
In the easiest case you can add additional parameter to the fucntion:
showsociety(str, id) {...}
And use this ID to search for correct element on the page.
[...]
document.getElementById(id).value = data[i].societyid;
[...]
.
<input id="society_name" onBlur="showsociety(this.value, this.id)" />
It can be done better but I think with such simple solution you should not have much problems.
Hope it helped.
I have three divs saved in an array as simple_html_dom objects. I needed to change a CSS property of two of them on the click of a button. That's easy, but then I also need to make that change in the CSS property (in the simple_html_dom object stored in the aforementioned array) in the PHP script on the server side.
So I figured from my web search I needed AJAX for this. So I read up this tutorial, and I am following this example, and doing something like:
On the client side:
function xyz(var divIdOne, var divIdTwo) {
document.getElementById(params.divIdOne).style.display = "none";
document.getElementById(params.divIdTwo).style.display = "block";
document.getElementById(params.divIdTwo).style.border = "5px solid red";
var xmlhttp;
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest();}
else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
On server side:
foreach($_REQUEST as $requestkey => $requestvalue) {
echo $requestkey.': '.$requestvalue;
}
if (array_key_exists('pass_back', $_REQUEST)) {
foreach ($array_of_divs as $div) {
if ($div->id=$divIdOne) {
$div->style='display:none';
} else if ($div->id=$divIdTwo) {
$div->style='display:block';
}
}
} else {echo 'FALSE!';}
The first foreach loop prints other variables but does not print pass_back. The next if block does not execute at all. The else block executes. This means that $_REQUEST clearly does not contain pass_back. Can anyone pinpoint why, or what I did wrong?
I fail to see the error. How do you check that you're not sending the data properly? I suggest using this piece of code in order to check what your server is receiving from your request:
function xyz() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);// Let's see what the server is echoing
}
}
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
Please, let us know the output.
I would recommend that you use jquery and firebug, and first get rid of the following problem: why is passback variable not received.
Create the file: test.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<title>Html page</title>
</head>
<body>
<script>
(function($){
$.post("myfile.php", {
passback: "pooo"
}, function(d){
console.log(d);
});
})(jQuery);
// or if you cannot use jquery
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// do something with the response, if you need it...
// document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "myfile.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("passback=pooo");
// src: http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp
</script>
</body>
</html>
Then create the file: myfile.php
<?php
if(isset($_REQUEST['passback'])){
echo "ok";
}
else{
echo "oops";
}
Next, download firefox, and download the firebug extension (or you can use chrome's console alternatively). The goal here is to see what is being passed through the network.
Launch test.php in a browser, open the firebug console (or chrome's console),
and debug until you see the "ok" message.
I'm trying to create a sort of chatbox system with PHP/MySql and AJAX but I'm having difficulties running my script in IE. I tested it in Google Chrome and it worked just fine. But when I test it in IE, the AJAX function that should get all messages from the database each 3 seconds, doesn't work properly. It does call the PHP script each 3 seconds and put the responseText into a div (displaying all messages found each 3 seconds). But the messages shown, are the same always ( untill I close the page and re-run the script ). Also when a new message is added to the database, it does not show up. It seems as if the responseText isn't 'updating'. These are my scripts:
(AJAX)
function getMessages(messengerid, repeat)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("messages").innerHTML=xmlhttp.responseText;
document.getElementById("messages").scrollTop = document.getElementById("messages").scrollHeight;
}
}
xmlhttp.open("GET","modules/get_messages.php?key=abcIUETH85i236t246jerst3487Jh&id="+messengerid,true);
xmlhttp.send();
if(repeat) {
setTimeout("getMessages("+messengerid+", 1);", 3000);
}
}
(PHP/MySql)
<?php
$key = "abcIUETH85i236t246jerst3487Jh";
if( ($_GET['key'] == $key OR defined('IS_INTERNAL')) AND (int)$_GET['id'] > 0) {
include_once("../config.php");
include_once("../class/system.class.php");
$sys = new system($template_name);
if(!$sys->connect($db)) {
exit();
}
$messages = $sys->getEntries("messages", " WHERE messenger_id = '".(int)$_GET['id']."' ORDER BY id ASC ");
$messenger = $sys->getEntries("messengers", " WHERE id = '".(int)$_GET['id']."' LIMIT 1");
$user1 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id1']."' ");
$user2 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id2']."' ");
$displaynames[$user1[0]['id']] = $user1[0]['displayname'];
$displaynames[$user2[0]['id']] = $user2[0]['displayname'];
foreach($messages AS $key => $message) {
if(is_numeric($key)) {
?>
<div class="message">
<b><?=$displaynames[$message['account_id']];?> (<?=date("h:m:s", $message['timestamp']);?>) says:</b> <br />
<?=nl2br($message['message_content']);?>
</div>
<?php
}
}
}
?>
Any help would be much appreciated!
Thanks in advance.
Best Regards,
Skyfe.
Your response is being cached. One way to fix this is to append a unique parameter in your request URL, such as the current timestamp.
Its a common problem with IE it caches the result.Add some dummy random parameter to your ajax call e.g current timestamp
i dont know about php but in jsp you can add the following code to your jsp page
response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
i know the post is old , i just replied for future viewers :D ;)