Loading dynamic contents when a div is clicked - javascript

I hope you can help me with this.
I would like to use a dynamic call to the server to get the content that needs to be loaded to a div.
There is a fixed menu at the bottom of the page that when tag is clicked calls a function and tells it which frame to update, and then in the function generates an XMLHttpRequest (or use ActiveX in case of old IE versions etc.), with that request navigate to a predefined location on the server where the php snippet lies that needs to be included, and then set that as the innerHTML of the corresponding output section.
I also would like an array outside of the function that keeps track of which pages have already been loaded, so that it doesn't load a page again just because a user clicks on the link a second time.
HTML:
<div id="FixedMenu">
<input type="radio" name="radio-set" checked="checked" id="main"/>
Main
<input type="radio" name="radio-set" id="2nd"/>
2nd
<input type="radio" name="radio-set" id="3rd"/>
3rd
<input type="radio" name="radio-set" id="4th"/>
4th
<input type="radio" name="radio-set" id="4th"/>
4th
</div>
<div class="scroll">
<section class="main">
<!-- loads the main context. -->
</section>
<section id="2nd" >
<!-- this section should load the php file only when the button is clicked. -->
</section>
<!-- section 3rd - 5th... -->
</div>
JAVASCRIPT
<script>
$(document).ready(function(){
$("#2").click(function(){
$("#2nd").load('MyURL');
});
});
</script>
Is there any chance I can put a php file in the same folder here instead of directing the function to an url?

You should be able to do this:
$("#2nd").load('/path/to/my/php/page/here');
Have you tried that

What you try is the right way.
$("#2nd").load('MyURL');
'MyUrl' should contain your link to your php file, relative to your current file.
If you want to cache the content, you could simply use the second parameter of load named data to save your content.

According to this documentation it appears that you can. It's still a URL though, as jQuery will still an AJAX request to fetch the given resource. Keep in mind that you want this, as your PHP server does need to parse the file in order to behave like PHP.
$('.content').load('dynamic_content.php');
In response to poster's comment:
Pay particular attention to the part of the documentation that regards to loading page fragments.
$( "#result" ).load( "ajax/test.html #container" );
Although PHP will still have to parse the entire requested script you can render only a specific portion of it using this syntax and that may help speed things up slightly.
Another thought may be not pointing to a full page, but to an API end point that would return the data you are looking for. This can avoid extra logic for the full page and/or return JSON data for easier JS work.

Related

Toggle Visibility of Separate Javascript Files on Same Wordpress Page

Let me preface by saying this is all in relation to a Wordpress page. My knowledge of JS is lacking at best and the concept of installing/loading/enqueueing a function on one area of the site and then calling that function in another area of the site is a something that makes sense to me in my head but is very new to me in practice and might need a little explaining.
I have two separate javascript files that I would like to load on a single page, but toggle visibility/display of either based on radio button input. The JS is provided by a 3rd party and is offsite. Their provided code is this:
<script src="https://toolkit.rescuegroups.org/j/3/FzemP6HU/toolkit.js"></script>
and
<script src="https://toolkit.rescuegroups.org/j/3/4ANRW3x8/toolkit.js"></script>
Each file presents a separate set of filtered results from their database. How can I incorporate both onto a page but only have one or the other showing based on a radio button form input? I would like the page to start off with nothing visible (hopefully giving time for both JS to load in the background while the user selects an option) and then show one or the other depending on what they selected.
You can see a single one of these in action at http://pricelesspetrescue.org/adoptable-dogs/. I'm trying to incorporate the use of an additional file on that same page based on input from the user and only showing one or the other rather than both.
I have tried to manage the following
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type='text/javascript'>
function displayForm(c) {
if (c.value == "2") {
jQuery('#claremontdogContainer').toggle('show');
jQuery('#chdogContainer').hide();
}
if (c.value == "1") {
jQuery('#chdogContainer').toggle('show');
jQuery('#claremontdogContainer').hide();
}
};
</script>
<label>Please select a location to view:</label>
<form>
<input value="1" type="radio" name="formselector" onClick="displayForm(this)"></input>Chino Hills
<input value="2" type="radio" name="formselector" onClick="displayForm(this)"></input>Claremont
</form>
<div style="display:none" id="chdogContainer">
<script src="https://toolkit.rescuegroups.org/j/3/FzemP6HU/toolkit.js"></script>
<script type="text/javascript">
</script>
</div>
<!-- If I uncomment this second block the whole thing breaks
<div style="display:none" id="claremontdogContainer">
<script src="https://toolkit.rescuegroups.org/j/3/4ANRW3x8/toolkit.js"></script>
<script type="text/javascript">
</script>
</div>
-->
This gets pretty close to what I need. The problem I have is the second script load seems to conflict with the functions they provide in the script. It will display the initial result but does not carry any of the functionality that it should have. http://pricelesspetrescue.org/test-page/ Nothing is clickable inside those results and should be.
Been searching through various similar posts and the wordpress codex and...and...I just haven't been able to come up with anything that seems close enough to what I'm looking for to make the answer click in my head.
Edit: It seems that if I only load one of the scripts in either what I have above or the suggested answer below, all functionality is present when loaded. It's the loading of the second toolkit script that is breaking the page. I'm guessing one would need to be loaded then unloaded before loading the second for it to work. Any ideas?
The toolkit.js file you linked adds some common scripts to the DOM (via document.write function, which is not a good solution - see here: http://www.jameswiseman.com/blog/2011/03/31/jslint-messages-document-write-can-be-a-form-of-eval/), then populates an array (toolkitObjects) with a series of variables that are custom per file and finally loads some other scripts.
It also seems that each file loads a div with a specific class containing all the pets, and each div is identifiable by a specific class ( "rgtk-SOMEID" ) and therefore can be shown/hidden via javascript.
Here is an example of what you can obtain using the div class:
http://jsbin.com/loneyijuye/edit?html,output

Load HTML within AJAX call

I'm having some difficulty with a Javascript function I am writing. The basic function of the script is that when a specific AJAX function is called and returns successful, it loads some HTML from a file and inserts that HTML into a on the main page and then (once loaded), fades in the parent div.
jQuery.ajax({
type: "POST",
url: "fns/authenticate.php",
data: dataString,
success: function (data) {
if (data=='1') {
jQuery("#authlogin").fadeOut(500, function(){
$(this).remove();
jQuery("#result").load("fns/logic.html", function() {
jQuery('#authtrue').fadeIn(1000);
});
});
} else {
jQuery('#details-error').fadeIn(200);
}
}
});
return false;
Now the AJAX seems to function properly, in that it will execute under the correct conditions and fade out and in the correct divs, the problem seems to be that the content isn't being loaded from logic.html or it is not being bound to the #result div correctly.
The main page's html looks like:
<div id="authlogin">
<!-- HTML form -->
</div>
<div id="authtrue" style="display: none;">
<div id="result"></div>
</div>
Any help would be much appreciated.
This is one of those things that you must troubleshoot yourself, because we do not have access to your fns/logic.html and therefore cannot test fully.
However, some thoughts:
(1) The basic logic of your .load() success function seems correct. Here is a jsFiddle that approximates the AJAX success function's logic. I substituted .html() for .load() because jsFiddle cannot do ajax. Anyway, assuming that .load() is doing what it should, that part should be working.
(2) You may already know this, but note that .load() is shorthand for $.ajax() -- as are .post() and .get(). You might find $.ajax() easier to troubleshoot as the code block is more structured. As a general rule, troubleshooting the shorthand constructions is slightly more abstract/difficult than troubleshooting $.ajax()
(3) Use developer tools in Chrome (press F12 key) to verify that the contents of logic.html have been inserted into the #result div. You might find, as I did in playing with my jsFiddle, that the contents were injected but the #authtrue div remained hidden. At least you will know that the logic.html document has been found and contents inserted. Knowing exactly where the problem is, finding/fixing the rest might now be trivial.
(4) Does your logic.html file include unnecessary header information? If so, you can strip it out by only inserting the BODY of the document, or a top-level containing div. See this section of the jQuery docs:
jQuery("#result").load("fns/logic.html #container", function() {//CALLBACK IN HERE});
(5) It would be a smart idea to create a test document that just and only loads the logic.html document, using various methods:
Method A: Using PHP (or whatever server-side language you use)
<div id="authlogin">
<!-- HTML form -->
<input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
<div id="result"><?php include 'logic.html'; ?></div>
</div>
Method B: Using load()
HTML:
<div id="authlogin">
<!-- HTML form -->
<input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
<div id="result"></div>
</div>
jQuery:
jQuery('#authtrue').show();
jQuery("#result").load("fns/logic.html");
(6) Ensure you do not have a typo in the destination element jquery selector: If no element is matched by the selector — in this case, if the document does not contain an element with id="result" — the Ajax request will not be sent. (from the docs)
I managed to fix this myself, thanks to the help of everyone here. It ended up being a browser caching problem. As soon as I cleared the cache everything magically worked.

Script to pick up the HTML value of a page? Explanation inside

I am quite the noob at anything other than some HTML, CSS etc, basic website stuff. My javascript is pretty non-existant too. However we were quoted £2,500 by the people who develop our website to add Paypal on the checkout page! They use a fancy 3rd party program which is a standalone software made by themselves that contains all the products etc. We pay monthly to have access to that and make all website changes (such as price, product name etc) in that.
To cut a long story short, I had a look around and found this:
<script src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
></script>
Now, can I change the data-amount field to pick up what the "value" is on the page in the HTML? That way I can simply just add a button that picks that up. Which would work with paypal.
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input type=hidden name='amount' value='1,038.00'>
Basically, how can I get the javascript code to pick up the value from the HTML (or somewhere else). I only have access to the full HTML of the page.
I am not sure how many of these data fields you have on a page but you could write a JS method to dynamically assign the values of the given HTML.
I would start by giving the HTML you're working with some ID's.
<script id="paypalScript" src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
onload="assignAmount"
></script>
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input id="amount" type=hidden name='amount' value='1,038.00'>
Then write a method to execute onload.
function assignAmount(){
var amtElm = document.getElementById('amount');
var scriptElm = document.getElementById('paypalScript');
scriptElm.dataset.amount = amtElm.value;
}
Then attach the method to the onload event of the script element. Putting the script tag below your data field in the HTML should prevent any load issues you might run into.

Rendering DOM at run time is not working in Dojox

What I am doing here is, I am rendering DOM(having check box) in a div (id="euiview") programmatically . my code is like
var iHtml='<span><input type="checkbox" id="cbox" data-dojo-type="dojox.mobile.CheckBox" onclick="toggleCheckbox()" class="addremove-check"><label for="cbox"> E&U Imperatives </label> </span></p><p><span><input type="checkbox" id="cbox1" data-dojo-type="dojox.mobile.CheckBox" class="addremove-check"><label for="cbox1"> Transform the utility network </label></span></p>';
domConstruct.place(iHtml,"euiview");
where I have a div in html page is like.
<div id="euiview" data-dojo-type="dojox.mobile.View">
</div>
Now the problem is I am unable to check or un check the check box in some android device browsers but it is working fine in desktop browser. can I render html this way or I need to create DOM programmetically? Please help me. Thanks
It depends on when you're parsing your page. If you parse your page after you add the new HTML, there will be no problem. However, if you parse your page before you add the new HTML, Dojo won't parse that DOM into widgets and so your checkbox won't work.
I assume you're parsing the page on DOM load, so it really depends on what's getting executed first. A solution that might work is the following:
var iHtml='<div id="new-content"><p><span><input type="checkbox" id="cbox" data-dojo-type="dojox.mobile.CheckBox" onclick="toggleCheckbox()" class="addremove-check"><label for="cbox"> E&U Imperatives </label> </span></p><p><span><input type="checkbox" id="cbox1" data-dojo-type="dojox.mobile.CheckBox" class="addremove-check"><label for="cbox1"> Transform the utility network </label></span></p></div>';
domConstruct.place(iHtml,"euiview");
parser.parse("new-content");
With this, you can make sure that the new content is parsed. I also noticed that you're closing your </p> tag but you didn't put a <p> in front of it.

Should I use template or return full code in jquery AJAX?

I am currently working on a project that lets users post comments with jquery and ajax. So far it is using Json and retunring several items, username, comment text, user photo url, comment ID number and stuff like that, I then need to use some sort of template to make all this data go into the correct div's before adding it all to the screen.
I am new to using javascript so this is a hard task for me. I am now considering the easy route.
Just have my PHP backend script return the whole block of code, div's and everything in place but I am wondering is this a bad idea? More importantly is it a bad idea with json?
Here is an example of a block of code that needs to be added to the screen when a comment is posted
<li class="admin" id="comment-1371">
<div class="photocolumn">
<!-- START Photo block -->
<div class="imageSub" style="width: 100px;">
<img class="male" src="http://cache2.mycrib.net/images/image_group34/0/39/T_653807517aff2b1f5662d865b40d87d527c8eb.jpg" alt="Something" width="100"/>
<div class="blackbg"></div>
<div class="label">JasonDavis</div>
</div>
<!-- END Photo block -->
</div><!-- END photocolumn -->
<div class="commenttext">
<p>02/12/3009</p>
<p>sample text for comment area!</p>
</div>
<!-- END COMMENTTEXT -->
</li>
I would say it depends on the situation/application. For instance I would use json and templating for a flight/hotel etc result screen. Why return 50k's worth of the same markup when a 4k json object will do and will allow for rapid clientside sort/filter. If you dont need quick clientside filtering/sorting then responding with dom fragments is ok. Horses for courses.
I don't see a problem with returning HTML via AJAX. A bonus of this is that you can generate most of the HTML in a view in PHP and still keep things fairly clean.
Tokenizing your data into an object is nice for re-use but can be overkill for a one-off.
Go the easy route, I can see no reasons of going with JSON array.

Categories