jQuery load page into <div> issues - javascript

I'm using the following code to load a page into a <div>. It works fine except it's not supposed to load all links into the <div>.
<script type='text/javascript'>
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("a").click(function(){
$j.ajax({
url: $j(this).attr("href"),
success: function(response) {
$j("#output").html(response);
}
});
return false;
});
});
</script>
<div>[ <a href="execute.php?cmd=test1">link 1</a] [ <a
href="execute.php?cmd=test2">link 2</a] [ <a href="mypage.com">link
3</a>]</div>
<div id="output"></div>
When I click link 3, used to go to the homepage, it opens the homepage in <div id="output"></div>.
Any idea why this happens?

You are assigning the click event to the a element, so all links will load the url inside the output div. You need to specify which elements to assign the click event, maybe by specifying a class.
$j("a.loadindiv").click
<a class="loadindiv" href
Hope this helps...

Link 3 is making a request to "mypage.com" and taking the html that it returns and outputting it into the 'output' div. You are making an AJAX call to the homepage and it is serving up the page to you.
Rather than having all the elements use the AJAX function you might want to consider doing:
<script type='text/javascript'>
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j(".ajaxLink").click(function(){
$j.ajax({
url: $j(this).attr("href"),
success: function(response) {
$j("#output").html(response);
}
});
return false;
});
});
</script>
<div>[ <a href="execute.php?cmd=test1" class="ajaxLink">link 1</a] [ <a
href="execute.php?cmd=test2" class="ajaxLink">link 2</a] [ <a href="mypage.com">link
3</a>]</div>
<div id="output"></div>

Related

Javascript of selected php file won't load when using JQuery's load(file.php) method

I have a master container php file with a div container. Initially, the div container doesn't have any content or html children by default when page is loaded. I use JQuery to load php files to this div container when the user clicks a navigation item in the navbar.
landingpage.php
<?php
require_once 'navbar.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Admin | Dashboard</title>
<link rel="stylesheet" href="css/dashboard_admin.css">
</head>
<body>
<div class="wrapper">
<!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
<div class="container" id="content_container">
<div class="div_dashboardLabel" id="dashboard_Label">
<h2 id="label_Dashboard">Admin Dashboard</h2>
</div>
</div>
<!-- END OF CONTENT CONTAINER-->
</div>
<!-- end of wrapper-->
<script src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
var user = '<?php echo json_encode($user);?>';
var role = '<?php echo json_encode($role); ?>';
</script>
<script src="js/landingpage.js"></script>
</body>
</html>
landingpage.js
/* GLOBAL VARIABLES WITHIN THIS DOCUMENT*/
var div_content_container = $("#content_container");
var navitem_dashboard = $("#admin_dashboard");
var navitem_admin_account_management = $("#admin_accountmanagement");
var userObj = JSON.parse(user);
var roleObj = JSON.parse(role);
var logout = $('#logout');
/* END */
$(document).ready(function(){
loadDashboard(); // dashboard is loaded as default view.
navitem_admin_account_management.on("click",loadAccountManagement);
});
function loadDashboard() {
var url_admin_dashboard = 'view/admin_dashboard.php';
var url_teacher_dashboard = 'view/teacher_dashboard.php';
var url_student_dashboard = 'view/student_dashboard.php';
div_content_container.html('');
if (roleObj.rolename === 'Administrator') {
div_content_container.load(url_admin_dashboard);
} else if (roleObj.rolename === 'Teacher') {
div_content_container.load(url_teacher_dashboard);
} else if (roleObj.rolename === 'Student') {
div_content_container.load(url_student_dashboard);
}
}
function loadAccountManagement(){
var url = 'view/admin_accountmanagement.php';
div_content_container.html('');
div_content_container.load(url);
}
Everything works as expected for landingpage.php which uses landingpage.js for the front end. No problem.
The problem is when admin_accountmanagement.php file is loaded in div_content_container. The JS of admin_account_management.php doesn't seem to bind to elements:
function loadAccountManagement(){
var url = 'view/admin_accountmanagement.php'; // has its JS file
div_content_container.html('');
div_content_container.load(url);
}
For example, let's take url which is 'view/admin_accountmanagement.php' This page gets loaded within div_content_container when user clicks a navbar item Account Management
as in
<div class="wrapper">
<!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
<div class="container" id="content_container">
<!-- view/admin_accountmanagement.php loaded here -->
</div>
<!-- END OF CONTENT CONTAINER-->
</div>
There are no problems displaying the page or replacing the current element contained in the div_content_container. The problem is, the JS file attached to view/admin_accountmanagement.php doesn't seem to apply when view/admin_accountmanagement.php page is loaded in div_content_container
The view/admin_accountmanagement.php is loaded but the click events binded to the elements of view/admin_accountmanagement.php doesn't work. I know this because I tried to display an alert() message on $(document).ready()
admin_accountmanagement.php
<body>
<div>
<button class="button" id="btn_AddUser">
Add New User
</button>
</div>
<script src="js/admin_accountmanagement.js"></script> <!-- this JS doesn't seem to get binded when this page is loaded in the div_content_container -->
</body>
admin_accountmanagement.js
var btn_add_user = $('#btn_AddUser');
$(document).ready(function(){
alert("TEST"); //doesn't work no alert message.
btn_add_user.on("click",test); //doesn't work no alert message
});
function test(){
alert("testing"); //doesn't work. no alert message
}
I'm only able to display the page but when I click on the <button id="btn_AddUser"> nothing happens.
How can I solve this given the how I structured the loading of pages to div_content_container?
Thanks in advance.
Change your admin_accountmanagement.js to
var btn_add_user = $('#btn_AddUser');
alert('Account management js loaded'); // this should show alert
$(document).on("click",btn_add_user,test);
function test(){
alert("testing"); //doesn't work. no alert message
}
This method works because the binding is not dependent on "document ready" as document ready has already been fired when you loaded the parent page for the first time
#jordan i agree with #Magnus Eriksson as it is better to bind it on('event','selector','function') but make use of .off() before your .on() as you are playing with dynamic content which may cause multiple binding of the function. And if you are still not able to get the binding event to work you can try injecting the .js file in your page's head section after the load of your content like: $('head').append('<script src="admin_accountmanagement.js"></script>'). With your load() function in your js to bind the click event.
Or, your use the below code snippet:
function LoadContent()
{
var url = 'view/admin_accountmanagement.php';
var jssrc = 'js/admin_accountmanagement.js';
div_content_container.html('');
div_content_container.load(url);
if($('head').find('*[src="'+jssrc+'"]').length==0)
{
//the below approach have some consequences related to it as you will not be able to see the injected js in your developers tool's Sources(in chrome).
$('head').append('<script src="'+jssrc+'"></script>');
}
}
and then on your .js will look like this:
var btn_add_user = null;
$(window).load(function(){
alert("TEST");
btn_add_user = $('#btn_AddUser');
btn_add_user.off('click').on("click",test); //use .off('event') if load() is being called multiple times.
});
function test(){
alert("testing");
}

Page not functioning correctly when opened via Ajax

I want to keep my pages separately and load them all into one main page using ajax, this way I can change my layouts much quicker. I use Metro UI Css.
Problem is, my page works perfectly when called alone, but when called through ajax and displayed on the main page, it does not respond, or throw any exceptions. This is my html code for the page that is loaded:
<head>
<script src="../../app/webroot/js/jquery/jquery.min.js"></script>
<script src="../../app/webroot/js/jquery/jquery.widget.min.js"></script>
<script src="../../app/webroot/js/prettify/prettify.js"></script>
<script src="../../app/webroot/js/load-metro.js"></script>
</head>
<body class="metro">
<div class="accordion" data-role="accordion" style="font-size:20px; color:#3D5168">
<div class="accordion-frame">
<a class="heading" href="#"><i class="icon-history"></i>Early days</a>
<div class="content">
<p>Line 1</p>
</div>
</div>
</div>
</body>
I suspect that the line
href="#"
has something to do with it, it might be trying to call to the original page that it came from, instead of the page it is actually displayed on. I do all the same imports on the "caller" page, and as I said, I get no exceptions.
This is how I load the page (Ajax)
function LoadPage(PageName)
{
document.getElementById('LoadedPage').style.visibility='hidden';
document.getElementById('loader').style.visibility='visible'
var xmlHttp=MakeConn();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState === 4)
{
HandleLoad(xmlHttp.responseText,PageName);
}
};
xmlHttp.open("GET", "http://www.somewebsite.com/main/"+PageName, true);
xmlHttp.send(null);
}
function HandleLoad(response,PageName)
{
if(PageName!='home')
{
document.getElementById('home').className = 'tile bg-VSblue1';
}
if(PageName!='games')
{
document.getElementById('games').className = 'tile bg-VSblue1';
}
if(PageName!='about')
{
document.getElementById('about').className = 'tile bg-VSblue1';
}
if(PageName!='contact')
{
document.getElementById('contact').className = 'tile bg-VSblue1';
}
document.getElementById(PageName).className = 'tile double bg-VSblue1 selected';
document.getElementById('loader').style.visibility='hidden';
document.getElementById('LoadedPage').style.visibility='visible';
document.getElementById('LoadedPage').innerHTML = response;
}
Does anyone have some suggestion on how to fix this? Thank you...
This happens because after you called AJAX it wasn't initialized so I won't work. To initialize jst add this line after you place the element in body :
$.Metro.initAll();
That's it now everything will work fine.
Note: If it doesn't try 'initall' instead of 'initAll'

Onclick page should not reload

Hi how can i make my page don't reload every time i click another link?
function myFunctionD(id) {
var x=document.getElementById(id);
var myURL = "http:www.sample.php";
document.location = myURL + "?t_id=" + x.id ;
return false
}
HTML:
<a href="docview.php?id=26" id="3" onclick="myFunctionD('3')" target="iframe_a" >July 17, 2013</a>
<a href="docview.php?id=26" id="4" onclick="myFunctionD('4')" target="iframe_a" >July 18, 2013</a>
You can change the target to open the link in new tab or window . Use window.open() instead of window.location
You can use ajax something like this
<script type="text/javascript">
$(function(){ myFunctionD('3'){
var form = $(this).parent("form");
$.ajax({
type: "POST",
url: form.attr("yourform"),
data: form.serialize()
})
return false;
});
});
</script>
Actually you don't even need to use Ajax. You can simply load content of another page in your current page with Jquery's $.get function
//Inserting a div for holding another page content. On click of button, this div will update content
<div id="contentdiv"></div>
<input type="button" value="Page 1 Load Content" onclick="loadContent('page1.html')"/>
<input type="button" value="Page 2 Load Content" onclick="loadContent('page2.html')"/>
<input type="button" value="Page 3 Load Content" onclick="loadContent('page3.html')"/>
<script type="text/javascript">
function loadContent(page)
{
//Empty contentdiv for new content and add new page content with jquery's $.get
$('#contentdiv').empty();
$.get('http://www.example.com/'+page, function(data) { $("#contentdiv").append(data); });
//This will load page content in your contentdiv
//for more info about $.get visit this http://api.jquery.com/jQuery.get/
}
</script>
In your other pages, just put that content which you want to load into contentdiv. Do not make complete html page with html and body tags etc. Just content you want to appear in you contentdiv.

Update a <div> when the user clicks on a <p> element?

I have the HTML Code:
<div id=ytVid>
<iframe width="420" height="315" src="http://www.youtube.com/embed/5EdmHSTwmWY" frameborder="0" allowfullscreen></iframe>
<script type="text/javascript" src="js/youtube.js"></script>
</div>
At the moment and I have a set of paragraphs that are generated by jQuery using an array.
What I would like to happen is that when the user clicks one of the generated paragraphs, this will start this code from the youtube.js file:
$(document).ready(function() {
function openLink(evt) {
var search = evt.target.innerHTML;
var keyword= encodeURIComponent(search);
var yt_url='http://gdata.youtube.com/feeds/api/videos?q='+keyword+'&format=5&max-results=1&v=2&alt=jsonc';
$.ajax({
type: "GET",
url: yt_url,
dataType:"jsonp",
success: function(response) {
if(response.data.items) {
$.each(response.data.items, function(i,data) {
var video_id=data.id;
var video_frame="<iframe width='420' height='236' src='http://www.youtube.com/embed/"+video_id+"' frameborder='0' type='text/html'></iframe>";
$("#ytVid").html(video_frame);
});
} else {
$("#ytVid").html("<div id='no'>No Video</div>");
}
}
});
};
});
I do not know if the above code is correct but what it should do is take what is in the array(if possible) or what is in the paragraph to search youtube for a video to update the ytVid div.
Thanks
In your "simplified" copy of the JavaScript jsfiddle, you have the strings wrapped in brackets, which signifies they are arrays. You also didn't have jQuery selected to be included.
http://jsfiddle.net/PADL9/1/
And here's one with the JS from above added in
http://jsfiddle.net/PADL9/2/
(remove the alert/return for the AJAX to work)

How do I get past the jQuery error "$ not found error"?

MAIN WINDOW
// some javascript
//some html
//here ajax-call to load all divs
//all divs hidden by default
//based on user choice(from select option), show selected group of divs
//click any shown div to call corresponding popup
POPUP WINDOW
//edit contents of that div.
//on close i need
1. refresh main window to load all divs
2. select the previously selected user option(from select option)
3. show corresponding divs only
4. most important is i have to give the user the main page,
where they clicked the div before(not the page starting always!)
I tried and i am left with " $ not found error ". any ideas..? suggestions?
this is the main window
<script type="text/javascript" src="jquerymin.js"></script>
<script type="text/javascript">
var visible_status=0;
function selectFn(sno){
if(sno==1){
$('#id2').hide();
$('#id1').show();
visible_status=1;
}else if(sno==2){
$('#id2').show();
$('#id1').show();
visible_status=2;
}
}
function popitup(url) {
newwindow=window.open(url+'?parent_status='+visible_status,'name');
if (window.focus) {newwindow.focus();}
return false;
}
</script>
<select name='optionw'
onchange="selectFn(this.options[this.selectedIndex].value);">
<option value="">Select</option>
<option value="1">Div1</option>
<option value="2">All</option>
</select>
<div id='id1' style="display:none;">DIV1</div><!--by ajax i am loading-->
<div id='id2' style="display:none;">DIV2</div><!--these divs-->
<button onclick="popitup('popup.php');">popUp</button><br><!--and these-->
popupwindow
<script type="text/javascript" src="jquerymin.js"></script>
<script type="text/javascript">
var parent_status='<? echo $_GET[parent_status];?>';
function closePopup() {
window.opener.history.go(0);
//alert('going to call parent selectFn('+parent_status+')');
window.opener.selectFn(parent_status);
self.close();
}
</script>
...Here editing a part of the main page content...
<input type=button value=close_popup onclick="closePopup();">
If i remove the comments in the closePopup function , it works as expected. Any help to make it work without commnted line.
I would suggest that perhaps you're not linking to the jQuery library properly or have it linked in the wrong order. Could you provide more details as to what you're asking? Do you want the code to do this, or are you just asking about the jQuery object not being found?
get firebug plugin for firefox. load your page .. go to firebug console .. type $ and if it doesnt say 'function()' you haven't included the jQuery library properly
I'm trying to understand your question; it's very unclear what you're describing. Is the code you're showing coming from your web browser once you've loaded it (by viewing the source) or is it prior to being evaluated on the server?
What happens if you change this line in the popup:
var parent_status='<? echo $_GET[parent_status];?>';
to this:
var parent_status=1;
According to what I have understood here is the code below and check it if this works for you:
Paste this code inside main window:
<?php if(isset($_GET['parent_status'])): ?>
$(document).ready(function(){
selectFn(<?php echo $_GET['parent_status'] ?>);
})
<?php endif ?>
Below this code:
function popitup(url) {
newwindow=window.open(url+'?parent_status='+visible_status,'name');
if (window.focus) {newwindow.focus();}
return false;
}
And, replace the closePopup function inside popup window with this code:
function closePopup() {
var href = window.opener.location.href;
if((pos = href.lastIndexOf('parent_status=')) >= 0)
{
var patt = new RegExp('parent_status=' + parent_status);
href = href.replace(patt, 'parent_status='+parent_status);
} else {
href = window.opener.location.href + '?parent_status=' + parent_status
}
window.opener.location.href = href;
self.close();
}
Hope this helps.

Categories