I have been learning Ajax techniques in javascript from various online tutorials and I ended up with this code
function fun1 ()
{
var a;
if (window.XMLHttpRequest)
a = new XMLHttpRequest();
else
a = new ActiveXObject("Microsoft.XMLHTTP");
a.onreadystatechange=function()
{
if (a.readyState == 4 && a.status == 200)
{
document.getElementById("myDiv").innerHTML = a.responseText;
}
}
a.open("POST", "java4s.txt", true);
a.send();
}
HTML:
<div id="myDiv" style="width: 300px; height: 30px;">
Click on the button below
</div>
<button type="button" onclick="fun1()">
Change Content
</button>
I already added "java4s.txt" with some text but after clicking the button(Change Content) there's no effect on the page.I can't find anything wrong about the script.Just help me if it's problem with caching or something else. p.s: I am using Firefox browser.
There is nothing wrong with the script. Using Chrome, open up your (F12) developer tools, you should see the response in the network tab or a console error displayed which will fix the issue. If you're having trouble, provide more information on how and where you are hosting the .txt file.
You can see a near exact copy of your script here: W3Schools Ajax Demo
Ajaz, where you do a request and check in webmaster tool you should see something like this:
Whene click on each request you should see something like this
And then clicking on response tab you should see all data returned into the response as per this final image:
The format of data in this picture is json.
However you need to pay attention about which type of data you return to setup the correct mimeType of the request.In json you need to return "application/json" in xml case "application/xml" and so on.Check it too.
This issue came because the CORS was not enabled for the application. It worked after enabling CORS.