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?
Related
Currently my website dynamically loads content using an ajax script.
Here is the script
/***********************************************
* Dynamic Ajax Content- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* Please keep this notice intact
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
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)
}
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
}
}
}
<p> Hello World! </p>
Form
<div id="content"></div>
This part work's fine my content is loaded dynamically the problem arises when I attempt to submit a php form inside of the loaded content the whole page simply refreshes I've tried using javascript to stop the page from refreshing but still no luck. I used this form as a test http://www.codingcage.com/2015/06/submit-php-form-without-page-refresh-jquery-ajax.html it functions properly outside of the ajax content but when placed inside the page simply just refreshes! If anyone could give me some insight on how to solve this problem It'd be greatly appreciated
I think it's because your form is dynamically generated, therefore the event handler doesn't capture your submit event. It happened to me a lot of times and what I did was something like this. I had my selector to the static content. $("#staticContainer").on("submit","#formId",function(){
});
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');
});
I have two ASP.NET programs, one of them is in VS2010 (a web project with one DLL) and .NET 4, it works really great, but another project (VS2008, a web site with a lot of DLLs!) has some problem in running javascript codes (of course these JS codes work fine in VS2010 app), I use some functions for changing images (onmouseclick) and image fade, but there is almost no reaction in VS2008 project, of course JS is located in a content page in VS2008, can it be a possible cause? (I've tested an alert function in VS2008 JS functions and the alert function works, so I think JS function are executed but perhaps there are some other errors)
it is my JS function for changing images:
<asp:Content ID="ContentMain" ContentPlaceHolderID="CPHMain" Runat="Server">
<script type="text/javascript" >
function shownextimage() {
if (document.getElementById('imgBanner').src.toString().indexOf("1") != -1) {
document.getElementById('imgBanner').src = 'Images/2.jpg';
document.getElementById('lblNextImage').innerHTML = "2/5";
}
else if (document.getElementById('imgBanner').src.toString().indexOf("2") != -1) {
document.getElementById('imgBanner').src = 'Images/3.jpg';
document.getElementById('lblNextImage').innerHTML = "3/5";
}
else if (document.getElementById('imgBanner').src.toString().indexOf("3") != -1) {
document.getElementById('imgBanner').src = 'Images/4.jpg';
document.getElementById('lblNextImage').innerHTML = "4/5";
}
else if (document.getElementById('imgBanner').src.toString().indexOf("4") != -1) {
document.getElementById('imgBanner').src = 'Images/5.jpg';
document.getElementById('lblNextImage').innerHTML = "5/5";
}
else if (document.getElementById('imgBanner').src.toString().indexOf("5") != -1) {
document.getElementById('imgBanner').src = 'Images/1.jpg';
document.getElementById('lblNextImage').innerHTML = "1/5";
}
//var element = document.getElementById('id');
//var opa = 1.0;
//document.getElementById('imgBanner').style.opacity = opa;
// IE fallback
//document.getElementById('imgBanner').style.filter = 'alpha(opacity='+opa*100+')';
}
should I also write my fade function? They work smoothly in VS2010 but there is no luck in VS2008!
thanks
I'm trying to write a bookmarklet that will allow me to view the Web Of Trust (WOT) ratings for all the links on a page before visiting them. While WOT provides their own bookmarklet, it is not very useful since you need to visit the page first before viewing the rating. This will be used on SeaMonkey, so I can't just install the WOT extension, either.
WOT has a Javascript API that allows you to activate the ratings on any page it is included in, so I am using that as a base. However, it never seems to work correctly as a bookmarklet. Here's one attempt where I tried to keep the code as close to the API as possible. I only modified the wotinject function so that it would work in a bookmarklet and added a timeout so that the rating widget wouldn't be loaded before jQuery.
var wotprotocol = (document.location.protocol == "https:") ? "https://" : "http://";
var wotbase = wotprotocol + "api.mywot.com/widgets";
var wotinject = function(src) {
document.body.appendChild(document.createElement("script")).src = wotbase + "/" + src + ".js";
};
var wotjquery = typeof(jQuery) != "undefined";
if (!wotjquery) {
wotinject("jquery");
}
void(window.setTimeout(wotinject, 200, "ratingwidget"));
I can see the APIs being loaded in the status bar, but it doesn't do anything at all. Is there any way to get this working?
I'm not sure if this answers your question, but I use a bookmarklet in production that loads jQuery. This code works fine for me:
load = function() {
load.getScript("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js");
// do stuff when jQuery finishes loading.
load.tryReady(0);
}
load.getScript = function(filename) {
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref);
}
load.tryReady = function(time_elapsed) {
/* Continually polls for jQuery library. */
if (typeof $ == "undefined") {
if (time_elapsed <= 5000) {
setTimeout("load.tryReady(" + (time_elapsed + 200) + ")", 200);
} else {
alert("Timed out while loading jQuery.");
}
} else {
/************ JQUERY IS NOW LOADED, PUT CODE HERE ****************/
}
}
load();
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...