views:

47

answers:

2

Ive been having great frustration for hours now trying to remember my AJAX!

Im trying to write a function which will be called that will simply POST 4 variables to a given URL, written in javascript and not jquery such as:

function postVariables(URL, var1, var2, var3, var4)
{
  ......
  return true;
}

Can anyone help?

A: 
<form method="POST" action="basicform.php">
Your name: <input type="text" id="name" name="name" size="25" /> <br />
Your age: <input type="text" id="age" name="age" size="25" /> <br />
<input type="submit" value="submit" />
</form>

creating an Ajax object instance:

        function ajaxRequest(){
         var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] 
    //activeX versions to check for in IE
         if (window.ActiveXObject){ 
//Test for support for ActiveXObject in IE first 
//(as XMLHttpRequest in IE7 is broken)
          for (var i=0; i<activexmodes.length; i++){
           try{
            return new ActiveXObject(activexmodes[i])
           }
           catch(e){
            //suppress error
           }
          }
         }
         else if (window.XMLHttpRequest) // if Mozilla, Safari etc
          return new XMLHttpRequest()
         else
          return false
        }

simple call

var mypostrequest=new ajaxRequest()

POST request

mypostrequest.onreadystatechange=function(){
 if (mypostrequest.readyState==4){
  if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
   document.getElementById("result").innerHTML=mypostrequest.responseText
  }
  else{
   alert("An error has occured making the request")
  }
 }
}

var namevalue=encodeURIComponent(document.getElementById("name").value)
var agevalue=encodeURIComponent(document.getElementById("age").value)
var parameters="name="+namevalue+"&age="+agevalue

mypostrequest.open("POST", "basicform.php", true)
mypostrequest.setRequestHeader("Content-type", 
"application/x-www-form-urlencoded")
mypostrequest.send(parameters)
aSeptik
A: 

Been a while since I've done this without jQuery but something like

function postVariables(URL, var1, var2, var3, var4)
{
  var xhr= new XMLHttpRequest();

  var postvars = "var1=" + var1 + "&var2=" + var2 etc;
  xhr.open("POST", URL, true);

  xhr.setRequestHeader("Content-type", "text/html;");
  xhr.setRequestHeader("Content-length", postvars.length);
  xhr.setRequestHeader("Connection", "close");

  xhr.send(postvars);
}

I'm sure my syntax is off somewhere or other, but you should be able to search for XmlHttpRequest and find some valid samples.

ref: http://www.w3.org/TR/XMLHttpRequest/

kekekela