xmlHttpRequest issues in a Google-like autosuggestion script - javascript

I am trying to build up an autosuggestion search field similar to Google Suggestion (or Autosuggestion?).
I am using pure javaScript/AJAX and 2 files: index.php and ajax-submit.php (is the file where I will actually query the database). But for moment I am simply echo a text for debugging.
There are a few issues:
Issue 1: The issue is the firebug outputs: xmlhttp is not defined as soon as I type something in the search input [solved, see below].
Issue2: I would like also to echo the content of the search input something like this:
echo $_GET['search_text'];
or
if(isset($_GET['search_text'])) {
echo $search_text = $_GET['search_text'];
}
but I get the following error: *Undefined index: search_text in ajax-submit.php*
So here is my function suggest call:
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
And here is my function suggest():
<script type="text/javascript">
//function does not needs params because is unique to the input search_text
function suggest() {
//browser object check
if(window.xmlHttpRequest) {
xmlhttp = new xmlHttpRequest();
}
else if (window.ActiveXObject) {
//console.log("error");
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
//when the onreadystatechange event occurs
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementByID('results').innerHTML = xmlhttp.responseText;
}
}//end onready
xmlhttp.open('GET', 'ajax-submit.php', true);
xmlhttp.send();
}//end suggest
</script>
and here is my php ajax-submit file:
<?php
echo 'Something';
?>
Can someone help me debug? It might be a scope issue but I have no clue.
The second question would be how would you normally debug an Ajax request in Firebug?
Thanks

Actually, it is
XMLHttpRequest()
not
xmlHttpRequest()
To have a true cross-browser compliant XHR object creation, go with this:
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
var xhr = ( function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());

Use:
new XMLHttpRequest
not
new xmlHttpRequest

I wrote a better implementation: cross-browser/more readable code, function splits. Below is the code. Unfortunately tough reads php echo text it won't read the variable search_text, I don't know why:
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php?search_text="+document.search.search_text.value");
}
</script>
and HTML code:
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and ajax-submit.php:
<?php
//echo 'Something';//'while typing it displays Something in result div
echo $_GET['search_text'];
?>

Related

JavaScript Not Returning Data But No Error Either

I am calling a php file that queries my database and returns a result. I have verified that the php file accurately returns the data as needed, but my calling page is not updated from the JavaScript.
What do I need to alter in my syntax below so that the returned value is returned on page?
<script type="text/javascript">
function boostion()
{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("data").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
EDIT
I have also opened Developer Options in Chrome and checked the Console and there are no errors or issues displayed, everything is a success!
Edit 2
I tried to use the JQuery approach below and used this syntax - but I get the error
Uncaught TypeError: $(...).load is not a function
Syntax:
<script src="https://code.jquery.com/jquery-3.1.1.slim.js"
integrity="sha256-5i/mQ300M779N2OVDrl16lbohwXNUdzL/R2aVUXyXWA="
crossorigin="anonymous" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
document.getElementById("data").innerHTML = data;
});
});
</script>
Edit 3
This is my php syntax that runs the sql syntax and echo result that I want to have returned from the javascript
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'host';
$option['user'] = 'user';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance( $option );
$result = $db->getQuery(true);
$result->select($db->quoteName(array('trackandfieldresults')));
$result->from($db->quoteName('[TrackData]'));
$db->setQuery($result);
$row = $db->loadRowList();
echo $row['0']
?>
Use xhr.send();
If it is a GET request, you have to apply the query string in in xhr.open and you dont have to set Content-type:application/x-www-form-urlencoded
first, the scripts should be inside the HTML before the ending body tag. then you open another file and write your code in it. JQUERY does not have script tag. Sp you are creating an external javascript file for the script. No script tag needed. Now use this format.
$(window).on('load', function(e){
e.preventDefault();
var dat = //the content you are trying to load
$.get('middleware.php', dat, function(data){
$('#selector').html(data)
});
})
I have a faster approach using JQuery.
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
//Do whatever you want here
});
});
This should do the Job. Your approach is old and kind of complicated to debug
Try this
function boostion(){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.send();
xhr.onreadystatechange = function(){
console.log(xhr);
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("data").innerHTML = xhr.responseText;
}
}
}
<div id="data"></div>
<button onclick="boostion();">Load</button>

Self-made calculator doesnt work

I wrote small calculator script with JS and PHP. As i saw all is correct, but in output server show me blank ('0') value. I cant find a solution for 2 hours.
JS script, that open connection with POST method with action 'calc.php':
<script type="text/javascript">
function getXmlHttp() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function summa() {
var how0 = document.getElementById("how0").value;
var xmlhttp = getXmlHttp();
xmlhttp.open('POST', 'calc.php', true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("how0=" + encodeURIComponent(how0));
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("how").value = xmlhttp.responseText; //
}
}
};
}
</script>
Form for calculating:
<input type="number" required name="how0" id="how0" min="100" max="999999" placeholder="100">
<input type="number" required readonly name="how" id="how" min="200" max="999999" placeholder="200">
<input type="button" value="Calcul" onclick="summa()" />
Calc.php for checking:
<?php
$a = is_numeric($_POST["how0"]);
$a = floor($a);
if ($a>1) {
$a = $a * 2;
}
if ($a>10000) {
$a = $a * 3;
}
echo $a;
?>
This line:
$a = is_numeric($_POST["how0"]);
Assigns the return value of is_numeric to $a — e.g., true or false. Then you use $a as though it contained the value posted to the script, but it doesn't.
You probably meant to use intval or floatval or similar:
$a = intval($_POST["how0"]);
Note that unless you need to support really old browsers, there's no need for your getXmlHttp function. All vaguely-modern browsers support new XMLHttpRequest.

Javascript data input Json

I have data on a website which looks like this
[{"id":213877,"pic":"https://graph.facebook.com/ariel.barack/picture?type=square","url":"https://angel.co/ariel-barack","name":"Ariel Barack","type":"User"},{"id":109396,"pic":"https://d1qb2nb5cznatu.cloudfront.net/users/109396-medium_jpg?1405528556","url":"https://angel.co/mattbarackman","name":"Matt Barackman","type":"User"},{"id":881384,"pic":null,"url":"https://angel.co/austin-barack","name":"Austin Barack","type":"User"},{"id":245752,"pic":null,"url":"https://angel.co/drgoddess","name":"Dr. Goddess","type":"User"}]
I have a html file with javascript code as follows:
function httpGet(url) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
var data = xmlHttp.responseText;
data = (JSON.parse(data));
I need to access the "name" attribute from the URL database and form a string concat of all the name attributes. Could you please help me out what to be done next?
Below is my test data
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name);
For Example if you want to acces the name you can access as like above.
To concatenate the vales do like below
var Output = json.map(function(result) {
return result.name;
}).join('');
alert(Output);
Have a look on it https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var result = data.map(function(user) {
return user.name;
}).join('');
<html>
<head>
<script type="text/javascript">
function fun(){
var str='[{"id":213877,"pic":"https://graph.facebook.com/ariel.barack/picture?type=square","url":"https://angel.co/ariel-barack","name":"Ariel Barack","type":"User"},{"id":109396,"pic":"https://d1qb2nb5cznatu.cloudfront.net/users/109396-medium_jpg?1405528556","url":"https://angel.co/mattbarackman","name":"Matt Barackman","type":"User"},{"id":881384,"pic":null,"url":"https://angel.co/austin-barack","name":"Austin Barack","type":"User"},{"id":245752,"pic":null,"url":"https://angel.co/drgoddess","name":"Dr. Goddess","type":"User"}]';
var obj=eval(str);
var names='';
for(var item in obj){
names+=obj[item].name;
}
alert(names);
}
</script>
</head>
<body>
<input type="button" onclick="fun()" value="click me"/>
</body>
</html>
I got what you mean.It is the Ajax problem.If you really use the code that you provided,it should not work.Here is the Ajax code to get response from a certain url:
var ajaxRequest;
//create ajax object
function createAjaxRequest() {
var xmlhttp = null;
if (window.XMLHttpRequest) {// code for all new browsers
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {// code for IE5 and IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
//send request and identify callbak handler
function send(url) {
ajaxRequest = createAjaxRequest();
ajaxRequest.onreadystatechange = callback;
ajaxRequest.open("POST", url, true);
ajaxRequest.send(null);
}
// the callback handler
function callback() {
if (ajaxRequest.readyState == 4) {// 4 = "loaded"
if (ajaxRequest.status == 200) {// 200 = OK
var data = ajaxRequest.responseText;
}
else {
alert("Problem retrieving data");
}
}
}

PHP ajax call failure

I am new to ajax and trying to create AJAX->PHP connection. I am using the following code
file1.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<input type="text" id='demo'>
<input type="button" onclick='ajaxCall()' value='23' >
<script>
function ajaxCall()
{
document.getElementById('demo').value="343434";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.requeststate==4 && xmlhttp.status==200){
document.getElementById('demo').value="4444343434";
document.getElementById('demo').value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>
</body>
</html>
and the corresponding test.php
<?php
echo "me";
?>
Now when I click the button, the value of textbox is changing to 343434 but not changing on AJAX call, even it does not change to 4444343434. I'm currently runnning php 5.5.6 on ubuntu 14.04LTS.
Change xmlhttp.requeststate to xmlhttp.readyState
Try use the following crossbrowsing function
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
And change xmlhttp = new XMLHttpRequest(); to xmlhttp = new getXmlHttp();
And this work without jQuery.

How to retrieve an element from an ajax call

I want to retrieve all elements from an ajax call, then insert them into another element without:
using jquery (I just want to use pure JavaScript)
creating a new element to contain the ajax response
Here's what I have tried:
index.php
<!DOCTYPE HTML>
<head>
<script type="text/javascript">
function loadPage() {
var ajax = new XMLHttpRequest();
ajax.open('GET', 'test.php', true);
ajax.onreadystatechange = function (){
if(ajax.readyState === 4 && ajax.status === 200){
document.getElementById('output').appendChild( ajax.responseText ) ;
}
};
ajax.send();
}
loadPage();
</script>
</head>
<body>
<div id="output">
<h1>Default</h1>
</div>
</body>
</html>
test.php
<h1>
its work
</h1>
<div>
<h2>
its work2
</h2>
</div>
I already googled it, but the answer was always to use jQuery.
Node.appendChild requires a Node object as an argument. What you're getting from test.php is a string. Try using innerHTML instead
document.getElementById('output').innerHTML = ajax.responseText;
As of XHR level 2, you can simply attach an onload handler to XHR instead of checking the readyState and status properties.
ajax.onload = function() {
document.getElementById('output').innerHTML += this.responseText;
}
have you looked at this
http://w3schools.com/ajax/ajax_examples.asp
http://w3schools.com/ajax/tryit.asp?filename=tryajax_first
I think the most of the examples that you find use jquery because jquery makes it cross browser
try this one
function loadPage(){
var strURL="test.php";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('output').value=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
function getXMLHTTP() { //function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}

Categories

Resources