Below is a function I use to submit form data (POST) to a PHP script using Asynchronous / Synchronous JavaScript And XML.
function runSQL(div, script, data) {
var ajax = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest;
var ajax = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest;
if (div != "") {
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {document.getElementById(div).innerHTML = ajax.responseText}; //AJAX
if (ajax.readyState == 4) {document.getElementById(div).innerHTML = ajax.responseText}; //AJAX
};
}
ajax.open("POST", script, div != '' ? true : false);
if (data) {ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")};
ajax.send(data ? data : null);
if (div == "") {
return ajax.responseText; //SJAX
} else {
return;
return;
}
}
}
Example of AJAX call:
Example of SJAX call:
runSQL('DIV_Content', 'sql.php', 'action=getContents&page=Home&custom=1');
Example of SJAX call:
result = runSQL('', 'sql.php', 'action=getContents&page=Home&custom=1');
//Do something with result
//Do something with result
Note: Using AJAX allows the JavaScript to continue executing however using SJAX forces JavaScript to wait for the result before continuing. This is useful if you need to do something with the result such as use it in a calculation elsewhere in JavaScript whereas the AJAX result can just be returned straight to the HTML div element as is, once it is ready.
Post a Comment