I'm having a problem. I'm trying do ajax on my own, but I have problem with saving result from ajax call. I want it to do just like jQuery does, or similarly. So, I have a function called ajax, with I parameter, and this parameter is an object with properties like: method, url, async, data, and success ... When I call ajax function, I have no problem except success .. I want it just like jQuery (dont ask me why I dont want to use jQ). So I want this
ajax({
method: "POST",
url: "ajax.php",
async: false,
data: "name=something",
success: function(result) {
console.log(result);
}
});
and I have a problem to save result to parameter in definition of ajax function, and here just use it.
Here's ajax.php
<?php
$name = "The input is: " . $_POST['name'];
return $name;
?>
Here's a definition of an ajax function:
var ajax = function (arg) {
if (typeof arg.method !== "undefined" && typeof arg.url !== "undefined" && typeof arg.async !== "undefined"
&& typeof arg.success !== "undefined" && typeof arg.data !== "undefined") {
var xmlhttp, i = 0,
versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
for ( ; i < versions.length; i++) {
try {
xmlhttp = new ActiveXObject(versions[i]); break;
} catch (e) { }
}
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
/* ////////////////////////////////////////////
HERE I HAVE PROBLEM
/////////////////////////////////////////////*/
// this is obviously wrong (I know it is)
arg.success = function (something) {
something = xmlhttp.responseText;
}
} else if (xmlhttp.status == 400) {
console.log("There was an error 400");
} else {
console.log("UNSUCCESSFUL");
}
}
}
xmlhttp.open(arg.method, arg.url, arg.async);
xmlhttp.send(arg.data);
console.log("Method: " + arg.method + "
URL: " + arg.url + "
Async: " + arg.async + "
Data: " + arg.data + "
");
}
};
How to save a xmlhttp.responseText
to arg.success
function parameter in a way that I can use the parameter in ajax function calls? Should I use callbacks?
EDIT: Thanks, it works but, it only print "The input is: ". How can I fix it?