I am facing with some glitches regarding the ajax load
OK, so the query is lets say I have page a (picture attached)
the ajax loads the div into the "RESULT" div on clicking the specific id's
here is the ajax script & the html i have come so far. this loads perfectly on the Result div on the page a itself.
<a href="#" id="one" /><br>
<a href="#" id="two" /><br>
<a href="#" id="three" /><br>
<div id="result" class="functions"></div>
$.ajaxSetup({
cache: false
});
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
var loadUrl = "content.php";
$("#one").click(function () {
$("#result").html(ajax_load).load(loadUrl);
});
var load2Url = "content1.php";
$("#two").click(function () {
$("#result").html(ajax_load).load(loadUrl);
});
var load3Url = "content2.php";
$("#three").click(function () {
$("#result").html(ajax_load).load(load2Url);
});
thing is i need to load the same contents on the result div on page b from another page using the same id calls, lets say page b.
the concept is, on page b, the id is clicked, it LOADS page a first & loads the content on "RESULT" div. both pages are on the same server
Would really appreciate any assistance. thank you.
One way to handle it will be to pass the dynamic item as a request parameter like in page b use the url /pagea.html?section=one etc
Then on page load
$(function(){
var location = window.location.href;
var page = location.substring(location.indexOf('=') + 1);
$('#' + page).trigger('click');
})
You got your loadUrl's in the wrong pace they should be inside of the function otherwise it's value is the last value it was set to which is content2.php
jsFiddle Demo
$.ajaxSetup({
cache: false
});
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
$("#one").click(function () {
var loadUrl = "content.php";
$("#result").html(ajax_load).load(loadUrl);
});
$("#two").click(function () {
var loadUrl = "content1.php";
$("#result").html(ajax_load).load(loadUrl);
});
$("#three").click(function () {
var loadUrl = "content2.php";
$("#result").html(ajax_load).load(loadUrl);
});
Related
Not sure what's wrong but I'm getting this error from my chrome console:
jquery-3.2.1.slim.min.js:1244 jQuery.Deferred exception: $.ajax is not a function TypeError: $.ajax is not a function
at HTMLDocument.<anonymous> (file:///C:/Users/Adam/Desktop/UseTime/js/example.js:3:7)
at j (file:///C:/Users/Adam/Desktop/UseTime/js/jquery-3.2.1.slim.min.js:1193:55)
at k (file:///C:/Users/Adam/Desktop/UseTime/js/jquery-3.2.1.slim.min.js:1199:45) undefined
r.Deferred.exceptionHook # jquery-3.2.1.slim.min.js:1244
jquery-3.2.1.slim.min.js:1247 Uncaught TypeError: $.ajax is not a function
at HTMLDocument.<anonymous> (example.js:3)
at j (jquery-3.2.1.slim.min.js:1193)
at k (jquery-3.2.1.slim.min.js:1199)
From this JavaScript:
$(function() { //when the DOM is ready
var times; //declare global variable
$.ajax({ //set up request
beforeSend: function (xhr) { //before requesting data
if (xhr.overrideMimeType) { //if supported
xhr.overrideMimeType("application/json"); // set MIME to prevent errors
}
}
});
//funciton that collect data from the json file
function loadTimetable() { //decalre function
$.getJSON('data/example.json') //try to collect json data
.done(function (data) { //if succesful
times = data; //store in variable
}).fail(function () { //if a problem: show message
$('#event').html('Sorry! we couldnt load your time table at the moment');
});
}
loadTimetable(); //call the function
//CLICK ON TEH EVENT TO LOAD A TIME TABLE
$('#content').on('click', '#event a', function (e) { //user clicks on place
e.preventDefault(); //prevent loading page
var loc = this.id.toUpperCase(); //get value of id attr
var newContent = "";
for (var i = 0; i < times[loc].length; i++) { // loop through sessions
newContent += '<li><span class = "time">' + times[loc][i].time + '</span>';
newContent += '<a href = "descriptions.html#';
newContent += times[loc][i].title.replace(/ /g, '-') + '">';
newContent += times[loc][i].title + '</a></li>';
}
$('#sessions').html('<ul>' + newContent + '</ul>'); // Display Time
$('#event a.current').removeClass('current'); // update selected link
$(this).addClass('current');
$('#details').text('');
});
//CLICK ON A SESSION TO LEAD THE DESCRIPTION
$('#content').on('click', '#sessions li a', function (e) { //click on session
e.preventDefault(); // prevent loading
var fragment = this.href; //title is in href
fragment = fragment.replace('#', ' #'); //Add Space before #
$('#details').load(fragment); //to load info
$('#sessions a.current').removeClass('current'); //update selected
});
//CLICK ON PRIMARY NAVIGATION
$('nav a').on('click', function (e) { //click on nav
e.preventDefault(); //prevent loading
var url = this.href; //get UR: to load
$('nav a.current').removeClass('current');
$(this).addClass('current');
$('#container').remove(); //remove old
$('#content').load(url + ' #container').hide().fadeIn('slow'); // add new
});
});
I'm not sure if it's an issue with the way I'm initiating .ajax or if my jquery isn't correctly implemented. I think it is. Any Thoughts?
edit: here's the html that goes with the script above
<!DOCTYPE html>
<body>
<header>
<h1>UseTime</h1>
<nav>
HOME
PROFILE
MANAGE TASKS
TIME TABLE
</nav>
</header>
<section id="content">
<div id="container">
<div class="third">
<div id="event">
<a id="class1" href="class1.html"><img src="" alt="class1" /> Class 1 </a>
<a id="class2" href="class2.html"><img src="" alt="class2" /> Class 2 </a>
<a id="class3" href="class3.html"><img src="" alt="class3" /> Class 3 </a>
</div>
</div>
<div class="third">
<div id="sessions"> Select a Class from the left </div>
</div>
<div class="third">
<div id="details"> Details </div>
</div>
</div>
<!-- container -->
</section>
<!-- content -->
<script src="js/jquery-3.2.1.slim.min.js"></script>
<script src="js/example.js"></script>
</body>
You are using slim version of jQuery. It Doesn't support ajax Calling.
Use
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
instead of it.
Slim build
Sometimes you don’t need ajax, or you prefer to use one of the many
standalone libraries that focus on ajax requests. And often it is
simpler to use a combination of CSS and class manipulation for all
your web animations. Along with the regular version of jQuery that
includes the ajax and effects modules, we’ve released a “slim” version
that excludes these modules. All in all, it excludes ajax, effects,
and currently deprecated code. The size of jQuery is very rarely a
load performance concern these days, but the slim build is about 6k
gzipped bytes smaller than the regular version – 23.6k vs 30k. These
files are also available in the npm package and on the CDN:
https://code.jquery.com/jquery-3.1.1.slim.js
https://code.jquery.com/jquery-3.1.1.slim.min.js
Referred from jQuery Blog
jQuery 3 slim version doesn't support ajax.
According to the release docs,
Along with the regular version of jQuery that includes the ajax and
effects modules, we’re releasing a “slim” version that excludes these
modules. All in all, it excludes ajax, effects, and currently
deprecated code.
To use .ajax method, simply use the full version one.
Try this one (jquery-3.2.1.min.js) instead of slim (jquery-3.2.1.slim.min.js)
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
I want to load some PHP page to div tags with this, but this code does not work;
<span>Dahili Branşlar</span>
<a href="#" id="cerrahi" ><span>Cerrahi Branşlar</span></a></li>
<script>
var yuklenecek = document.getElementById(id);
$("#"+yuklenecek).on("click", function(){
$("#orta_load").load(yuklenecek+".php");
});
</script>
<div id="orta_load">
when ı click to buton that which ı choose : should load dahili.php or cerrahi.php page in here
</div>
You need this:
$(".loaddiv").click(function() {
var url = $(this).attr("id") + ".php";
$("#orta_load").load(url);
console.log("loading " + url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Dahili Branşlar</span>
<span>Cerrahi Branşlar</span>
<div id="orta_load">
when ı click to buton that which ı choose : should load dahili.php or cerrahi.php page in here
</div>
Note how the jQuery function assigns the click handler to each <a>, then uses its id to determine the php document.
I'm using dynamic content in PHP and I need to get the image title and then append that to the end of the current URL. When the user clicks the image they'll be sent to that destination.
For instance - www.foo.com/bar/ is the current url. The image title is dynamic "current-image-title". I need the anchor with the class "item-link" to now use "www.foo.com/bar/current-image-title" when the user clicks the image
<a class="item-link" href="new-category">
<img id="item-desc" src="image.jpg" title="dynamic-title">
</a>
<script type='text/javascript'>
var link = $('#item-desc').each(function() {
$(this).attr('title');
$('a.item-link').click(function(event) {
event.preventDefault();
document.location.href = document.location + '/' + '$link';
});
</script>
I can figure out how to either get and use the image title or how to append to the end of the URL but I can't seem to figure out how to do both.
You could try
$(".item-link").each(function () {
var $this = $(this), $img = $this.find("img");
$this.attr("href", $this.attr("href") + "/" + $img.attr("title"));
});
Try it on https://jsfiddle.net/gkk9ohca/
I am having a problem with jQuery where by it is not loading inside a requested div.
Setup:
On index.php I have 4 Morris charts on 4 tabs all working fine.
On each tab there is a list. Each item in the list is a link
Upon clicking the link the div within the tab reloads with new data
via post:
$(document).ready(function () {
$('.click5').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company5-'+companyId+' .clickthrough5').val(),
ref_date_from5: $('#company5-'+companyId+' .ref_date_from5').val(),
ref_date_to5: $('#company5-'+companyId+' .ref_date_to5').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
The new div contains a back button to take you back to a replica of the 1st graph but on a different page (donut1.php), for my personal ease:
$(document).ready(function () {
$('.backref2').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut1.php', {
clickthrough6: $('#company6-'+companyId+' .clickthrough6').val(),
ref_date_from6: $('#company6-'+companyId+' .ref_date_from6').val(),
ref_date_to6: $('#company6-'+companyId+' .ref_date_to6').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
All this code works fine up until landing on donut1.php.
At this point I proceeded to pull out chunks of my hair for several hours looking through Inspect Element in Chrome to identify the issue.
1 bald person later I realised the jQuery was not loading although it is correctly requested in a script tag.
I confirmed this by placing the following on both donut1.php and donut5.php:
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
donut5.php displays the output fine while donut1.php does not.
I then tried to load an external source and a different version using the Google snippets found here but this still did not work.
Some points to note:
I currently have jquery loading in my header and footer as part of trying to work this out.
As the 2 pages donut1.php and donut5.php do not include header or footer I have manually included them both in there. Same exact way in both files. donut5.php works donut1.php does not.
Order is index.php > donut5.php > donut1.php and then you continue to cycle between donut5 and donut 1 - or you would if the post on click was working in donut1.php.
Any help would be greatly appreciated!
EDIT: donut1.php:
<?php
include("../../../includes/config.php");
$selected = $_POST['clickthrough6'];
$date_from = $_POST['ref_date_from6'];
$date_to = $_POST['ref_date_to6'];
?>
<script src="../../../js/jquery-1.11.0.js"></script>
<script>
$(document).ready(function () {
$('.click7').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company7-'+companyId+' .clickthrough7').val(),
ref_date_from5: $('#company7-'+companyId+' .ref_date_from7').val(),
ref_date_to5: $('#company7-'+companyId+' .ref_date_to7').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
</script>
<div id="tabs2">
<div id="tabs-1" class="donut5">
<h4>Top 5 Referrers - Quotes <br /><small>Total number of Quotes between <?php echo date("d/m/Y", $date_from); ?> to <?php echo date("d/m/Y", $date_to); ?></small></h4>
<div class="statgrid">
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
<?php $quotes_q="SELECT
c.case_id,
co.name AS company_name,
co.company_id AS company_id,
COUNT(c.case_id) 'quote_count'
FROM
(`case` c,
`panel_company` pc,
`panel` p)
LEFT JOIN company co ON (co.company_id = pc.company_id)
WHERE pc.panel_id = " .$RegisteredUser['panel_id']. " AND
p.company_id = pc.company_id AND
c.panel_id = p.panel_id AND
c.insert_date > ".$date_from. " AND
c.insert_date < ".$date_to. "
GROUP BY p.panel_id
ORDER BY quote_count DESC, co.company_id
LIMIT 5";
$result=$mysqli->query($quotes_q); ?>
<div class="col-2-6">
<div id="morris-donut-chart6"></div>
</div>
</div>
<div class="statgrid">
<?php while ($row=$result->fetch_array()) { ?>
<div class="col-4-6">
<div id="company7-<?php echo $row['company_id'];?>">
<input type="hidden" class="ref_date_from7" value="<?php echo $date_from; ?>" />
<input type="hidden" class="ref_date_to7" value="<?php echo $date_to; ?>" />
<input type="hidden" class="clickthrough7" value="<?php echo $row['company_id'] ?>" />
<a><div id="<?php echo $row['company_id'];?>" class="click7 col-5-6"><?php echo $row['company_name']; ?></div></a>
<div class="col-1-6"><?php echo $row['quote_count']; ?></div>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
<?php
$quotes_q = "SELECT
c.case_id,
co.name AS company_name,
COUNT(c.case_id) 'quote_count'
FROM
(`case` c,
`panel_company` pc,
`panel` p)
LEFT JOIN company co ON (co.company_id = pc.company_id)
WHERE pc.panel_id = ".$RegisteredUser['panel_id']." AND
p.company_id = pc.company_id AND
c.panel_id = p.panel_id AND
c.insert_date > ".$date_from." AND
c.insert_date < ".$date_to."
GROUP BY p.panel_id
ORDER BY quote_count DESC, co.company_id
LIMIT 5";
$result = $mysqli->query($quotes_q);
?>
<script>
var donut_data6 = [
<?php while ($row = $result->fetch_array()) { ?>
{
label: '<?php echo substr($row['company_name'],0,15); ?>',
value: '<?php echo $row['quote_count']; ?>'
},
<?php } ?>
];
var donut6 = {
element: 'morris-donut-chart6',
data: donut_data6,
resize: false
}
donut6 = Morris.Donut(donut6)
</script>
EDIT2:
Not too sure if this makes a different but in Network tab I have 2 listings for jquery the initial one loaded from the header which loads 304 Not Modified and the 2nd one which loads on calling donut5.php which loads as 200 OK. Seems that after this I cannot request jquery again perhaps?
EDIT3: in donut1.php I have removed everything except for the jquery script request and the Hello World inside the div I am trying to retrieve. Network tab still shows that jquery is not loading. The strange thing is I have this exact setup, minus the charts, working on the same page (different div classes of course), and this does load jquery fine.
EDIT4: Substituted jQuery for JS as a test and not even basic stand alone JS will work, added in:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Nothing :( - Looping in JS world
EDIT5: Suppose <script> is a HTML tag so looping in them too.
EDIT6: When adding console.logo(data) to the function in list item 4 above I get back the following (obviously I have excluded a lot for testing:
<script src="../../../js/jquery-1.11.0.js"></script>
<script src="../../../js/jquery-ui.js"></script>
<!--
<script>
$(document).ready(function () {
$('.click7').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company7-'+companyId+' .clickthrough7').val(),
ref_date_from5: $('#company7-'+companyId+' .ref_date_from7').val(),
ref_date_to5: $('#company7-'+companyId+' .ref_date_to7').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
</script>
-->
<div id="tabs2">
<div id="tabs-1" class="donut5">
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
</div>
</div>
EDIT7:
Placing code here to confirm if I have correctly inplemented KevinB's suggestion.
var
contentSelector = '.donut5',
$content = $(contentSelector),
contentNode = $content.get(0);
var documentHtml = function (html) {
// Prepare
var result = String(html)
.replace(/<\!DOCTYPE[^>]*>/i, '')
.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
.replace(/<\/(html|head|body|title|meta|script)\>/gi, '</div>');
// Return
return $.trim(result);
};
$(document).ready(function () {
$('.click5').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company5-' + companyId + ' .clickthrough5').val(),
ref_date_from5: $('#company5-' + companyId + ' .ref_date_from5').val(),
ref_date_to5: $('#company5-' + companyId + ' .ref_date_to5').val()
},
function (data) {
var
$data = $(documentHtml(data)),
$dataBody = $data.find('.donut5'),
$dataContent = $dataBody.find(contentSelector),
$menuChildren, contentHtml, $scripts;
// Fetch the scripts
$scripts = $dataContent.find('.document-script');
if ($scripts.length) {
$scripts.detach();
}
// Fetch the content
contentHtml = $dataContent.html() || $data.html();
$scripts.each(function () {
var $script = $(this),
scriptText = $script.text(),
scriptNode = document.createElement('script');
if ($script.attr('src')) {
if (!$script[0].async) {
scriptNode.async = false;
}
scriptNode.src = $script.attr('src');
}
scriptNode.appendChild(document.createTextNode(scriptText));
contentNode.appendChild(scriptNode);
});
console.log(data);
});
});
});
EDIT8:
After trying the code above in EDIT7 the .donut5 in no longer being pulled from donut5.php to index.php which was originally working. I can see that jquery doesn't duplicate anymore on Network tab when clicking the link for donut5.php (even though the call to it is still there). Currently either I assume I have not mapped a div correctly above as I did remove part of the class find code for :first as I felt it was not required or somehow I have managed to make things worse!
When you pass an htmlstring to .html, one of two things happen. It either gets inserted using .innerHTML, or it gets inserted using .empty().append(htmlString). Which one is chosen is based on the complexity of the htmlstring passed in.
If it's relatively simple, .innerHTML will be used and scripts will execute in the way you expected.
However, if it is more complex, the elements are first parsed and appended to a docFragment before being appended to the document. This middle step is what causes your problem because the javascript will be executed before the elements are part of document.
The only way to fix this issue is to forcibly delay the execution of the javascript by either coding the javascript in such a way that it's execution is in a callback that later gets called, or by removing the javascript from the htmlstring before appending it and then executing it after.
Below is an example of the former:
(function divTestLooper () {
if (!$("#divTest1").length) {
// the element didn't exist, lets wait a little longer...
return setTimeout(divTestLooper, 10);
}
$("#divTest1").text("Hello, world!");
})();
Here is an example of the latter:
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L60-L70
and
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L123-L135
and
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L158-L167
Of course, the best solution is likely to avoid this problem entirely by not including javascript in your partials.
I have this page, the first button is working good.
I want when press the second button to give me the link that is in the href, i tried like this , but i got the whole page , not just the value of the link , why please?
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var url = "http://localhost/test/asdfasdf.php";
$("#button").on("click", function() {
$('body').load( url );
});
$("#button2").on('click',function(){
$('body').load( url +"#link" );
});
});
</script>
</head>
<body>
<input type="button" id="button" value="load" />
<input type="button" id="button2" value="search for a tag" />
</body>
</html>
I think you want a space:
$('body').load(url + " #link");
http://api.jquery.com/load/#loading-page-fragments
All you seem to want is the href of the a#link element at that URL. So instead of loading it into the <body>, just make the AJAX request, and look through the result:
$.ajax({
type: "GET",
url: "http://localhost/test/asdfasdf.php",
dataType: "html"
}).done(function (data) {
var the_link = $(data).find("#link");
alert(the_link.attr("href"));
});
And to put the href in the <body>, add this line in the .done() method:
$("body").html(the_link.attr("href"));
// or
$("body").append(the_link.attr("href"));
But if you actually want to load the a#link element into <body>, do what you had before, but then look for the a#link element and get its attribute:
$('body').load(url + " #link", function () {
var the_link = $("#link");
alert(the_link.attr("href"));
});
EDIT
You're trying to capture the href of the <a> on a different page. A try:
$.get(url+' #link', function(data) {
var $link = $(data).find('a').attr('href');
alert($link);
});
That is my very best guess, but its a shot in the dark.
Currently your code evaluates to .load('http://localhost/test/asdfasdf.php#link'), where #link is a useless fragment. You need a space to engender jQuery's special behavior of automatic DOM parsing and element loading.
$("body").load(url + " #link");
EDIT: to get the actual link value:
$.get(url).done(function (html) {
console.log($(html).find('#link').attr('href'));
});
You can also append to body inside of the .done callback.