Load HTML within AJAX call - javascript

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.

Related

Unable to make collapsible work on webpage

I'm attempting to made a collapsible (and hopefully simple) DIV and was working with another answer I had found here on stack overflow but I cannot seem to get it to work on my website. I do have a fiddle with the full links and coding which shows that its actually working (in the fiddle) but then I input the code into my page and it hides the stuff beneath the first picture (using that as the divider) but when I click on it nothing happens (it doesn't display)
Below is the snippet of HTML coding:
<p class="expand-one"> <img src="https://www.mywebsite.net/something/vip1.png"></p>
<p class="content-one">
<td width="33%" align="center" valign="top">
<br>
</td>
<td width="33%" align="center" valign="top">
<a href="http://www.mywebsite.net/bigslice" title="The Big Slice: Home of the Edge">
<font color="#dace77">[ m u s i c ]</font>
</a><br>
<font color="#FAF9B6">$ROOMNAME bigslice$</font><br>$USERLIST bigslice$<br>
</td>
</tr>
</p>
and up in my CSS I have the simple addition of:
<style>p.content-one {
display: none;
}
</style>
And down before the body ends where all my JS scripts are I have
<script>
$('.expand-one').click(function() {
$('.content-one').slideToggle('slow');
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Since the answer was as simple as jQuery not loading before the code using it, I thought I'd post the troubleshooting steps I suggested as an answer. The question may be marked as a duplicate, but if not, maybe someone will stumble upon it and be helped... idk.
Ensure any code using jQuery is added after the jQuery library is included (typically I include jQuery at the end of the body and any custom script after that, but that's personal preference).
Check the brower console (F12) for errors- typically these are easy to grok, or you can search for the error message.
If jQuery attempts to select an element before the element is added (either because the jQuery comes before the HTML code, or because the HTML code is dynamically added after loading), it won't find an element- thus adding a listener won't do anything. Either ensure the code comes after the element, attach the listener to a parent/ancestor and specify which element to listen for (e.g. $(document).on('click', 'p', function() { /*...*/ }) will attach a listener to the entire document which will only run when a paragraph is clicked), or use $(function() { /* code here */ }) to ensure your code doesn't run until the page is done loading.
console.log() is extremely helpful if you're not sure if code just won't run, or if it's running and just not affecting anything. If nothing logs, the code isn't running.

Using .load in JavaScript

I am using .load() function in JavaScript and I'm working with JSP java files. I am loading a page like this in JavaScript
$("#body").load("livestatus #status")
The problem is the div I'm trying to load doesn't load immediately on page load because it contains some data from APIs, so there's a one second delay but my code doesn't accommodate that delay.
Try to put your code in document.ready block or if you are making an ajax request then put your code in Ajax success function
If you use jQuery and it just not initialized for some element, you can use
$(function() {
$("#body"). // ... your code
});
If it calls through some time and you can't track when exactly, you can use live listeners on some event. Like, click on this element.
$("body").on("click", "#body", function() {
// your code
});
$("body") can contain any parent element which had loaded before jQuery.
Or you can load 1px image with you code which loads after main code and track when it will load.
<div id="body">
<!-- your markup -->
<img class="loading-status-img" src="../path_to_1px_small_image.png" style="display:none">
<img class="loading-status-img-2" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQI12NgYAAAAAMAASDVlMcAAAAASUVORK5CYII=" style="display:none">
<!-- your markup -->
</div>
<script>
$("body").on("load", ".loading-status-img", function() {
// execute you code here after #body will load
});
</script>
The second image is encoded with base64.
[UPD] old version of jQuery have another syntax. More: http://api.jquery.com/live/

How to manipulate iframe objects using jquery

I've gone through lot of topics related to this question but unable to get the desired output.
I'm calling a iframe inside and html like this:
<iframe class="full-screen-preview__frame" id="nitseditpreview" src="himu/index.php" name="preview-frame" frameborder="0" noresize="noresize" data-view="fullScreenPreview">
Suppose in this iframe I have h2 tag with a class name like this:
<body>
<section id="about-us">
<div class="container">
<div class="text-center">
<div class="col-sm-8">
<h2 class="maincontent">
Why with Us
</h2>
</div>
</div>
</div>
</section>
</body>
As seen by the inspect element in browser
By using Jquery I want to manipulate this lets say for example I want to put border in this. I've tried a lot of things but I guess this thing will work if anyone fixes the bug, my jquery looks like this:
$(document).load(function () {
$('#nitseditpreview').load(function () { //The function below executes once the iframe has finished loading
$this = $(this);
$('#nitsmenu', this.contents()).css('border', 'solid 1px #777');
});
});
Don't know where I'm doing mistake, even I'm following same origin policy too.
If both framed and framing documents are on the same domain, there shouldn't be any need for sandbox attributes or CORS hoop-jumping. But there are a number of other errors here:
$(document).load(...) should be $(document).ready(...) (since it has already loaded by the time your script runs)
you define $this = $(this), but then in the next line try to use a bare this
You're trying to match a #nitsmenu that doesn't appear to exist in the framed document
The following appears to work, although I'm concerned there may still be a race condition on that iframe's .load():
$(document).ready(function() {
$('#nitseditpreview').load(function() {
$(this).contents().find('.container').css('border', 'solid 1px #777');
});
});
http://plnkr.co/edit/tCEHdU0ckg5q4w4tPVFU

Loading dynamic contents when a div is clicked

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.

Add link to dynamic text with javascript

I'm trying to make a dynamic text a link with javascript:
<div class="container">
<div class="form-current">
<form>
<h2 style="margin-left:10px" ><a href='#' onclick="homePage()" id="h2Current" ></a></h2>
<div id="node-current"></div>
</form>
</div>
This is the html and the text is loaded from a DB through a javascript function:
var h2Current = document.getElementById('h2Current');
h2Current.innerHTML = 'Day '+data[0]['day'];
the parameter "data" is a simple Json. The text appear underlined correctly but is impossibile to click.
Thanks in advance
You need to check your JSON. Check JSON i have written is a correct one. check your JSON format. You can use jsonlint.com to validate JSON you are trying to use.
<html>
<head>
</head>
<body>
<div class="container">
<div class="form-current">
<form>
<h2 style="margin-left:10px" ><a href='#' onclick="homePage()" id="h2Current" ></a></h2>
<div id="node-current"></div>
</form>
</div>
</div>
<script>
var data = [{ 'day':'monday'},{ 'day':'tuesday'}]
var h2Current = document.getElementById('h2Current');
h2Current.innerHTML = data[0]['day'];
</script>
</body>
The problem is not the JSON since you say that it appears and is underlined properly. The issue is that you are either not actually calling your 'homePage' function during the 'onclick' event, or there is an unhandled exception in the code of your 'homePage' function. Here is how you go about debugging this issue.
You need to open your site in Chrome, and open the developer tools, 'F12'. Click the 'Sources' tab, and find your .JS file, or the page file, if it contains the function, 'homePage' inline. You may need to open the 'File Navigator'. If this is the case, click the "arrow in the box" directly beneath the 'Elements' tab.
Once the file is opened, find the function declaration 'homePage' and breakpoint the first non var declarative line. Now, simply click the link and step through the function. You may find that you are not even calling the function at all and you may even see JS exceptions listed. Address any exceptions which appear inline in your code. If you are actually reaching your function, step through every line, 'F11' including any nested functions, until you find the exception.

Categories