-3
function saveToDataBase(save_id,textarea_id,question_no,assg_name,testinput,testoutput)
{
    document.getElementById(save_id).addEventListener('click',function(){

        //alert("Hello");
        var question=document.getElementById(textarea_id).value;
        var question_id=assignment_name+question_no;
        var request;
        var url="saveQuesToDataBase.jsp?question="+question+"&question_id="+question_id+"&assg_name="+assg_name;

        for(var i=0;i<testinput.length;i++)
            {
              var v=document.getElementById(testinput[i]).value;
              url=url+"&testinput"+i+"="+v;
            }

        for(var i=0;i<testoutput.length;i++)
            {
              var v=document.getElementById(testoutput[i]).value;
              url=url+"&testoutput"+i+"="+v;
            }

        var len=testinput.length;
        url=url+"&size_of_arr="+len;

        if(window.XMLHttpRequest)
        {  
        request=new XMLHttpRequest();  
        }
        else if(window.ActiveXObject)
        {  
        request=new ActiveXObject("Microsoft.XMLHTTP");  
        }    
        try
        {  
        request.onreadystatechange=function()
        {  
        if(request.readyState==4 && request.status == 200)
        {  
            alert(request.responseText);
        }  
        };
        request.open("GET",url,true);  
        request.send();  
        }
        catch(e){alert("Unable to connect to server");
        }
    })

}

The function is called on click, but not redirected to saveQuesToDataBase.jsp . Please see if I could append things to url this way ? Tell me the better way.

testinput and testoutput are the two arrays of id's of textareas. I used loop to retrieve id and to get the value.

core
  • 3
  • 4

1 Answers1

0

For your code design,I have two suggestions:

a. First I would recommend you using jQuery ajax instead of original Ajax,it will hide the implement of different browsers.With it you can make it like below:

$.ajax({
  url:your_request_url,
  type:"post",//or get
  data:your data,
  success:function(data){},
  error:function(){}
});

b. since Http Get method has parameter length limit,details can be found at maximum length of HTTP GET request?. You need to use POST instead of GET,while using POST,when can using data to pass more parameters to ajax:

var params ={};//define a parameter object
for(var i=0;i<testoutput.length;i++)
{
   var v=document.getElementById(testoutput[i]).value;
   params["testoutput"+i]=v;
}
$.ajax({
  url:your_request_url,
  type:"post",//or get
  data:params,//passing the parameters.
  success:function(data){},
  error:function(){}
});
flyingfox
  • 13,414
  • 3
  • 24
  • 39