Mootool ajax readystate response is always 1? - ajax

I've been trying to make this mootools (ver: 1.2.4) Class to process my ajax requests. But my scripts only returns readystate 1. never gets to 2,3 ,or 4, the method handleHttpResponse only seems to run once. I'ves put alerts to see and I only get 1. any ideas?
var replyXML = new Class ({
/* GDW AJAX REQUEST SCRIPT */
/* By: Jonathan Robidas 2011-05-13 */
initialize : function(url){
this.http = this.getHTTPObject(); // We create the HTTP Object
this.url = url; // Requested server-side script
this.response = ''; // String returned by AJAX, Set after positive response
},
returnResponse : function() {
return this.response;
},
handleHttpResponse : function() {
alert(this.http.readyState);
if (this.http.readyState == 4) {
if(this.http.status==200) {
alert("YA YA 2");
this.response = this.http.responseText;
return true;
}
}
},
requestXML : function() {
this.http.open("GET", this.url, true);
//this.http.onreadystateshange = this.handleHttpResponse();
this.http.onload = this.handleHttpResponse();
},
getHTTPObject : function() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
});
This is how i launch it for now. my content is null but my url is a working XML file. so it shouldnt be blank... ?
<script language="Javascript" type="text/Javascript">
window.addEvent('domready', function() {
loadXML = new replyXML('gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59');
loadXML.requestXML();
content = loadXML.returnResponse();
alert(content);
/*
x=content.documentElement.childNodes;
for (i=0;i<x.length;i++) {
document.write(x[i].nodeName);
document.write(": ");
document.write(x[i].childNodes[0].nodeValue);
document.write("<br />");
}
*/
});
</script>
Tested on Google chrome, Firefox 4, Internet explorer 7 & 8, all same result.
Here is an example of XML the script is suppose to output: http://jerenovici.net/gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59 so I know my php generating the xml is fine.
Thanks!!

Why are you reinventing the wheel? If you're using mootools, making an ajax request is extremely easy (docs, referring to newest version, but in this case Request hasn't changed):
new Request({
url : './gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59',
onSuccess : function(responseText, responseXML){
/* here, do stuff with your response */
},
onFailure : function(xhr){
/* the XMLHttpRequest instance. */
}
}).send();
Then, are you sure the url is correct?

Related

AJAX call to ASP page to update database record works only once in IE9

After several pieces of helpful advice from the members of this forum I'm getting closer to solving what should be a simple issue. I'm a complete newbie to AJAX.
Can someone please tell me why this piece of code works fine in Firefox 8 but not in IE 9? It works ONCE in IE but not again unless I close the browser and reopen!!??
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch(e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if (ajaxRequest.readyState == 4) {
}
}
ajaxRequest.open("GET", "disp_processTEXT.asp", false);
ajaxRequest.send(null);
}
//-->
</script>
The readystate is left blank as it is copied code which originally assigned a value to a div but I only want to run the database code in the asp page. Presumably this could have been deleted?
The code to be run in the asp page is
<%
Set MyConn = Server.CreateObject("ADODB.Connection")
MyConn.Open "dsn=xxx;uid=xxx;password=xxx;"
SQLString = "UPDATE dbo_tbl_printing_tempstore SET front_has_text1 = 'YES', front_text = 'help' WHERE id = 106567"
MyConn.Execute(SQLString)
MyConn.Close
Set MyConn = Nothing
%>
Please help me as this is driving me mad.
Many thanks
Switch to jQuery and its Ajax system as it should be cross browser compatable out the box, and saves you huge amounts of time:
Add a reference for jQuery:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
and switch to its Ajax method (place below the above):
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'disp_processTEXT.asp',
success: function(response) {
alert('It worked');
}
});
});
</script>
Update:
To bind to the onblur event using jQuery try this. Remove the onblur= attribute from your current code.
$(document).ready(function() {
$('#yourinput').on('blur', function(){
$.ajax({
url: 'disp_processTEXT.asp',
success: function(response) {
alert('It worked');
}
});
});
});
Demo: http://jsfiddle.net/qmPLj/
Try this. It has worked for me across all browsers but some Opera versions.
function GetXmlHttpObject(handler)
{
var objXmlHttp=null;
if(navigator.userAgent.indexOf("MSIE")>=0)
{
var strName="Msxml2.XMLHTTP";
if(navigator.appVersion.indexOf("MSIE 5.5")>=0)
{
strName="Microsoft.XMLHTTP";
}
try
{
objXmlHttp=new ActiveXObject(strName);
objXmlHttp.onreadystatechange=handler;
return objXmlHttp;
}
catch(e)
{
alert("Error. Scripting for ActiveX might be disabled");
return;
}
}
else //All other browsers
{
objXmlHttp=new XMLHttpRequest();
objXmlHttp.onload=handler;
objXmlHttp.onerror=handler;
return objXmlHttp;
}
}
var url= "http://www.example.com/";
xmlHttp=GetXmlHttpObject(stateChanged);
xmlHttp.open("GET", url , true);
xmlHttp.send(null);

Ajax , html5, Fancybox.js

I am having problems with using Ajax and Fancybox.js photo viewer together.
I have a website set up first as web 1.0 with the standard navigation with hyperlinks.
but for html5 browsers I'm am using javascript that creates a web 2.0 experience.
The javascript first highjacks the links onclick event which makes a XMLHttpRequest that calls a php script that parses the html and sends back just the part of the html that I want to replace. I am using pushState and popState to get the back and forward buttons to function.
It is working great, it creates the Ajax effect, while persevering all the advantages of web 1.0 including SEO, because the links as far as the search engine spiders are concerned the links are just standard links to standard html pages.
The problem is that one of the pages uses Fancybox.js to show photos, it works fine when the page is accessed via the standard url, but when the html is accessed via the Ajax scripts if breaks it.
Here is code for the Ajax,
if (history.pushState) {
function changeContent(url) {
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('content').innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "getContents.php?url=" + url, true);
xmlhttp.send();
}
$(document).ready(function() {
var elems = null,
links = null,
link = null,
i;
elems = document.getElementById('nav');
links = elems.getElementsByTagName('a');
if (links) {
for (i = 0; i < links.length; i++) {
links[i].addEventListener("click", function(e) {
url = $(this).attr("href");
var pathArray = window.location.pathname.split( '/' );
var n = pathArray.length;
changeContent(url);
history.pushState(null, null, url);
e.preventDefault();
var urlstr = window.location,
index = /index/g,
program = /program/g,
photos = /photos/g,
testimonials = /testimonials/g,
about = /about/g,
contact = /contact/g;
if (program.test(urlstr)){
changeCurrentPage('#program');
document.title = "Our Programs Kolibri Daycare";
}else if (photos.test(urlstr)){
changeCurrentPage('#photos');
document.title = "Photos Kolibri Daycare";
slideShow();
}else if (testimonials.test(urlstr)){
changeCurrentPage('#testimonials');
document.title = "Tesimonials Kolibri Daycare";
}else if (about.test(urlstr)){
changeCurrentPage('#about');
document.title = "About Kolibri Daycare";
}else if (contact.test(urlstr)){
changeCurrentPage('#contact');
document.title = "Contact Kolibri Daycare";
}else {
changeCurrentPage('#home');
document.title = "Kolibri Daycare";
}
}, false);
}
}
window.setTimeout(function() {
window.addEventListener("popstate", function(e) {
var pathArray = window.location.pathname.split( '/' );
var n = pathArray.length;
if (pathArray[n-1]){
changeContent(pathArray[n-1]);
}else {
changeContent('index.html');
}
}, false);
}, 1);
});
}
and her is the script that calls Fancybox.js,
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
$("a[rel=example_group]").fancybox({
'overlayShow' : false,
'cyclic' : true,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic'
});
});
//]]>
</script>
It is in the head section of the page.
When the html that has the photo links is brought in via Ajax the script that calls fancybox.js is not included. I have tried calling it in different places but nothing seems to work. Does anyone have any ideas?
You need to re-initialize fancybox on the new elements added from ajax. I'm not sure why you don't just upgrade the entire page to HTML5 and use some of the ajax functions provided by jQuery, but I think the re-initialization should be inserted after this line (not tested!):
document.getElementById('content').innerHTML = xmlhttp.responseText;
$('#content').find("a[rel=example_group]").fancybox();

AJAX Ready State stuck on 1

Hi I can see this has been discussed but after perusing the issues/answers I still don't seem to be able to get even this simple AJAX call to bump out of ready state 1.
Here's the Javascript I have:
<script language="javascript" type="text/javascript">
var request;
function createRequest()
{
try
{
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
function loadClassesBySchool()
{
//get require web form pieces for this call
createRequest(); // function to get xmlhttp object
var schoolId = getDDLSelectionValue("ddlSchools");
var grade = getDDLSelectionValue("ddlGrades");
var url = "courses.php?grades=" + escape(grade) + "&schoolId=" + escape(schoolId);
//open server connection
request.open("GET", url, true);
//Setup callback function for server response
//+++read on overflow that some fixed the issue with an onload event this simply had
//+++the handle spitback 2 readystate = 1 alerts
request.onload = updateCourses();
request.onreadystatechanged = updateCourses();
//send the result
request.send();
}
function updateCourses()
{
alert('ready state changed' + request.readyState);
}
function getDDLSelectionValue(ddlID)
{
return document.getElementById(ddlID).options[document.getElementById(ddlID).selectedIndex].value;
}
</script>
The PHP is HERE just a simple print which if i navigate to in the browser (IE/Chrome) loads fine:
<?php
print "test";
?>
I'm quite new at this but seems like I can't get the most bare bones AJAX calls to work, any help as to how work past this would be greatly appreciated.
All I get out of my callback function 'updateCourses' is a 1...
Well after more digging I actually gave up and switched over to jQuery which should for all intents and purposes be doing the EXACT same thing except for the fact that jQuery works... I was just less comfortable with it but so be it.
Here's the jQuery to accomplish the same:
function loadCoursesBySchool(){
var grades = getDDLSelectionValue("ddlGrades");
var schoolId = getDDLSelectionValue("ddlSchools");
jQuery.ajax({
url: "courses.php?grades=" + grades + "&schoolId=" + schoolId,
success: function (data) {
courseDisplay(data);
}
});
}
function courseDisplay(response)
{
//check if anything was setn back!?
if(!response)
{
$("#ddlCourses").html("");
//do nothing?
}
else
{
//empty DLL
$("#ddlCourses").html("");
//add entries
$(response).appendTo("#ddlCourses");
}
}

AJAX doesn't send POST query

$(document).ready(function() {
function ajaxselectrss(rssurlvar) {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('news');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
//var rssurlvar = $(this).attr("title");
var queryString = "rurl=" + rssurlvar;
var urltofile = "rssget.php";
ajaxRequest.open("POST", urltofile, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", queryString.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(queryString);
}
$(".rshownews").click(function() {
window.setInterval(function() {ajaxselectrss($(this).attr("title"))}, 1000);
});
});
The POST query is "undefined" (Firebug).
You should use $.ajax - it will standardise the whole XmlHTTPRequest thing across browsers.
$.ajax({
type: "POST",
url: "rssget.php",
data: queryString,
success: function(data) {
$('#news').html(data);
}
});
(And, BTW, if you setInterval in your click handler, you will start a new periodic call to your ajaxselectrss function every time the button is clicked.)
Also, your context has changed due to the wrapper function. Try changing your click handler like so:
$(".rshownews").click(function() {
var _this = this;
window.setInterval(function() {ajaxselectrss($(_this).attr("title"))}, 1000);
});
Since you seem to use jquery anyway ($(document).ready) you could use it's wrapper for simplifying ajax-requests.
http://api.jquery.com/jQuery.post

AJAX Response not working in FF

I have a bit of code which alerts the $response from a php code in IE, but for some reason it doesn't work in FF..
Here's the code:
function contactfunction() {
var url = "scripts/php/cbb.php?pname=";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatecontact1;
xmlHttp.send(null);
}
function updatecontact1() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
alert(response);
}
}
And here's the PHP file (cbb.php)
<?php
$fp=fopen("ip.txt","a+");
fwrite($fp, "cib\r\n");
fclose($fp);
$response = "something";
return $response;
?>
Can anyone help me out here? I'm not sure how to get it to work in FF, it just gives a blank popup..
Do yourself a favour, and use one of the many ajax capable Javascript libraries out there, like jQuery, which frees the user from hacking up code to deal with browser discrepancies (for the most part, at least):
//using jQuery's $.get method
function update(name) {
$.get('cbb.php?name=' + name, function(response) {
alert(response);
$('#someDiv').html(response);
});
}
or:
//using jQuery's $.load method
function update(name) {
//directly inject div id="someDiv" with output of url
$('#someDiv').load('cbb.php?name=' + name);
}
Putting it together:
//when the DOM is ready
$(document).ready(function() {
//bind to click event of all anchors with class="contact"
$('a.contact').click(function(e) {
//stop the link from being followed
e.preventDefault();
//get the name from the link text
var name = $(this).text();
update(name);
});
});
Timmy
McLovin
<div id="someDiv">This is where the output will be injected</div>
See http://docs.jquery.com/Ajax for more information.
I managed to get the code working by using:
function getFile(fileToOpen) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.open("GET",fileToOpen,false);
xmlhttp.send(null);
alert( xmlhttp.responseText );
}
function contactfunction() {
getFile('scripts/php/cbb.php?pname=');
}
If anyone else has the same problem :)

Resources