InnerHtml problem in Internet Explorer - javascript

I am having problem with applying ajax on IE.I am applying innerHtml on select tag but it is not working my ajax code is
function AjaxF(ftype, cid) {
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if (httpxml.readyState == 4) {
var myarray = httpxml.responseText;
if (ftype == 'Files') {
document.getElementById('temp_thumbnail').innerHTML = myarray;
document.getElementById('temp_mainfiles').innerHTML = myarray;
document.getElementById('temp_preview').innerHTML = myarray;
document.getElementById('temp_image').innerHTML = myarray;
}
else {
document.getElementById('temp_thumbnail').innerHTML = myarray;
document.getElementById('temp_main').innerHTML = myarray;
document.getElementById('temp_image').innerHTML = myarray;
}
}
}
var url = "ajax/files_ajax.php";
url = url + "?filetype=" + ftype + "&customerid=" + cid;
url = url + "&sid=" + Math.random();
httpxml.onreadystatechange = stateck;
httpxml.open("GET", url, true);
httpxml.send(null);
}
My php code for creating option is.I am getting the values in filetype and it is working fine on other browsers
$sql="select name ,id from temporary_upload where type ='$filetype' AND customer_id='$customer_id'";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result))
{
$s.="<option id='' name='' selected='selected' value='". $rows['name'] ."'>". $rows['name'] ."</option>";
}
echo $s;
My html for this code is
<select id="temp_thumbnail" name="temp_thumbnail" style="width:452px">
<option></option>
</select>
I have searched for this error on many forums.They all are saying that innerHtml with select has error in IE can anyone help me to resolve this issue.That I can populate my select option.
Thanks in advance

some years ago, i had a similar problem with IE6. if i remember right, i solved this by replacing the whole select-element instead of just replacing the innerHTML (the option-elements).
to do this, you'll have to change the file called via ajax to output the start- and end-tag of your select-element, too. put the select-elemet on your html-site into another element with an id (if there isn't already one you havn't posted) and replace the innerHTML of that outer element.
EDIT: the link gnur posted describes exactly this workaround, so it seems like i remember right ;)

Not a fan of the solutions where they want you to remove the select and than add it back. Kills all the event handlers. Wrote a little function that tries to set the innerHTML. If setting the innerHTML results in no options being added, it rewrites the function so it will create an element and clone its options.
function addOptionsToSelect( selectId, optStr){
var sel = document.getElementById(selectId)
sel.options.length = 0;
sel.innerHTML = optStr;
if(sel.options.length===0){
(addOptionsToSelect = function( selectId, optStr){
var div = document.createElement("div");
div.innerHTML = "<select>" + optStr + "</select>";
var newSelect = div.getElementsByTagName("select")[0];
var sel = document.getElementById(selectId);
sel.options.length = 0;
for(var i=0;i<newSelect.options.length;i++){
var cpy = newSelect.options[i].cloneNode(true);
sel.appendChild(cpy);
}
div = newSelect = sel = null;
})
( selectId, optStr);
}
}
Running Example

This may work for you in IE and FF, of course a bit of modification depending on how and where you want to place the new options in the select ...
function addmore(){
var select=document.getElementById('myselect');
var theindex=select.options[select.selectedIndex];
var option=document.createElement('option');
option.text='text_4';
option.value='value_4';
try{
select.add(option,theindex);
}
catch(e){
//and for ie
select.add(option,select.selectedIndex);
}
}

This page has an excellent work around:

Related

XMLHttpRequest - get value from URL and write it in a div

I have a div called totalvalue.
<div id="totalvalue"></div>
I wrote a function to get value from my PHP script (on the same server).
function totalvalue() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
totalvalue = (ajax5.responseText);
console.log(totalvalue);
document.getElementById("totalvalue").innerHTML = ajax5.responseText;
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
The php script does output a value.
Neither my console nor the div display the output.
This worked for me.
function test5() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
xxx5 = (ajax5.responseText);
console.log("this is the total value: "+xxx5);
if (xxx5 == 0) {
document.getElementById("totalvalue").innerHTML="Loading...";
} else {
document.getElementById("totalvalue").innerHTML="Total: "+xxx5;
}
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
I presume that where I write the div matter + there could have been an issue with the cache. I cannot tell for sure why the above just started working.
For simpler code, and better cross browser support, i would use jQuery.ajax like so:
$.ajax({
url: 'totalvalue.php',
success: function(data){
$('#totalvalue').html(data);
}
});
Read more about it in the documentation

Replace XML with response from a XMLHttprequest

EDIT
With all the edits to my question it had grown quite lengthy. So let me try to shorten it up a bit and make it easier to follow.
I am building an XUL application using XULRunner. I have it load a dummy XUL page, and then I am looking to use XMLHttprequest to load everything from my server (local ampps server), using PHP to do all the real work. My PHP is setting the XML Content-Type header, and formatting all the output data as XML.
Here is what the JavaScript function, that handles the XMLHttprequest and the response, currently looks like.
function RequestData()
{
if (window.XMLHttpRequest)
{
var url = 'newmenu.xml';
var request = new XMLHttpRequest();
}
else
{
var url = 'http://localdomain.prog/';
var request = Components.classes['#mozilla.org/xmlextras/xmlhttprequest;1'].createInstance(Components.interfaces.nsIXMLHttpRequest);
}
request.onload = function(aEvent)
{
var xmlDoc = aEvent.target.responseXML;
var oldmenu = document.getElementById('menubarwrapper');
oldmenu.parentNode.replaceChild(xmlDoc.documentElement, oldmenu);
};
request.onerror = function(aEvent)
{
window.alert("Error Status: " + aEvent.target.status);
};
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('pageid=menu');
}
The RequestData() is called with the window onload event.
My original code looked to do nothing, but as I researched and tested I eventually got XULRunner to put out some errors in the error console. Ultimately it lead to what, I now assume, were working versions but I just didn't know it.
The Error Console was putting out this message (and still is)
Warning: XUL box for window element contained an inline toolbox child, forcing all its children to be wrapped in a block.
In order to find out if my code worked I had to get it into Firefox. Hence the reason for the if (window.XMLHttpRequest), as it allows me to test with both Firefox and XULRunner. I then took the XML that my PHP was generating and made a local file, as Firefox will not allow an XMLHttprequest to load a remote file (even if it is technically local).
The above code does import the XML and replaces the <menubar id="menubarwrapper">...</menubar>. But, in both Firefox and XULRunner the menu disappears. I can see all the elements if use Firebug, but why they are no longer visible is beyond me, and there are no errors in the Firebug console. This is where I am currently stumped.
In-case its of any use, below is a copy of the dummy XUL file I load.
<?xml version="1.0"?>
<?xml-stylesheet href="main.css" type="text/css"?>
<window id="main" title="My App" width="1000" height="800" sizemode="maximized" orient="vertical" persist="screenX screenY width height" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/javascript" src="main.js"/>
<toolbox id="toolboxwrapper">
<menubar id="menubarwrapper">
<menu id="file-menu" label="File" accesskey="F">
<menupopup id="file-popup">
<menuitem label="Refresh" funcname="RefreshWin"/>
<menuitem label="Open Window" funcname="OpenWin" acceltext="Ctrl+O" accesskey="O" />
<menuseparator/>
<menuitem label="Exit" funcname="ExitProg"/>
</menupopup>
</menu>
<menu id="edit-menu" label="Edit" accesskey="E">
<menupopup id="edit-popup">
<menuitem label="Undo"/>
<menuitem label="Redo"/>
</menupopup>
</menu>
</menubar>
</toolbox>
</window>
The XML that my PHP generates is quite lengthy, but basically it is the <menubar> element with all of its child elements, similar to above, but with a lot more <menu> and <menuitem> elements.
Without more information, this is just a guess at what the problem is.
What may be happening is that the XML data which is retrieved from your XMLHttpRequest() is being interpreted as XML/HTML and not XUL. This could result in the behavior which you describe. You can check this by using the DOM Inspector to look at the elements which were inserted with your line:
oldmenu.parentNode.replaceChild(xmlDoc.documentElement, oldmenu);
What you should look for is what Namespace URI shows for those elements. If it is not http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul then the elements are not being treated as XUL.
One way to solve this would be to do:
oldmenu.insertAdjacentHTML("afterend", aEvent.target.responseText);
oldmenu.setAttribute("hidden","true");
//Alternately (if you don't want to keep the placeholder <menubar>):
//oldmenu.parentNode.removeChild(oldmenu);
I got it working but the code is 80+ lines longer than it should ever need to be. I tried every variation of importNode, replaceChild, appendChild, adoptNode, removeChild, ect. I could think of. I am fairly certain I could write a book on how many ways you could handle any given XML element or node.
Here's an example of how absurd the issue was. This will work
function AddNewElem()
{
var menubar = document.getElementById('menubarwrapper');
var menuitem = '<menu id="help-menu" label="Help" accesskey="H" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">';
menuitem += '<menupopup id="help-popup">';
menuitem += '<menuitem id="test-menu" label="Test" acceltext="Ctrl+T" accesskey="T" />';
menuitem += '<menuseparator/>';
menuitem += '<menuitem id="about-menu" label="About" acceltext="Ctrl+A" accesskey="A" />';
menuitem += '</menupopup>';
menuitem += '</menu>';
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(menuitem, 'text/xml').documentElement;
menubar.appendChild(xmlDoc);
}
but this will not
function RequestData()
{
var url = 'newmenu.txt';
var request = new XMLHttpRequest();
request.onload = function(aEvent)
{
var menubar = document.getElementById('menubarwrapper');
var responsetxt = aEvent.target.responseText;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(responsetxt, 'text/xml').documentElement;
menubar.appendChild(xmlDoc);
};
request.onerror = function(aEvent)
{
alert("Error Status: " + aEvent.target.status);
};
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('pageid=menu');
}
newmenu.txt is just the contents of menuitem in the preceding piece of code. I even went as far as to serialize the xmlDoc back to a string and then parse it again and still wouldn't work. I tried a ton of dumb ideas, and many I knew wouldn't work, on the off chance I might get a clue as to the problem. When you crash Firefox you know you have pushed too hard.
But I digress. So for the sake of others trying to use do a XHR with XULrunner below is what I had to do.
function RequestData()
{
var url = 'http://localdomain.prog/';
var request = Components.classes['#mozilla.org/xmlextras/xmlhttprequest;1'].createInstance(Components.interfaces.nsIXMLHttpRequest);
request.onload = function(aEvent)
{
var xmlDoc = aEvent.target.responseXML;
var toolbar = document.getElementById('toolboxwrapper');
var menubar = document.getElementById('menubarwrapper');
toolbar.removeChild(menubar);
var menubar = document.createElement('menubar');
menubar.setAttribute('id', 'menubarwrapper');
var docfrag = document.createDocumentFragment();
docfrag.appendChild(menubar);
var newmenus = xmlDoc.getElementsByTagName('menu');
var menuslen = newmenus.length;
for (var i = 0; i < menuslen; i++)
{
docfrag = CreateMenu(newmenus[i], docfrag);
}
toolbar.appendChild(docfrag);
};
request.onerror = function(aEvent)
{
window.alert("Error Status: " + aEvent.target.status);
};
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('pageid=menu');
}
function CreateMenu(obj, docfrag)
{
var fragbar = docfrag.getElementById('menubarwrapper');
var menu = document.createElement('menu');
menu = SetMenuAttr(obj, 'id', menu);
menu = SetMenuAttr(obj, 'label', menu);
menu = SetMenuAttr(obj, 'accesskey', menu);
var fragmenu = fragbar.appendChild(menu);
var popup = obj.getElementsByTagName('menupopup')[0];
var menupopup = document.createElement('menupopup');
menupopup = SetMenuAttr(popup, 'id', menupopup);
var fragpopup = fragmenu.appendChild(menupopup);
if (popup.hasChildNodes())
{
var childmenu = popup.childNodes;
var menulen = childmenu.length;
for (var i = 0; i < menulen; i++)
{
if (childmenu[i].nodeName == 'menuitem' || childmenu[i].nodeName == 'menu')
{
if (childmenu[i].nodeName == 'menuitem')
{
var menuitem = CreateMenuitem(childmenu[i]);
}
if (childmenu[i].nodeName == 'menu')
{
var menuitem = CreateMenu(childmenu[i]);
}
fragpopup.appendChild(menuitem);
}
}
}
return docfrag;
}
function CreateMenuitem(obj)
{
var menuitem = document.createElement('menuitem');
menuitem = SetMenuAttr(obj, 'id', menuitem);
menuitem = SetMenuAttr(obj, 'label', menuitem);
menuitem = SetMenuAttr(obj, 'accesskey', menuitem);
menuitem = SetMenuAttr(obj, 'acceltext', menuitem);
menuitem = SetMenuAttr(obj, 'disabled', menuitem);
return menuitem;
}
function SetMenuAttr(obj, attr, newobj)
{
if (obj.hasAttribute(attr))
{
newobj.setAttribute(attr, obj.getAttribute(attr));
}
return newobj;
}
Basically had to retrieve each element and its attributes and make new elements. By far its not the preferred solution. For myself, if I have to write one line of code more than is absolutely necessary, it is wrong. The solution should have been 2 lines.

Javascript XMLHTTPRequest Not Posting XML File

I have a content generator which contians textboxes, textareas and file input controls. All controls are in HTML. Once the save button is clicked I create my XML Document with the text entered into the HTML controls. Finally, I would like the user to be prompted to download the XML File. I am hoping I can do this using a POST method with a XMLHTTPRequest in Javascript. Once the XML Document is sent with the XMLHTTPRequest here is what happens,
Chrome: HTTP Status Code: 304
IE10: Nothing happens
Again, I would like the browser to prompt the user to download the XML File. Here is my code.
function generateBaseNodes() {
var xmlString = '<?xml version="1.0"?>' +
'<sites>' +
'<site>' +
'<textareas>' +
'</textareas>' +
'<textboxes>' +
'</textboxes>' +
'<images>' +
'</images>' +
'</site>' +
'</sites>';
if (window.DOMParser) {
parser = new DOMParser();
xmlDocument = parser.parseFromString(xmlString, "text/xml");
}
else // Internet Explorer
{
xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
xmlDocument.async = false;
xmlDocument.loadXML(xmlString);
}
return xmlDocument;
}
function saveXmlFile(xmlDocument) {
if (window.XMLHttpRequest) { // IE7+, Chrome. Firefox, Opera. Safari
xmlhttp = new XMLHttpRequest();
}
else { // IE5 & IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open('POST', 'http://localhost:57326/ContentGenerator.html', true);
xmlhttp.setRequestHeader('Content-type','text/xml');
xmlhttp.send(xmlDocument);
}
$('document').ready(function () {
$('#templateTab a').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
//Create TextArea XML elements and add them
$('#btnSave').click(function () {
var x;
var xmlDocument = generateBaseNodes();
$('.content').each(function () { // Textarea
if ($(this).attr('id') != undefined) {
if ($(this).is('textarea')) {
// create article node with control id.
articleNode = xmlDocument.createElement($(this).attr('id'));
// append node to xmldocument
x = xmlDocument.getElementsByTagName('textareas')[0];
x.appendChild(articleNode);
// append text
articleNode.appendChild(xmlDocument.createTextNode($(this).text()));
}
if ($(this).is('input[type=text]')) { // Textbox
textNode = xmlDocument.createElement($(this).attr('id'));
x = xmlDocument.getElementsByTagName('textboxes')[0];
x.appendChild(textNode);
textNode.appendChild(xmlDocument.createTextNode($(this).text()));
}
} else { // Show error if a control does not have an ID assigned to it.
alert('The' + $(this).prop('type') + 'has an undefined ID.');
}
});
$('.imageContent').each(function () {
if ($('.imageContent input[type=file]')) { // Image url
// Validate file is an image
switch ($(this).val().substring($(this).val().lastIndexOf('.') + 1).toLowerCase()) {
case 'gif': case 'jpg': case 'png':
imageNode = xmlDocument.createElement($(this).attr('id'));
x = xmlDocument.getElementsByTagName('images')[0];
x.appendChild(imageNode);
imageNode.appendChild(xmlDocument.createTextNode($(this).val()));
break;
default:
$(this).val('');
// error message here
alert("not an image");
break;
}
}
});
saveXmlFile(xmlDocument);
});
});
I SUPPOSE I SHOULD POST MY XML OUTPUT
<sites>
<site>
<textareas>
<article1>sfdsfd</article1>
<article2>dsfsdf</article2>
</textareas>
<textboxes>
<title>dsfdsf</title>
<contentHeader>sdfsdf</contentHeader>
<linkContent>sdf</linkContent>
<link>sdfsd</link>
<relatedContent>sdfsdf</relatedContent>
<contentLink>dsf</contentLink>
<relatedArticle>sdfa</relatedArticle>
<articleLink>sfdf</articleLink>
</textboxes>
<images>
<imageHeader>C:\Images\Header.png</imageHeader>
<articleImage>C:\Images\Main.png</articleImage>
<articleImage2>C:\Images\Deals.png</articleImage2>
</images>
</site>
</sites>
Is there any way to make the browser prompt to download the XML File?
Yep. Convert your data to Blob, then generate a URL from it, which you can then use in an <a>, give that <a> a download attribute and the browser now knows it's to be saved not opened, then finally simulate a click on it. For example;
function txtToBlob(txt) {
return new Blob([txt], {type: 'plain/text'});
}
function genDownloadLink(blob, filename) {
var a = document.createElement('a');
a.setAttribute('href', URL.createObjectURL(blob));
a.setAttribute('download', filename || '');
a.appendChild(document.createTextNode(filename || 'Download'));
return a;
}
function downloadIt(a) {
return a.dispatchEvent(new Event('click'));
}
// and use it
var myText = 'foobar',
myFileName = 'yay.txt';
downloadIt(
genDownloadLink(
txtToBlob(myText),
myFileName
)
);
Try using Filesaver.js to get the user to download a file in memory.
Look also into Data URI's like this:
text file

fetching xml data into a div via ajax and javascript

Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps

Javascript get element by ID and his inside value

This is what i have inside javascript
function xmlhttpPost(strURL,formname,responsediv,responsemsg) {
var xmlHttpReq = false;
var self = this;
// Xhr per Mozilla/Safari/Ie7
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// per tutte le altre versioni di IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
// Quando pronta, visualizzo la risposta del form
updatepage(self.xmlHttpReq.responseText,responsediv);
}
else{
// In attesa della risposta del form visualizzo il msg di attesa
updatepage(responsemsg,responsediv);
}
}
self.xmlHttpReq.send(getquerystring(formname));
}
function getquerystring(formname) {
var qstr = document.getElementById[formname];
return qstr;
}
function updatepage(str,responsediv){
document.getElementById(responsediv).innerHTML = str;
}
First it was deveoped for FORM value, and easy i can transfer POST VALUES in another PHP file,and make a query, now i want to modified it just simple transfer some value of one element in new file, that is going to be loaded ajax in another element and do query, where i got wrong and how to echo value from this class in another file?
You should use () instead of [] to make an actual function call (in this case getElementById). Furthermore, if you want the content of the element, use the textContent or innerHTML properties:
function getquerystring(what) {
var qstr = document.getElementById(what);
return qstr.innerHTML;
}
The [] are property accessors in object or arrays.
To get the contents of the div, return the innerHTML property and change [] to ().
function getquerystring(what) {
var qstr = document.getElementById(what).innerHTML;
return qstr;
}
jsFiddle example
You need to use parentheses "()" for the function call. Also, you want innerText of the element, not the whole element.
function getquerystring(what) {
var qstr = document.getElementById(what);
return qstr.innerText;
}
if you want to get text inside the div, try this:
<div id="test">
Some <span class="foo">sample</span> text.
</div>
function getquerystring(what) {
var node = document.getElementById(what),
var htmlContent = node.innerHTML; // htmlContent would give "Some <span class='foo'>sample</span> text."
var textContent = node.textContent; // textContent would give "Some sample text."
}
you can get the text in between your div by using the following code,
For reference innerHTML, DEMO
function getquerystring(what) {
var qstr = document.getElementById(what).innerHTML;
return qstr;
}
This should work
function getquerystring(what) {
var qstr = document.getElementById[what].innerHTML;
return qstr;
}

Categories

Resources