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
}
});
Related
This snippet doesn´t work. I´m trying to get the file size of an resource via jscript
I find this code:
var obj = new XMLHttpRequest();
obj.open('HEAD', 'resource.png', true);
obj.onreadystatechange = function()
{
if(obj.readyState == 4)
{
if(obj.status == 200)
{
alert('Size in bytes: ' + obj.getResponseHeader('Content-Length'));
}
else
{
alert('ERROR');
}
}
};
Whats wrong? thanks.
try this
var obj = new XMLHttpRequest();
obj.open('HEAD', 'resource.png', true);
obj.onreadystatechange = function()
{
if(obj.readyState == 4)
{
if(obj.status == 200)
{
alert('Size in bytes: ' + obj.getResponseHeader('Content-Length'));
}
else
{
alert('ERROR');
}
}
};
obj.send(null);
hope it helps.
here is my ajaxHandler i want to convert this to native javascript i.e
using XMLHttpRequest but i am unable to understand how to convert.`
ajaxHandler = {
defaultAttributes: {
type: 'GET',
url: 'index.php/request',
datatype: 'json',
data: {},
success: null,
error: function(data) {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
},
timeout: function() {
errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
}
},
sendRequest: function(attributes) {
Paper.giffyLoading.style.display = 'block';
if (!attributes.nopopup) {
if (attributes.loadmsg) {
Controllers.AnimationController.createProgressBarScreen(attributes.loadmsg);
attributes.loadmsg = null;
}
}
$.ajax(attributes);
}
}
i have try to convert the above code like this
XMLRequestDefaultHandler = function() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'index.php/request', true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4 || xmlHttp.status === 200) {
} else {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
}
};
xmlHttp.send(null);
}
I extracted ajax function of Jquery, to work without jquery.
And replace $.ajax(attributes); to ajax(attributes);
JQuery's ajax function, without JQuery :
function ajax(option) { // $.ajax(...) without jquery.
if (typeof(option.url) == "undefined") {
try {
option.url = location.href;
} catch(e) {
var ajaxLocation;
ajaxLocation = document.createElement("a");
ajaxLocation.href = "";
option.url = ajaxLocation.href;
}
}
if (typeof(option.type) == "undefined") {
option.type = "GET";
}
if (typeof(option.data) == "undefined") {
option.data = null;
} else {
var data = "";
for (var x in option.data) {
if (data != "") {
data += "&";
}
data += encodeURIComponent(x)+"="+encodeURIComponent(option.data[x]);
};
option.data = data;
}
if (typeof(option.statusCode) == "undefined") { // 4
option.statusCode = {};
}
if (typeof(option.beforeSend) == "undefined") { // 1
option.beforeSend = function () {};
}
if (typeof(option.success) == "undefined") { // 4 et sans erreur
option.success = function () {};
}
if (typeof(option.error) == "undefined") { // 4 et avec erreur
option.error = function () {};
}
if (typeof(option.complete) == "undefined") { // 4
option.complete = function () {};
}
typeof(option.statusCode["404"]);
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } }
else { xhr = new XMLHttpRequest(); }
} else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; }
xhr.onreadystatechange = function() {
if (xhr.readyState == 1) {
option.beforeSend();
}
if (xhr.readyState == 4) {
option.complete(xhr, xhr.status);
if (xhr.status == 200 || xhr.status == 0) {
option.success(xhr.responseText);
} else {
option.error(xhr.status);
if (typeof(option.statusCode[xhr.status]) != "undefined") {
option.statusCode[xhr.status]();
}
}
}
};
if (option.type == "POST") {
xhr.open(option.type, option.url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(option.data);
} else {
xhr.open(option.type, option.url+option.data, true);
xhr.send(null);
}
}
I'm creating a sign up page with inline validation, and having script for email availability in external file but pattern check inside the HTML using jquery but problem is css of elements doesn't change in email check script so i want to pass a variable value from external JavaScript to internal Jquery...
Help me out....
// JavaScript Document for live email availability check
function createXMLHttpRequest() {
var xmlhttp = false;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xmlhttp = false;
}
}
}
return xmlhttp;
};
function AjaxFunctionusername(signupemail){alert('call');
var mygetrequest = new createXMLHttpRequest();
mygetrequest.onreadystatechange = function() {
if (mygetrequest.readyState == 4 && mygetrequest.status == 200){
arrRecevied = mygetrequest.responseText;
alert(arrRecevied);
if (arrRecevied > 0) {
}
else {
}
}
}
pars = "";
pars = "signupemail=" + signupemail;
domainUrl = "ckh_client.php?" + pars;
alert(domainUrl);
mygetrequest.open("GET", domainUrl, true);
mygetrequest.send();
}
i want aarReceived variable's value to be passed in jQuery as shown below...
<script>
$(document).ready(function(){
//validation for invalid email ID
$("#signupemail").keyup(function(){
var msg = '';
var emmsg = '';
msg = document.getElementById('signupemail').value;
var emailReg = /^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
if (!emailReg.test(msg)) {
$(".validation-img-1").css("display", "block");
$(".validation-img-2").css("display", "none");
}
else if (emailReg.test(msg)) {
AjaxFunctionusername(msg);
}
});
//validation for invalid email ID ends here
});
</script>
Make the following changes-
function AjaxFunctionusername(signupemail){alert('call');
var arrRecevied=''; //Note the change. Do not create global vars.
var mygetrequest = new createXMLHttpRequest();
mygetrequest.onreadystatechange = function() {
if (mygetrequest.readyState == 4 && mygetrequest.status == 200){
arrRecevied = mygetrequest.responseText;
alert(arrRecevied);
if (arrRecevied > 0) {
}
else {
}
}
}
pars = "";
pars = "signupemail=" + signupemail;
domainUrl = "ckh_client.php?" + pars;
alert(domainUrl);
mygetrequest.open("GET", domainUrl, true);
mygetrequest.send();
return arrRecevied;
}
In your script,
if (!emailReg.test(msg)) {
$(".validation-img-1").css("display", "block");
$(".validation-img-2").css("display", "none");
}
else if (emailReg.test(msg)) {
var value= AjaxFunctionusername(msg);
//value is your arrRecevied
}
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 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... **/
?>