I have been troubled on how to load the same div into the same page for days.
Been looking for answer in stackoverflow but not found one yet.
Simplified, this is my code so far,
<script>
function add_fields() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "add_more.php", false);
xmlhttp.send();
document.getElementById("add_more1").innerHTML = xmlhttp.responseText;
}
</script>
<html>
<body>
<input type="button" onclick="add_fields()" value="ADD"/>
<div id="add_more1"></div>
</body>
</html>
The problem is that when i clicked the button, it will only load add_more.php once. I want it to load everytime the button is clicked. How to do that?
Please help.
function add_fields() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //really no need for this anymore these days.
}
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) //success
{
document.getElementById("add_more1").innerHTML=this.responseText;
}
}
xmlhttp.open("POST","add_more.php",true); //set the sync to true, modern browsers will block a synchronous request.
xmlhttp.send();
}
This updated versions contains a readystate event that will fill your div every time the Ajax call is completed.
You were using a XMLHttpRequest with the asynchronous option set to false. This could block the user experience and modern browsers (like Firefox) will block this.
if you would like to add more content to the div, use
document.getElementById("add_more1").innerHTML += this.responseText;
+= adds content to the element instead of replacing it. It's a shorthand for:
document.getElementById("add_more1").innerHTML = document.getElementById("add_more1").innerHTML + this.responseText;
SIDENOTE: You are using a POST (in this case a GET would be better, since you're retrieving information only). If you want to send post data to the server you need to put the querystring (without the ?) as an argument in the send method.
To continue with this read up on asynchronous coding:
Easy to understand definition of "asynchronous event"? (very simple explanation).
How does Asynchronous Javascript Execution happen? and when not to use return statement? (more comprehensive).
Related
I'm currently playing around with JavaScript attempting to fetch the contents of a webpage as plain text, and dump the text to a String.
I have found many ways to do this but nothing seems to happen when I do something similar to this: (In this example I use a plain text file)
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
// As you can see I'm also spamming myself with alerts, but they also
// just return blank.
alert(xmlhttp.response);
}
xmlhttp.open("GET", "http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt", true);
xmlhttp.send();
How do I go about doing this?
You cannot because of the Same-Origin-Policy.. otherwise each webpage could load some bank website or so.. So they (Browser vendors) implemented Same-Origin Policy.. You can access only websites which have give you access to..
just try put this in you console on stackoverflow:
open devtools while you see this site
put this into the console
jQuery.get('http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt')
I am new to javascript and AJAX, and have spent the last 8 hours on this one problem, and its beating me. I know its simple, just can't find what I am doing wrong. I have an image on my site with a with an on-click=SendCommand() . This is the js code that I have
function SendCommand(){
alert("BingoBango!");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
};
I get the alert message, and I get no errors using firebug or in chrome javascript console. However that page is not executed. I can however copy and paste that exact url into the browser and it executes successfully.
Any help would be GREATLY appreciated, its kickin my butt.
The page it is calling is calling a python script as well as updating a mysql record. Is there something i can do in my request to ask it to not use the browser cache and actually hit my server?
You should not use a GET request for things that execute actions on the server. Use POST instead, which should not be cached.
If that doesn't help, adapt your HTTP cache headers or, as a last resort, append random strings to the url.
This is how I would do it
JS
function SendCommand()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
}
HTML
<button type="button" onclick="SendCommand()">My button</button>
<div id="myDiv"></div>
i am trying to make an ajax commenting system where if a new comment is posted, the document title changes to (1) website title (like twitter)
my code is here
The xmlHTTPrequest
function loadXMLDoc7(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
document.getElementById('newcomments').innerHTML=xmlhttp.responseText;
}
The PHP
echo "<script type='text/javascript'>
function auto2comments()
{
var MyDiv1 = document.getElementById('uiuiui');";
echo "loadXMLDoc7(MyDiv1.innerHTML)";
echo "}";
echo "setInterval(\"auto2comments()\",15000);</script>";
}
The DIV uiuiui contains /newcommentingi.php?show=0&id=username
The problem is when the Newcomments DIV gets filled, it shows
ID =
Show = 0
why?
The XmlHttpRequest object is asynchronous, which means that when it has the data ready, it returns it in a method. It is best to create a function to act as an event handler so that when the server responds, it calls the event handler function.
I think the solution you need is similar to here: How to get the response of XMLHttpRequest?
I got a cgi-script the performs a search according to the query-string it gets submitted.
That works all fine.
But since the search can take some time and the user might start another search. I want the first search to get aborted before a second search is started, but if I insert a xmlhttp.abort() at the beginning of my AJAXRequest function the cgi-script doesn't get started at all.
Can anyone tell me how this could be performed?
Thanks in advance!
and here is the AJAX-code snippet
var xmlhttp;
function AJAXRequest()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
window.document.getElementById("resultlist").innerHTML=xmlhttp.responseText;
}
}
var queryString= "from=03-01-2006&to=04-30-2006&pattern=345";
xmlhttp.open("POST","../cgi-bin/search.exe?"+queryString);
xmlhttp.send();
}
Yea, XMLHttpRequest.abort() is a correct method to use for AJAX request aborting.
In my opinion your problem is more kind of design problem and not technical.
Therefore my suggestion is to review the flow of how the user interacts with your application.
For example, the classical solution is to show the progress bar or spinner and disable the "Search" button while your request is not completed and revert this state on success or error.
I found my problem.
I tried to abort a request object that has just been created. The object has to be global. At least that's the only way I see how to achieve this.
I am trying to load a different xml file everytime a link is clicked, based on its href.
I have the following in head:
JAVASCRIPT
window.onload=function() {
loadXMLDoc("papers.xml"); // loads the default xml file so that page is not empty
}
function scanForXML(){
var extLinks=document.getElementById('results_list').getElementsByTagName('a');
for (i=0; i<extLinks.length; i++) {
extLinks[i].onclick=function getName()
{
var fileName=this.getAttribute('href');
loadXMLDoc(fileName);
return false;
}
}
}
HTML
<ol id="results_list">
<li> <a class="tooltip" href="paper2.xml"> Teaching with Tablet PC's </a></li>
<li> Tablet PC’s as Instructional Tools </li>
</ol>
The onclick event works, I get the href value but the new xmlFile does not get loaded.
Any ideas why?
ps: no jquery plz, cannot use that. trying to learn better basic javascript
The Javascript load code - by the way it does not work in chrome and opera - but works the default xml file gets loaded in safari
Code:
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",dname,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
Thanks!
K
That's because the request is asynchronous : there is no response when your loadXMLDoc function returns.
The usual solution is this :
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
// use xmlhttp.responseXML;
}
}
}
xmlhttp.open("GET",dname,false);
xmlhttp.send();
The main difference is that you don't use the return of the loadXMLDoc function but ask it to do something after it has fetched the XML.
Another solution would be to force a synchronous request using jquery's ajax function
EDIT : I mark it as duplicate as it's a frequent question but I hope this specific answer will help you.