4

I want to call a jsp file through ajax post call. So I've done below code -

  xmlhttp=new XMLHttpRequest();

   xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {  
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
   }
   }

   var params = "report_id=0&id=1234567890";
  xmlhttp.open("POST","/test/jsp/test.jsp",true);
  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

      xmlhttp.setRequestHeader("Content-length", params.length);
      xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send(params);
   }
   </script>
    </head>
<body onload="loadXMLDoc()">
 <div id="myDiv"></div>

Now test.jsp looks like below -

  <html>  
  <head>
   <script language="JavaScript">
   function hello()
   {
   alert("Hello");
   //Do my stuff
    }
   </script>
     <title>test Page</title>

  </head>
    <body topmargin="0" leftmargin="0" onload="hello()">
  <form name="mainForm" >
  </form>
  </body>
  </html>

Issue is, I'm not getting alert message when opening my first html page. What is wrong here and what needs to be done?

Pakira
  • 1,951
  • 3
  • 25
  • 54
  • possible duplicate of [Executing – Quentin Oct 04 '13 at 20:44

2 Answers2

2

Instead of trying with onload function, use ready function as

    $( document ).ready(function() 
    {
        //here you can call hello function
    })
balaji
  • 774
  • 1
  • 16
  • 42
0

you will not get javascript executed when you are making ajax call like this.

Once ajax call is made you should trigger a function on main page not on ajax page

 $.ajax({
    type: "POST",
    url: "test.jsp",

    success: function(){
        hello();
    },
    error: function(){
        alert("error");
    }
});
function hello()
{
}
Bala
  • 510
  • 2
  • 9
  • could you please let me know how do I call hello() function from test.jsp page. Do you mean I need to create some short of link or button which will trigger hello() function? I want to call this function once test.jsp is loaded without any user click. Thank you for your help! – Pakira Oct 07 '13 at 21:25