not working "onclick " on firefox, chrome and safari - javascript

I am working on a program using python, HTML and javascript. I have two images that works as a button changin colors onmouseover and onmouseout. It also has a function that works when the onclick event happens. Everything is working very well on Internet Explorer (which is extrange) but the onclick event is not working on safari,chrome or firefox. The error console doesnt mark any error, neither the error.log on console.
Do you see anything wrong with the code? Are there some functions like onmouseover or onmouseout or onclick that does not work on those browsers?
<td><img src="/RH/images/tacha.png" onclick="eliminarRenglon('eliminar','%s');testing()"
onmouseover="this.src='/RH/images/tacha_2.png'" onmouseout="this.src='/RH/images/tacha.png'" /></td>''' % variable
function testing(){
alert("JUST TESTING");
}
not even the "testing" function works. The "eliminarRenglon" function works very well on IE, and also the "testing" function. Here is the code of the "eliminarRenglon", but as it works very well on IE i dont know if the problem is with it.
function eliminarRenglon(tipo,id) {
var nivel = "No"
var divPrincipal = document.getElementById("divPrincipal");
var idReq = document.getElementById("req" + id).value;
var claveProyecto = document.getElementById("claveproyecto").value;
var url = 'actualizarRenglonAjax.py?nivel='+nivel+'&tipo='+tipo+'&idReq='+idReq+'&claveProyecto='+claveProyecto;
if(document.getElementById("selectReq" + id).value == ""){
xmlhttp = GetXmlHttpObject(nivel);
if(!xmlhttp) {
alert("Browser does not support HTTP Request");
return;
}
var xml = xmlhttp;
xmlhttp.onreadystatechange = function() {
if(xml.readyState == 1) {
loading.innerHTML = "<img src='/RH/images/loading_4.gif' />"
}
if(xml.readyState == 4) {
divPrincipal.innerHTML = xml.responseText;
actualizarTodo();
}
};
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
return true;
}
else
alert("No se puede eliminar");
}
I would really appreciate the help
Thanks a lot!

I'd suggest adding a selector value to the image, then binding events the unobtrusive way (makes maintenance a bit easier later on).
Do it like this:
<img src="/RH/images/tacha.png" class="myImage" />
then, after the DOM is loaded, attach your events (jquery here for simplicity)
$('img.myImage').bind('click', function() {
alert('testing!');
eliminarRenglon('eliminar','%s');
});

Related

event listener in firefox/ie gets ignored

im having some Problems with my html/javascript project, while chrome seems fine with my code both firefox and ie deny to work how i want them to.
Following you see the code which is causing trouble...
<script>
if (window.DeviceOrientationEvent) {
console.log("DeviceOrientation is supported");
window.addEventListener("deviceorientation", handleOrientation);
} else {
console.log("DeviceOrientation is not supported");
}
</script>
with
var handleOrientation = function(event){
if(event.alpha!=null || event.beta!=null || event.gamma!=null) {
var alpha = Math.round(event.alpha);
var beta = Math.round(event.beta);
var gamma = Math.round(event.gamma);
if (WURFL.form_factor == "Tablet") {
tabletOutput();
}
orientationFunction(alpha, beta, gamma);
if(navigator.userAgent.match(/Android/i)){
document.getElementById("androidSpecial").style.display = "inline";
}
} else {
desktopOutput();
}
};
tabletOutput as well as desktopOutput only change the display values of some classes in my css document.
As i said chrome gets to the desktopOutput function but firefox and ie just log "DeviceOrientation is supported" then ignore the window.addEventListerner and keep going.
Thanks for any help!

Java Script Only one function call works

I have a simple registration form. As soon as the user types his phone number and leaves the textbox (onblur), a few of the other fields get auto populated, using an Ajax call to a php script, and this piece works fine. Now, I'm trying to add another onblur() event ON A DIFFERENT TEXT FIELD that has nothing to do with the ajax call or the fields populated but is in the same form. However, when I create this function in java script, the event does not get fired. More over, the original ajax call also stops working i.e., the onblur event for the phone number field also does not get fired (I've confirmed this by putting a few alert messages in place). I'm stuck and given that I'm a novice web developer, it has been an irritable ride. So any help or a nudge in the right direction would be appreciated.
My java script code is in the same file as my HTML code, i.e., between the tags. When I create both the functions between the same script tags, none work, but when I put them in separate script tags, the first function (ajax call behind Phone number) gets fired on blur but the second one does not. The functions in point are: vldtnPhNo() and enabtnRegCmplt().
<script type="text/javascript">
function vldtnPhNo()
{
var xhr;
var dvPhNo = document.getElementById("divPhNo");
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
var FoneNumb = document.getElementById("txtPhNo").value;
xhr.open("POST", "verify.php", true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
document.getElementById("txtRegInv").value = xhr.responseText;
var rstOftheTxt = xhr.responseText;
document.getElementById("txtPhNo").value=rstOftheTxt;
document.getElementById("txtPhPop").value=rstOftheTxt;
}
else
{
document.getElementById("txtPhNo").value='waiting';
document.getElementById("txtPhPop").value='waiting';
}
}
}
xhr.send("txtPhNo=" + FoneNumb);
}
else
{
throw new Error("Ajax is not supported by this browser");
}
}
function enabtnRegCmplt(){
If(txtRegInv.value!="")
{
var UsrNm;
var Psswd;
var RePsw;
var PostBackInfo;
UsrNm = document.getElementById('txtUsrNm');
Psswd = document.getElementById('txtPsw');
RePsw = document.getElementById('txtrePsw');
txtRegInv = document.getElementById('txtRegInv');
If (RePsw.value!="" && Psswd.value!="" && UsrNm.value!="" && RePsw.value==Psswd.value)
{
document.getElementById('btnRegCmplt').disabled="False";
}
else if(UsrNm.value=="")
{
UsrNm.value="Please Enter UserName";
}
else if(Psswd.value=="")
{
Psswd.value="Please Enter Password";
}
else if(RePsw.value=="")
{
RePsw.value="Does not match";
}
}
}
</script>
Your code is very messy. One of the reason why it's necessary to write neat code. Your brackets are wrong, thus the whole code isn't executed (else statement is connected with function).
The If statement doesn't exist, try if instead (lowercase I).
Other things:
use onkeyup instead.
2:
For the vars you could do:
var UsrNm,
Psswd,
RePsw,
PostBackInfo
;
OR
var UsrNm = document.getElementById('txtUsrNm'),
etc.
Syntax mistake
An extra brace }
`else
{
document.getElementById("txtPhNo").value='waiting';
document.getElementById("txtPhPop").value='waiting';
}
}
}`
Remove one brace after the else condition

Multiple calls to ajax script not working

I am very new (literally less than a few days) to all things ajax, but it is required for a form I am building for my employer.
Basically, no matter what I do it just will not work for more than one function. To elaborate, I am trying to update 4 different parts of a page based on one drop down using onchange. Now updating one part works fine, updating any more than that fails... but not only fails, it also fails if for example I do call to ajax part, then just a simple alert... but if I do it with the alert first it works, then falls over again if I put anything after the ajax call. I hope that makes sense. It also works if I do, for example onchange, and onblur on the same element, it will execute twice. I'll post the code then hopefully it will make more sense.
<select name="pType" id="ptype" onchange="dostuff()">
So that's the input element...
<script type="text/javascript">
function dostuff(){
ajaxpage('adminincludes/popoptions.php?pID=<?= $sql['pID']; ?>&pType=' + ptype.value,'options');
alert('test');
}
</script>
...and that's the dostuff code, or an example anyway, ignore the PHP part as it fails regardless of that, that part works fine.
Now the rest of the code is within an external file and I believe that somewhere in there is where the problem lies... however I am new to ajax, and am not the greatest with js as I have never really had a major need for it so just learned what I needed, when I needed.
var bustcachevar = 1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname
var bustcacheparameter = ""
function ajaxpage(url, containerid) {
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject) { // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
page_request = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e) {}
}
} else
return false
page_request.onreadystatechange = function () {
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter = (url.indexOf("?") != -1) ? "&" + new Date().getTime() : "?" + new Date().getTime()
page_request.open('GET', url + bustcacheparameter, true)
page_request.send(null)
page_request.send(null)
}
function loadpage(page_request, containerid) {
if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)) document.getElementById(containerid).innerHTML = page_request.responseText
}
function loadobjs() {
if (!document.getElementById) return
for (i = 0; i < arguments.length; i++) {
var file = arguments[i]
var fileref = ""
if (loadedobjects.indexOf(file) == -1) { //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js") != -1) { //If object is a js file
fileref = document.createElement('script')
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", file);
} else if (file.indexOf(".css") != -1) { //If object is a css file
fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref != "") {
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects += file + " " //Remember this object as being already added to page
}
}
}
Now like I said, the code works perfectly when only calling ajaxpage() once, or multiple times via different events, it just will not work multiple times from one event, even when putting the multiple instances into the dostuff() function.
Any help would be greatly appreciated as this is really starting to aggravate me.
UPDATE: This isn't as urgent now as i have done a "workaround" which uses multiple events such as mouseover, mouseout etc on an update link instead. which means it works as i need it to, however it is not elegant by any means and I am still intrigued why it won't work when called multiple times within 1 event?!
I notice on lines 26 and 27 of your sample you're repeating:
page_request.send(null)
Worth eliminating that before you continue. Could we see a live link to this anywhere so we can perhaps examine generated source?

execute javascript onload rather than onchange

I have am HTML form in a PHP page. The form has various inputs. One of the inputs has an onchange event:
<input size=10 type=number id=sku1 name=sku1 onchange="showUser(1, this.value);showWhse(1, this.value)">
This calls the following function:
<script type="text/javascript">
function showUser(userNumber, str)
{
if (str=="")
{
document.getElementById("txtHint" + userNumber).innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("txtHint" + userNumber).innerHTML=xmlhttp.responseText;
var responseText = xmlhttp.responseText;
var description = responseText.substring(12, responseText.indexOf(",Warehouse:"));
var warehouse = responseText.substring(responseText.indexOf(",Warehouse:")+11, responseText.indexOf(",SellingUnits:"));
var sellingUnits = responseText.substring(responseText.indexOf(",SellingUnits:")+14);
document.getElementById("whse" + userNumber).innerHTML = warehouse;
document.getElementById("txtHint" + userNumber).innerHTML = description;
document.getElementById("su" + userNumber).innerHTML = sellingUnits;
}
}
xmlhttp.open("GET","getdata1.php?q="+str,true);
xmlhttp.send();
}
</script>
This works 100%. if however, the input is populated by a session variable, and the page is refreshed, how can I get the script to execute again onload, without an onchange event?
so when the page is first visited, id the input has a value, execute the script?
Just execute the function onload?
window.onload = function init() {
showUser(1, document.getElementById("sku1").value);
}
You may also use the onload attribute of your document's body, or add the init function as an event handler to DOMContentLoaded. But I'm sure you already have some functions which are executed onDOMready.
you can also use the ready function from the jquery
$(document).ready(function() {
showUser(1, $("#sku1").val());
});
Well, you can use the onload event. You may also want to consider using Jquery's document.ready functionality. The difference can be found here. Also, Jquery provides a much more concise syntax for accessing your form elements
In either case, you would probably simply need function that does something like checking the field has a value.
<script type="text/javascript">
function showUserOnLoad()
{
var inputValue = $('#sku1').val();
if(inputValue != '' && inputValue != null)
showUser(1, inputValue);
}
function showUser(userNumber, str)
{
...
}
</script>

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