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.
Related
I am changing my question What is missing or wrong in this code When user type something in the textboxt onother texbox supposed to get server time But nothing happens.I am so inexperience with programming.Can you plase help
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
Response.Write(DateTime.Now.ToShortTimeString());
Response.End();
}
<script type="text/javascript">
function ajaxFunction() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
document.getElementById("user").value = xmlHttp.responseText;
}
else {
document.getElementById("label").innerHTML = "wait";
}
xmlHttp.open("GET", "Default.aspx", true);
xmlHttp.send(null);
}
}
</script>
<title></title>
</head>
<body>
<input id="user" type="text" onkeyup="ajaxFunction()"/>
<p>
<input id="time" type="text" /></p>
<div id="label">
</div>
<p>
</p>
</body>
</html>
You misplaced the call to actually start the request
function ajaxFunction() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
document.getElementById("user").value = xmlHttp.responseText;
} // closes the if
else {
document.getElementById("label").innerHTML = "wait";
} // closes the else
} // closes the function() for onreadystatechange
// call the stuff
xmlHttp.open("GET", "Default.aspx", true);
xmlHttp.send(null);
}
I'm trying to familiarize myself with Ajax as I will need to use it continually for work. I'm working through the W3Schools tutorial trying things with my Apache2 server. I have a file called ajax_info.txt on the server (under /var/www (ubuntu)). I'm making a call to it and with Firebug I see I get a good response (4 & 200) but it isn't outputting the contents of the file to the DOM. Here's the code:
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
var url = "http://192.168.0.5/ajax_info.txt";
function loadXMLDoc(url, cfunc) {
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 = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction() {
loadXMLDoc(url, function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv">
<h2>Let AJAX change this text</h2>
</div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
I'm not exactly sure what it is I'm doing wrong. The w3schools tutorial isn't exhaustive by any stretch. I plan on buying a book, but I'd love to learn these simple GET calls as it will get me headed in the proper direction. Any suggestions would be greatly appreciated.
function ajax(x) {
var a;
if (window.XMLHttpRequest) {
a = new XMLHttpRequest();
} else if (window.ActiveXObject) {
a = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Browser Dosent Support Ajax! ^_^");
}
if (a !== null) {
a.onreadystatechange = function() {
if (a.readyState < 4) {
//document.getElementById('cnt').innerHTML = "Progress";
} else if (a.readyState === 4) {
//respoce recived
var res = a.responseText;
document.getElementById('center_scrolling_div').innerHTML = res;
eval(document.getElementById('center_scrolling_div').innerHTML);
}
};
a.open("GET", x, true);
a.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
a.send();
}
}
I have Apache set on my home pc.
A page called ajax.html has xmlhttp request set on a button. (for fetching a html page main.html residing in same directory)
Whenever i click on button, nothing happens, i have set response as text.
Below is javascript code.
function()
{ var httpRequest; document.getElementById("ajaxButton").onclick = function() { makeRequest('main.html'); };
function makeRequest(url) {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', url);
httpRequest.send(); }
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
} } })();
html code;
<html>
<head>
<title>Ajax Demo</title>
</head>
<body>
<input type="button" id="ajaxButton" value="Click" />
<script type="text/javascript" src="ajax.js">
</script>
</body>
</html>
I am trying to load some content dynamically in my HTML div. If I try to do this, I get an error: Syntax error HOME. (this is the content that should be visible within the div).
HTML:
Navigation bar:
<li>Home</li>
Div to be filled:
<div id="pagepanel"></div>
home.html
HOME.
Javascript:
function replaceContent(newDiv) {
var xmlHttp = createXMLHttp();
xmlHttp.onreadystatechange = function(){replace(xmlHttp);}
xmlHttp.open("GET", newDiv, true);
xmlHttp.send(null);
}
function replace(xmlHttp) {
if (xmlHttp.readyState==4 && xmlHttp.status==200){
document.getElementById("pagepanel").innerHTML=xmlHttp.responseText;
}
alert(xmlHttp.responseText);
}
function createXMLHttp() {
var xmlHttp;
if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else{
alert("Please upgrade your browser! Your browser does not support AJAX!");
}
return xmlHttp;
}
The error occurred due to the lack of a semi-colon.
onclick="replaceContent('home.html')";>Home</a></li>
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'];
?>