Cant detect the file in ajax - javascript

Hey guys am new to ajax I have a php file and a ajax file. I just want to detect the php file from the ajax so I have send a request in ajax like
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
} else {
console.log('file not fetched');
}
xmlhttp.open("GET","first.php?m=babe",true);
xmlhttp.send();
}
}
loadXMLDoc();
</script>
</head>
<body>
</body>
</html>
My php file
<?php
include("ajax.html");
$p = $_REQUEST['m'];
if($p == 'babe') {
echo true;
}
When I run the ajax.html on localhost it doesn't show me any message in the window nor in the console.
Can you guys tell me why is it like this?
Thanx for the help

Some of your brackets were wrong:
function loadXMLDoc(){
var xmlhttp;
if(window.XMLHttpRequest){ // This bracket was missing
xmlhttp=new XMLHttpRequest();
}
else{ // This bracket was missing
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
}
else{
console.log('file not fetched');
}
} // This bracket was on the wrong place (it enclosed the .open() and .send())
xmlhttp.open("GET","first.php?m=babe",true);
xmlhttp.send();
}
loadXMLDoc();
Also, a simpler way of defining the callback function is:
xmlhttp.onload=function(){
if(xmlhttp.status==200){
alert(xmlhttp.responseText);
}
else{
console.log('file not fetched');
}
}

Related

Javascript XMLHttpRequest onreadystatechanged not firing?

I have an html file and a .txt file in the same directory hosted on a webserver. The html file contains the following code:
<html>
<head>
<script>
window.onload = function() {
receiveMessage();
}
function receiveMessage() {
var xmlhttp = new XMLHttpRequest;
xmlhttp.open("GET", "message.txt", true);
xmlhttp.send();
xmlhttp.onreadystatechanged = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
}
</script>
</head>
<body>
</body>
</html>
Since the text file message.txt contains "hello world", a javascript alert box containing that message should pop up when the response is received, but it's not. What am I doing wrong?
The property you are looking for is onreadystatechange not onreadystatechanged. There is no d on the end.
reorder the request and change function onreadystatechanged to onreadystatechange:
function receiveMessage() {
var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","message.txt",true);
xmlhttp.send();
}
put the open and send calls after the onready statechanged event like in http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>

Multiple ajax requests not working after a while

I have my page which loads live stock data from server continuously (every second) making request to a php file named data.php. Also I have a Ganns square of 9 calculator that passes value to a PHP file (getdata.php) using ajax through a OnKeyUp function of a textbox and returns some output.
The issue is-
As the page loads both work perfectly. Live data as well as calculator can be used. But after a while the calculator doesn't work. On writing value into the textbox the request must be processed and value must be returned through ajax call, but it doesn't happen.
Live Stock data code (refreshes every sec):
<script>
function showPort(t)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("portfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data.php",true);
xmlhttp.send();
setTimeout(showPort,t);
}
</script>
It runs using on page load-
<body onload="JavaScript:showPort(2000);">
Ganns square calculator code which runs onkeyup event of textbox:
<script>
function showData(str)
{
if (str.length==0)
{
document.getElementById("txtData").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtData").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getdata.php?a="+str,false);
xmlhttp.send();
}
</script>
Runs onKeyUp event of textbox-
<input type="text" placeholder="Last traded Price" name="str" onKeyUp="showData(this.value)">
I tried searching for similar questions but did not get my answer. Thus, posting this issue as a new question here.
The first script:
function showPort(t)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("portfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data.php",true);
xmlhttp.send();
setTimeout(showPort,t);
}
Can be converted this way:
$(document).ready(function(){
setInterval(function(){
$.get("data.php", function(data){
$("#portfo").html(data);
});
}, 2000);
});
And the next one:
function showData(str)
{
if (str.length==0)
{
document.getElementById("txtData").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtData").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getdata.php?a="+str,false);
xmlhttp.send();
}
Can be rewritten as:
function showData(str)
{
if (str.length==0)
{
$("#txtData").html("");
return;
}
$.get("getdata.php?a="+str, function(data){
$("#txtData").html(data);
});
}
Can you please try executing the above code and see if it works? Don't forget to include jQuery this way:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">

Ajax call to get Data

Dear I want to get Variable Value form PHP Value, and I want to write an ajax call in Java Script, tags,
How it is possible,
I want to get Value from get_result.php file,
and I have following code in get_result.php:
<?php
echo $val="abc";
?>
and I wrote follwing code in another file named ajax.php:
<script>
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url="<?php echo "get_result.php"; ?>";
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
var ok xmlhttp.responseText;
alert(ok);
</script>
is there any bug and Where?
I want to get value from get_result.php file and show this value in an Alert;
You can use jQuery. but for your code, you didn't assign the response
<script>
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url="get_result.php";
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
var ok = xmlhttp.responseText;
alert(ok);
The below code will help you in returning the value from the php page
<script>
function myfun()
{
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)
{
var demo=xmlhttp.responseText;
alert(demo);
}
}
xmlhttp.open("GET","result.php",true);
xmlhttp.send();
}
</script>
body
<body>
<input type="button" onclick="myfun();"/>
</body>

How to fetch parameters from ajax post request

The Javascript code is:
var str = "html=<p>Some htmlcode here<p><div>more htmlcode </div>";
saveProject(str);
function saveProject(str) {
if (str=="") {
return;
}
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);
}
}
xmlhttp.open("POST","../demo.asp",true);
xmlhttp.send(str);
}
and the ASP file:
<%
response.expires=-1
x = Request.Form("html")
response.write x
%>
I need to fetch the str passed to xmlhttp.send() method and do some useful stuffs, but it looks like I'm missing something. The response is (an empty string). Any help is a appreciate!
Adding the request header solve the problem.
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

How do you make this ajax example work on opera and firefox?

I have a quick question, the following only works on IE 7 and above, how can I make it work on firefox and opera aswell?
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.tdsoft.se/index.html",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Edit
Thanks for all your answers, now I just have another question regarding the followng code
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
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)
{
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.html",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Now I want to search through the xmlhttp.responseText (in other words call the function loadXMLDoc()) for key words, like for example "testfile" and if it exists multiple example "testfile_1" and "testfile_2"....."testfile_n" then "doSomething"
like this
function searchADocument(wordToSearchFor){
int numberOfTimesWordOccurs=0;
var thePageToSearchThrough [] = loadXMLDoc();
for (i=0; i<thePageToSearchThrough.length; i++){
if(thePageToSearchThrough[i]==wordToSearchFor)
numberOfTimesWordOccurs++;
}
If (wordToSearchFor > 1)
document.write(" testfile_1" testfile_2 testfile_n
)
Else
window.location="http://selnc05.go.se:8080/component_test/build/testfile.html";
}
I don't know where to start since I don't know what type xmlhttp.responseText is, can I store it in an array and scan it using for loop etc?
Thanks in advance. =)
Try something like this:
ajax("http://www.tdsoft.se/index.html", function(data) {
document.getElementById("myDiv").innerHTML = data;
});
Code
function getXmlHttpObject() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function ajax(url, onSuccess, onError) {
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status != 200) {
if (typeof onError == 'function') {
onError(this.responseText);
}
}
else if (typeof onSuccess == 'function') {
onSuccess(this.responseText);
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}​

Categories