I am searching for a Javascript Library Which has only AJAX no other feature. e.g. a Small Simple XMLHttp Wrapper.
microajax is what I settled on.
This is not a library but it is a "Small Simple XMLHttp Wrapper" I made:
//params format:"bob=hi&id=1295&lol=haha"
function ajax_post(post_url,params,success_callback,fail_callback,timeout)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST",post_url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
//xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState == 4 )
{
clearTimeout(xmlHttpTimeout);
if(xmlHttp.status == 200)
{
success_callback();
}
else
{
fail_callback();
}
}
}
xmlHttp.send(params);
var xmlHttpTimeout=setTimeout(ajaxTimeout,timeout);
function ajaxTimeout()
{
xmlHttp.abort();
fail_callback();
}
}
function ajax_get(url,success_callback,fail_callback,timeout)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET",url, true);
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState == 4 )
{
clearTimeout(xmlHttpTimeout);
if(xmlHttp.status == 200)
{
success_callback(xmlHttp.responseText);
}
else
{
fail_callback();
}
}
}
xmlHttp.send();
var xmlHttpTimeout=setTimeout(ajaxTimeout,timeout);
function ajaxTimeout()
{
xmlHttp.abort();
fail_callback();
}
}
Here' a small chunk of a JavaScript PHP wrapper I wrote a long time ago when I virtually knew nothing about JavaScript... it barely contains any AJAX methods, just wrapper functions that communicate with a PHP backend in order to allow PHP to do all the work...
In all honesty, to get what it seems you're looking for... just sit down and write yourself an AJAX library with all the common helper functions. It should take you a few hours at the most.
The Javascript:
(function() {
var
PHPJS = window.PHPJS = window.$ = function() {
return new PHPJS.Strings;
};
PHPJS.Strings = PHPJS.prototype = {
InitAJAX: function(Library, ServerString)
{
var ResultCache = document.body;
var FunctionRequest;
try {
FunctionRequest = new XMLHttpRequest();
} catch (e) {
try {
FunctionRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
FunctionRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
throw new Error("The XMLHttpRequest() object is not supported by your browser.")
return false;
}
}
}
FunctionRequest.onreadystatechange = function() {
if (FunctionRequest.readyState == 4 && FunctionRequest.status == 200) {
ResultCache.innerHTML = FunctionRequest.responseText;
return FunctionRequest.responseText;
}
}
switch (Library) {
case 'Arrays' :
FunctionRequest.open("GET", "functions/arrays-lib.php" + ServerString, true);
break;
case 'Math' :
FunctionRequest.open("GET", "functions/math-lib.php" + ServerString, true);
break;
case 'Strings' :
FunctionRequest.open("GET", "functions/strings-lib.php" + ServerString, true);
break;
}
FunctionRequest.send(null);
},
/* String Functions */
addcslashes: function(str, charlist)
{
return this.InitAJAX('Strings','?function=addcslashes&String='+str+'&Charlist='+charlist);
},
addslashes: function(str)
{
return this.InitAJAX('Strings','?function=addslashes&String='+str);
},
bin2hex: function(str)
{
return this.InitAJAX('Strings','?function=bin2hex&String='+str);
},
chop: function(str,charlist)
{
return this.InitAJAX('Strings','?function=chop&String='+str+'&Charlist='+charlist);
},
chr: function(int)
{
return this.InitAJAX('Strings','?function=chr&Int='+int);
},
chunk_split: function(str, chunklen, end)
{
return this.InitAJAX('Strings','?function=chunk_split&String='+str+'&Chunklen='+chunklen+'&End='+end);
},
convert_cyr_string: function(str)
{
return this.InitAJAX('Strings','?function=convert_cyr_string');
},
/* more functions... */
}
})();
//PHPJS.bin2hex('afsdfadsafdsafdasfsaf');
The PHP:
<?php
switch($_GET['function']) {
case 'addcslashes' :
$charlist = (#$_GET['Charlist']) ? ','.$_GET['Charlist'] : '';
echo addcslashes($_GET['String'], $charlist);
break;
case 'addslashes' :
echo addslashes($_GET['String']);
break;
case 'bin2hex' :
echo bin2hex($_GET['String']);
break;
case 'chop' :
$charlist = (#$_GET['Charlist']) ? ','.$_GET['Charlist'] : '';
echo rtrim($_GET['String'], $charlist);
break;
case 'chr' :
echo chr($_GET['Int']);
break;
case 'chunk_split' :
echo chunk_split($_GET['String'], #$_GET['Chunklen'], #$_GET['End']);
break;
/** ...etc, etc... **/
?>
Related
http://kiwilocals.com.au/dev/
Hello, here is the ajax requests on a category in the middle of the page under the banner. Work everywhere, in addition to all versions of IE.
I checked the developer's tools, a query gives the correct structure, but nothing on the loading icon does not appear after loading. In what may be the reason? Thank you.
function scat(th) {
wait_loading('sub_lst');
if (request = create_request()) {
request.open("GET", "get_subcat.php?id=" + th + "&site=1", true);
request.onreadystatechange = function () {
//alert(request);
if (this.status == 200) {
if (this.readyState == 4) {
var doc3 = document.getElementById('sub_lst');
//alert(doc3);
doc3.innerHTML = this.responseText;
if (!scroll_start) {
$('.sub_scroll').jScrollPane({
animateScroll: true
});
$('.hidden_control').show();
scroll_start = true;
}
}
}
}
request.send(null);
}
}
function create_request() {
var request = false;
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
try {
request = new XMLHttpRequest();
} catch (e3) {
request = false;
}
}
}
if (!request) {
alert("Невозможно выполнить Ajax запрос.");
return false;
} else return request;
}
function wait_loading(el_id) {
document.getElementById(el_id).innerHTML = "<center><img style=\"padding-top: 60px;\" width=\"64\" height=\"64\" src=\"images/loading.gif\"></center>";
}
The problem is with your use of 'this' in the readstatechange event.
Give this a shot.
if(request = create_request()) {
request.open("GET", "get_subcat.php?id="+th+"&site=1", true);
request.onreadystatechange = function() {
if(request.status == 200) {
if( request.readyState == 4 ) {
var doc3 = document.getElementById('sub_lst');
doc3.innerHTML=request.responseText;
if(!scroll_start) {
$('.sub_scroll').jScrollPane({animateScroll: true});
$('.hidden_control').show();
scroll_start=true;
}
}
}
}
request.send(null);
}
But one question... you use jQuery throughout your code, except for this. Why not use:
$('#sub_lst').load("get_subcat.php?id="+th+"&site=1", function(){
if(!scroll_start) {
$('.sub_scroll').jScrollPane({animateScroll: true});
$('.hidden_control').show();
scroll_start=true;
}
});
i have this problem only in ie8
here is my javascript code
var bustcacheparameter="" ;
function createRequestObject(){
try {
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert('Sorry, but your browser doesn\'t support XMLHttpRequest.');
};
return xmlhttp;
};
function ajaxpage(url, containerid){
var page_request = createRequestObject();
if (bustcachevar) bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
}
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {
document.getElementById(containerid).innerHTML=page_request.responseText;
};
}
function LoadMonth(month, year) {
ajaxpage("calendar.php?month="+month+"&year="+year, "Calendar")
}
LoadMonth();
i use ie tester to know this error
line : 26
char : 6
unknown runtime error
TRY this ; its for compatability issues i.e
i hope it helps
AJAX support
function createXMLHttpRequest()
{
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone)
{
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
function getModIndex(val) {
var divEle = "IndexDiv" + val;
var request = createXMLHttpRequest();
if ( !request ) {
alert( request )
return false
}
var callback = function( oXML ) {
document.getElementById( divEle ).innerHTML = oXML.responseText;
}
request.connect(
'../ajax/ajax-GetIndex.php',
'POST',
'id=' + val,
callback
);
}
I have read the forums and google but i just dont understand how to change my ajax GET query to POST. It would be great if someone could help me to achive it. Thank you!
Heres my code:
function ajax(query,parameters,progress_div,progress_txt,result_div) {
// Sisend:
// 0 or 1 | (main_error) error string OR (resdiv) result string
var xmlhttp;
if (progress_div) { progdiv = document.getElementById(progress_div); }
if (result_div) { resdiv = document.getElementById(result_div); }
if (progdiv) { progdiv.innerHTML = progress_txt; }
// ajax
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var response = xmlhttp.responseText;
var string = response.split("<?php echo $vs; ?>");
//kui päring oli ok
if (string[0] == '1' || string[0] == '0') {
if (progdiv) { progdiv.innerHTML = ''; }
if (resdiv) { resdiv.innerHTML = string[2]; }
}
else {
errdiv = document.getElementById('main_error');
if (string[0] == '0') { errdiv.innerHTML = string[2]; }
else { errdiv.innerHTML = string[0]+string[1]; }
progdiv.innerHTML = '';
errdiv.style.display = 'block';
}
if (string[0] == '1' && string[1] != '0') {
window.location.href = string[1];
}
}
}
xmlhttp.open('GET','?leht=ajax&query='+query+'¶meters='+parameters,true);
xmlhttp.send();
return false;
}
change the below line
xmlhttp.open('GET','?leht=ajax&query='+query+'¶meters='+parameters,true);
like this
var url = 'http://yoursite.com/yourfile.php?leht=ajax&query='+query+'¶meters='+parameters;
xmlhttp.open("GET", url, true); //GET method
xmlhttp.open("POST", url, true); //POST method
You have missed the filename in your line.
Jquery POST
$.ajax({ url: "yourfilename.php",
data: {leht: 'ajax',"query":query,"parameters":parameters},
type: 'post',
success: function(output) {
//process the output
}
});
I'm curious as to why this isn't working, here's the code:
function Ajax(sUrl, fCallback) {
var url = sUrl || '';
var callback = fCallback || function () {};
var xmlhttp = (function () {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch (e) {
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (err) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
} else {
return null;
}
}());
this.setUrl = function (newUrl) {
url = newUrl;
};
this.setCallback = function (func) {
callback = func;
};
this.request = function (method, data) {
if (xmlhttp === null) { return false; }
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
callback(xmlhttp.status, xmlhttp.responseXML, xmlhttp.responseText);
}
};
data = data || '';
data = encodeURIComponent(data);
if ((/post/i).test(method)) {
xmlhttp.open('POST', url);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(data);
} else {
var uri = data === '' ? url : url + '?' + data;
xmlhttp.open('GET', uri);
xmlhttp.send();
}
return true;
};
return this;
}
var ajax = new Ajax(''); // sets the url, not necessary for this demonstration
var changed = false;
function change() {
changed = true;
}
function foo() {
ajax.setCallback(change);
ajax.request();
alert(changed);
}
foo();
There is a fiddle here: http://jsfiddle.net/dTqKG/
I feel like the change function would create a closure that would indeed change the changed variable. Does anyone know what's going on?
The ajax.request(); will return before change() is called. That is the async nature of the AJAX calls, and the reason why you need the callback as opposed to just getting return value from send() method.
Other than that there might be some other issues in the code. I question why wouldn't you use one of the many AJAX frameworks readily available instead of writing your own.
I've been trying to get my code off the ground, but I've run into a constantly occurring error across all browsers that tells me my ajax object does not include an open function. I'm sure something I've typed is wrong, but forgive me, as JavaScript is not my strong suit :)
window.onload = function(){init();}
function init() {
ajax = ajaxInit();
ajax.onreadystatechange = update(ajax);
ajaxContact(ajax);
setInterval("ajaxContact('"+ajax+"')",5000);
}
function ajaxInit() {
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (ajax) {
document.getElementById("status").innerHTML = "AJAX initialized";
return ajax;
}
else {
docuement.getElementById("status").innerHTML = "Error: AJAX not available";
return false;
}
}
function ajaxContact(ajax) {
try {
ajax.open("GET","updateAjax.php?" + "ran=" + Math.random(),true);
ajax.send();
}
catch (err) {
alert(err.message);
document.getElementById("status").innerHTML = "Error contacting server";
document.getElementById("loading").src = "images/redx.png";
}
}
function update(ajax) {
if (ajax.readyState==4 && ajax.status==200){
dataObj = jsonTranslate(ajax);
document.getElementById("status").innerHTML = dataObj.status;
document.getElementById("frame").innerHTML =
"Frame:" + dataObj.firstFrame + "/" + dataObj.lastFrame;
document.getElementById("thumbnail").src = dataObj.imgSrc;
}
if (ajax.status==404) {
document.getElementById("status").innerHTML = "Ajax updater not found";
document.getElementById("loading").src = "images/redx.png";
}
}
function jsonTranslate(ajax) {
return eval('(' + ajax.responseText + ')');
}
You are passing the ajax variable as a string...
setInterval("ajaxContact('"+ajax+"')",5000);
Try replacing that with...
setInterval(function() { ajaxContact(ajax); }, 5000);