Simple ajax not working, probably syntax error - javascript

window.onload = function(){
testAjax();
}
var testAjax = function(){
var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
request.onreadystatechange = function(){
if (request.readyState == 4){
// Server is done
try{
var p = document.getElementById['a'];
p.innerHTML = request.responseText;
//document.write(request.responseText);
}
catch(e){
document.write('More Epic Fail');
}
}
}
request.open('GET','updatethumbs.php',true);
request.send(null);
}

After a quick glance:
var p = document.getElementById['a'];
should be:
var p = document.getElementById('a');

getElementById should have ()'s, not []'s

Yup, use "rounded brackets"/parenthesis ()
There are a few names for the MSXML component and depending on what the user (in this case, you) has installed, it may not work.
EDIT: (as per question edit)
Browsers are not required to redraw the page once it's been rendered according to the CSS spec. You need to use javascript to style the items that are dynamically added in.Try, for example:
document.getElementById('a').style.border = "1px solid black";
for a simple black border.

Related

How to access Dom elements inserted by XMLHttpRequest?

I am loading html files with an XMLHttpRequest and putting everything in the body tag into an unseen 'storage' div, and then into the page to be seen. That works well.
function getModule(module,callback) {
var modulePath = makeModulePath(module);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 ) {
var el = document.getElementById('storage');
getContent(xhr.responseText, el);
callback(el);
}
};
xhr.open("GET", modulePath, true);
xhr.responseType = "";
xhr.send();
}
<span id="introCurrency" class="introCurrency"><p>Copper standard</p></span>
But, always a but right? But when I go to select part(.introCurrency) of that inserted text using document.getElementById('introCurrency') get an error saying 'introCurrency'[null] it is not an object. But querySelectorAll does locate it and I can work with it, but it is a little fudgey:
var aModule =
document.querySelectorAll('.introCurrency');
for (var i=aModule.length; i--;){
aModule[i].style.display = 'none';
}
I would much rather use document.getElementById. I hope someone can tell me what's going on. Thank you.

XMLHttpRequest sends url as response text, Firefox doesn't redirect

I have some javascript that sends a XMLHttpRequest to a PHP file. This PHP file sends a response, and javascript is supposed to create a URL and redirect to it, using the response text as a parameter. In all other browsers it works fine, but Firefox won't include the response text in the URL.
This is the javascript example:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'filename.php', true);
xhr.onreadystatechange = function(e){
var id = e.currentTarget.responseText;
var urlWithId = "restofurl?id=" + id;
window.location.href = urlWithId;
}
xhr.send(fd);
and filename.php is just a number at the moment:
<?php
echo "3";
?>
I have tried putting other parts of the url (up to the whole url) in the php part, and firefox always cuts out exactly that part. I have also tried copying the response several times to different variable, copying it character by character, putting it in a function that just returns the input again,...
This is only going to be on my own computer, so I don't need to worry about any security issues, so I'm mostly looking for an easy way to cheat around this rather than the way it would be done professionally. Does anyone have any idea?
This is a basic example, you actually have to test readyState status. If i remember well, it is also safer to set the event function before sending the request (not really sure of that).
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
//do something with this.responseText
}
};
xhr.open("POST", url, true);
xhr.send();
EDIT:
This is one of the reasons why i use frameworks, for the old browser support, but this is not an answer. To be more precise, in the past (present?), browsers used to implement exotic functions. It's been a long time i didnt bother to use XHR objects directly, last time it was for file uploads with loading bar (canvas). It shows you the basic way to handle some stuff. This is longer and a bit old fashioned, but well, it works.
function customXHR(){
if(window.XMLHttpRequest){
return new window.XMLHttpRequest;
}else{
try{ //the weird ones
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(ex){
return null;
}
}
}
var xhr = customXHR(), pleaseStop = false, startDraw = false;
if(xhr){
xhr.addEventListener('load', function(e){
var jsonRep;
if(!pleaseStop){
//did use a JSON response
jsonRep = $.parseJSON(e.target.responseText);
//do the rest, we finished
}
}, false);
xhr.addEventListener('error', function(e){
//error
pleaseStop = true;
}, false);
xhr.upload.addEventListener('progress', function(e){
//why not let this as an example!
//file_size must be retreive separately, i fear
if(e.lengthComputable && file_size > 0 && !pleaseStop && startDraw){ draw_progress(e.loaded / file_size); }
}, false);
xhr.addEventListener('loadstart', function(e){
//can be used too
}, false);
xhr.addEventListener('readystatechange', function(e){
if(e.target.status == 404 && !pleaseStop){
//error not found
pleaseStop = true;
}
if(e.target.readyState == 2 && e.target.status == 200){
startDraw = true;
}
/*if(e.target.readyState == 4){
//not used here, actually not exactly the same as 'load'
}*/
}, false);
xhr.open("POST", url, true);
xhr.send();
} //else no XHR support

How should I create two object to do two different ajax calls?

I have:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
document.getElementById('content').innerHTML = xhr.responseText; // Update
}
};
xhr.open('GET', 'data/data-one.html', true); // Prepare the request
xhr.send(null);
Now I want to do the same thing for another link, so when the link is clicked, in the code above, data-one.html is inserted to the HTML container with an id of content in my html page.
Now lets image I have another link in my nav and want to do the same process for another html container with an id of content1 this time to insert data-two.html .
Do I have to create the httprequest in this file or another ajax file? Are the variables gonna be different?
I already tried with the same variable both in the same file and other files but I get an error saying the I can't set the innerHTML to Null. I can't find out why. Please help.
This code is just to get you started. It is very verbose and can be improved to reused. For the sake of clarity I decided to keep it simple though.
function reqListener1 () {
console.log("listener1 -- html echo", this.responseText);
}
function reqListener2 () {
console.log("listener2 -- json echo", this.responseText);
}
document.addEventListener("DOMContentLoaded", function () {
var url1 = "/echo/html/";
var url2 = "/echo/json/";
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener1);
oReq.open("GET", url1);
oReq.send();
// you could use the same variable. but you'll need to instantiate a different object
var oReq2 = new XMLHttpRequest();
oReq2.addEventListener("load", reqListener2);
oReq2.open("GET", url2);
oReq2.send();
});
Demo: http://jsfiddle.net/pottersky/7dz8r19d/1/

innerHTML works in IE and Firefox, but not Chrome

The data will not display in Chrome, unless i open an IE tab in Chrome go to the site then close it back to Chrome (sorry, if that doesn't make much sense).
window.onload = function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function () {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
Im just starting to learn JavaScript so I really don't know much about it.
You should use some modern Javascript library. It guards you from many of those small differences between browsers. I like jQuery.
So, with jquery your code
window.onload = function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function () {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
becomes
$(document).load(function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
$.get(url, {}, function(data) {
$('#sales').html(data);
});
});
Shorter, cleaner and works in all browsers!
I think you want to use:
request.onreadystatechange = function() {
instead of:
request.onload = function() {
And change the way you check the return value.
See the asynchronous request code example here: https://developer.mozilla.org/en/DOM/XMLHttpRequest/Using_XMLHttpRequest for more details.
Just find that only the first form tag is removed so you can put an empty form () and the next one is keep in the code.

Replacing whole HTML content kills HEAD and BODY tags after HTTP Request!

After pressing a button, I'm sending the whole HTML content from a webpage (the part within the <html> tags) to a CGI script which manipulates the content and sends it back.
Now I'm trying to replace the existing content with the new one. Unfortunately after assignment, every single <head> or <body> tag (as well as the closing ones) will be killed.
By using some alerts I looked through the returning value as well as the original HTML stuff. Both are absolutely as expected.
But after the assignment there is some magic going on. Please help me to figure out what's going on.
Here is the used JavaScript code I used:
var originalBodyInnerHTML = document.body.innerHTML;
var htmlNode = document.getElementsByTagName('html')[0];
var post_parameters = encodeURIComponent(htmlNode.innerHTML);
makePOSTRequest("POST", "http://whatever.com/cgi-bin/doit.cgi", post_parameters, htmlNode);
function makePOSTRequest(method, url, parameters, htmlNode) {
var http_request = getRequestObj();
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function()
{
if (http_request.readyState < 4)
{
var waitingPageBody = '< img src="/img/ajaxloader.gif" alt="in progress..."/>';
document.body.innerHTML = waitingPageBody;
}
else //if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
alert('1response: ' + http_request.responseText);
alert('2innerhtml: ' + document.getElementsByTagName('html')[0].innerHTML);
document.getElementsByTagName('html')[0].innerHTML = http_request.responseText;
}//end of if (http_request.status == 200)
else
{//other http statuses
alert("There was a problem (" + http_request.statusText + ", " + http_request.status + ' error)');
bodyNode.innerHTML = originalBodyInnerHTML;
}
}//end of else if http_request.readyState == 4
}
http_request.open(method, url, true); //async
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Accept", "application/atom+xml,application/xml,text/xml");
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function getRequestObj() {
var http_request = false;
if (window.XMLHttpRequest)
{ // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/html');
}
}
else if (window.ActiveXObject)
{ // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return http_request;
}
This is a simple solution that worked for me. Just as a reference.
document.clear();
document.write(newHtml);
where newHtml is the complete html of new web page.
well, with this
document.getElementsByTagName('html')[0].innerHTML = http_request.responseText
you are replacing everything insidee the html, "killing" body, head and everything...
maybe you wanted
document.body.innerHTML = http_request.responseText
Also, I'd use jquery, it makes your life sooo much easier
You cannot do that. It's not possible to replace the contents of the whole html tag. You can get away with replacing only the contents of the body tag. The head element is kind of magical and browser generally don't support replacing it.
If you want to change the whole document, redirect to it.
If you want to change only parts of the head, try sending them in a different form (like JSON), and make appropriate changes using javascript APIs.
Thanks qbeuek for your answer!
To change only the header, Firefox in fact will allow something like this:document.getElementsByTagName('head')[0] += "e.g. some scripts"
But for Internet Explorer it is necessary to add each element separately to the DOM tree.
var script = document.createElement("script");
script.setAttribute('type','text/javascript');
objHead.appendChild(script);
However, it is really weird that Firefox behaves like this and not popup with some error...

Categories