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(){
});
Related
I have some problem with page load on desktop browser and mobile browser. In this case I have 4 html page one is home.html, second is home-mobile.html, third is product.html and fourth is product-mobile.html. My problem is I don't know to switch the html page if opened in mobile browser. For the example is when I open www.example.com in desktop the page will call home.html but when I open www.example.com in mobile the page will call home-mobile.html and so with product page, when I open www.example.com/product in desktop it will call product.html but when I open www.example.com/product in mobile it will call product-mobile.html. The point is how could I open one link and it will detect opened in desktop browser or mobile browser and call different html page.
Which I have been done now but still not working is :
<script>
window.mobilecheck = function() {
var check = false;
if(window.innerWidth<768){
check=true;
}
return check;
}
if(window.mobilecheck()){
window.location.href="home-mobile.html";
}
else {
window.location.href="home.html";
}
</script>
But with that script the URL was changing and not be the same.
Please anyone know how to do this could help me. Thanks.
This script allows you to change the page content without redirecting the browser.
window.mobilecheck = function() {
var check = false;
if (window.innerWidth < 768) {
check = true;
}
return check;
}
if (window.mobilecheck()) {
$.ajax({
'type': 'POST',
'url': 'home_mobile.html',
'data': postData,
'success': function(response) {
$("html").html(response);
}
});
}
modify the code as you need.
If your device mobile it will automatically redirect on mobile page. Simple use this code. No need for else condition. just check mobile device.
if ($(window).width() < 767) {
function getMobileOperatingSystem() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
"Android"
if (/windows phone/i.test(userAgent)) {
return "Windows Phone";
}
if (/android/i.test(userAgent)) {
return "Android";
}
if (/iPhone|iPod/.test(userAgent) && !window.MSStream) {
return "iOS";
}
return "unknown";
}
if(getMobileOperatingSystem()){
window.location="\home-mobile.html";
}
}
Let's say your page is home.html.
And when the page is loaded, you can run a script to detect client type( desktop or mobile), then send an Ajax call to corresponding page to get the content you want.
Then when the Ajax call returned, you can simply replace current content with the returned value.
In this way, your URL will not change at all, and the content can change according to current client type.
home.html:
<html>
<head>
<script language="javascript">
function loadContent(){
var clientType
//your code to get client type here
//Below block to get Ajax client object according to your browser type
var XHTTP;
try
{
//For morden versions Internet Explorer
XHTTP = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (ex)
{
try
{
try
{
//For old versions Internet Explorer
XHTTP=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(exxx)
{
XHTTP = new XMLHttpRequest("Msxml2.XMLHTTP");
}
}
catch(exx)
{
try
{
//For browsers other than Internet Explorer
XHTTP= new XMLHttpRequest();
}
catch(eexx)
{
//This means ActiveX is not enabled.
//To enabled go to your browser settings and enabled the ActiveX.
alert("Not Supported, It might be previous version browser");
}
}
}
if(clientType=="mobile"){
XHTTP.open("GET","/home_mobile.html");
}else{
XHTTP.open("GET","/home_desktop.html")
}
XHTTP.onreadystatechange= function()
{
if (XHTTP.readyState==4)
{
var result=XHTTP.responseText.toString();
document.getElementById("content").innerHTML=result;
}
}
//This finlly send the request.
XHTTP.send(null);
}
</script>
</head>
<body onload="javascript:{loadContent();}">
<div id="content"></div>
</body>
</html>
This script will change the html content of a current page with requested page html without changing url. (AJAX)
var xhr = new XMLHttpRequest(); // Create XMLHttpRequest object
xhr.onload = function() { // When response has loaded
// The following conditional check will not work locally - only on a server
// if(xhr.status === 200) { // If server status was ok
document.getElementsByTagName("html")[0].innerHTML= xhr.responseText; // Update
//}
};
xhr.open('GET', 'html u want to replace ', true); // Prepare the request
xhr.send(null); // Send the request
});
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?
My whole page is loading again whenever I make a ajax call to load a div.
I have noticed that 'body onload=init()' onload event is getting triggered on ajax response and all the initialization is happening again. I don't want that to happen.
Is there a way by which only div is loaded through ajax call.
<body onload="init()">
.....
.....
<div>...<b>More</b></div>
</body>
main.js
function saveView(arg){
if(arg=="more"){
ajaxGet(baseRef+"all.html", loadList);
}else{
ajaxGet(baseRef+"all-A.html", loadList);
}
function init(){
.....
}
function ajaxGet(url, responseHandler)
{
var page_request = false;
if (window.XMLHttpRequest && !(window.ActiveXObject && window.location.protocol == "file:")) {
// use this only if available, and not using IE on a local filesystem
page_request = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // older versions of IE, or IE on a local filesystem
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
}
}
}
else {
alert("Your browser does not support XMLHTTP.");
return false;
}
page_request.onreadystatechange=function() {
if(page_request.readyState==4) {
// on local machines the status for success is 0. on web servers it is 200
if(page_request.status==200 || page_request.status==0) {
responseHandler(page_request);
}
}
}
page_request.open('GET', url, true);
page_request.send(null);
}
function loadList(page_request){
document.getElementById("list").innerHTML=page_request.responseText;
Loaded = true;
try{
if(pLoaded)
doFilterStateChange1();
}catch(e)
{
}
setTimeout("restoreScrollTop()", 1000);
}
It is not ajax that is triggering onLoad event of body.
If you see the anchor tag, I haven't assigned any value to href="" which was causing the page to be loaded again. Removing it solved the problem.
We'd need to see your code to help, but when pages do things like reloading etc, it usually means their is a script error. Use firebug to check for errors, it might be hard to catch if it's refreshing quickly.
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...