Why is my div populated with my whole page? - javascript

I'm trying to load a div from another page using ajax but maintain the URL integrity using the History API. The ajax and history part is working (ie. the div is loading and the url is changing) but for some reason my div contains my entire page not just what is meant to be in the div!
This is the case for both the original page and the page div being loaded.
Stripped back HTML
<!DOCTYPE html>
<html>
<body>
<div id="slider">
... all the page content
<a rel='tab' href="p/password.jsf">Forgot password?</a>
</div>
</body>
</html>
JS
<script>
$(function(){
$("a[rel='tab']").click(function(e){
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
$.ajax({
url:pageurl + '?rel=tab',
success: function(data){
$('#slider').html(data);
}});
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({
url:location.pathname+'?rel=tab',
success: function(data){
$('#slider').html(data);
}});
});
</script>

If you want to fetch an part of an page with ajax, then you can use the load method with the id of the element to fetch the content from.
$('#slider').load(pageurl + '?rel=tab #container_with_content_to_fetch', function() {
alert('callback after success.');
});
More info about load(): info

You may need to stop the default click action. It appears as though your link is acting as a... link.
$("a[rel='tab']").click(function(e){
e.preventDefault();
...

you if you want to select a specific part of the page that you recive with the ajax response
then do the following
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({
url:location.pathname+'?rel=tab',
success: function(data){
var mydiv = $('#my_div_id' , data ) // this will get the div with an id of #my_div_id
$('#slider').html(mydiv );
}});
});

$.ajax loads the whole page. You can use .load()
Instead of
$.ajax({
url:pageurl + '?rel=tab',
success: function(data){
$('#slider').html(data);
}});
you can use
$('#slider').load(pageurl + ' [rel=tab]');
The docs are here.

Related

Ajax page load with <a> tag

I have an a-tag which when clicked, page gets reloaded and certain php code is executed. On successful execution of php code the page is then redirected to same page.
Now, the problem is that the page is jumping to the top which I guess is normal unless you don't use ajax. So, if I can get some assistance with the lines of codes below.
html:
Unfollow
on clicking the above link this php code is executed
php:
if(isset($_GET['key']) && isset($_GET['val'])){
//some task....
header('location:home.php');
}
NOTE: all codes are is same page home.php
if I can do this without reloading the entire page that would really be helpful.
[Edit] I am really sorry to not have added this in my question. I am using php to show bunch of datas on my page from mysql database. hence all datas have same id and class
try to do this via ajax
Unfollow
<script>
$(function(){
$('.ajax_reload').on('click',function(){
$.ajax({
url : home.php,
type:'POST',
data : {key: $(this).data('key'), val:$(this).data('someval')},
dataType:'json',
success:function(data)
{
if(data.success==1)
location.reload();
}
});
});
});
</script>
in home .php
if(isset($_POST['key']) && isset($_POST['val'])){
//some task....
echo json_encode(array('success'=>1));exit();
}
It may contain some syntax errors it is basic idea how to use it via ajax
To have your redirected page scroll down to the initial location, include a fragment (#) at the end of the location header:
if(isset($_GET['key']) && isset($_GET['val'])){
//some task....
header('location:home.php#ajax_reload"');
}
A more simple solution to this would be to build the link with a tag, and add the tag in the HTML, for example:
Unfollow
<div name="LinkThisPartOfThePage">...</div>
Now your link will point to that particular div
If you want to perform an action in PHP without reloading the page, a solution is by using ajax.
Example :
Html :
Click !
Javascript :
$("#ajaxButton").on('click', function() {
var btn = $(this);
$.ajax({
url : 'phpscript.php?key=somevalue&val=1',
type : 'GET',
dataType : 'json',
success : function(dataObject, statut){
// some tasks ...
console.log(dataObject);
},
error : function(result, statut, error){
console.log(erreur);
}
});
});
PHP :
<?php
if(isset($_GET['key']) && isset($_GET['val'])){
//some task....
return json_encode($result);
}
?>
This way the return of the PHP is use with javascript withount any reloading

changing script src onclick, will it execute once the page has loaded?

So lets say I have a script that loads immediately when you load a page.
But when you click on a button, the script src changes. Will that new src get executed?
HTML
<button>
click
</button>
<script class="tracking" src="www.gamespot.com"></script>
Javascript
$("button").on("click",function(){
$.ajax({
url: url,
dataType: "script",
success: console.log("success")
});
});
var url = "www.test.com";
I was actually thinking of appending the second script into the DOM when the button is clicked, but the results are funky on jsfiddle for some reason, so I'm not sure if that works..
Try to use RequireJS
Would be something like this:
var url = "www.test.com";
$("button").on("click",function(){
require(url, function() {
// callback that is executed after the script is loaded
});
});

Event handling in dynamically generated page

I have a div with class called 'taglines' which is contained in a div with class called 'container'. When 'taglines' is clicked, it navigates to another page. The problem is the events on this new page are not responding after navigation. The following is the code that I am using to navigate:
$(document).ready(function(){
$('.container').on('click', '.tagLines', function(){
window.location = "manageMarks.php";
});
}
The following is the code with the event that is refusing to work after navigation:
$(document).ready(function(){
$('.container').on('click', '.loadSub', function(){
alert('Clicked');
});
});
However, If i use ajax to load the new view I want, the events do eventually work. The following is the ajax I code I am using:
$(document).ready(function(){
$('.container').on('mouseover', '.tagLines', function(){
$.ajax({
type: 'GET',
url: 'manageMarks.php',
data: {
videoCode: $(this).attr('data-code')
},
success: function(data){
//alert(data);
$('.container').html(data);
}
}).error(function(){
alert('An Error Has Occured');
});
});
How can I get it to work without using ajax?
Are you doing a full page reload? If so your events would need to be wired up again. If not they should get wired up to dynamically loaded content.

Scroll to certain div with url

Can i send the request to load certain div with a url only something like abc.com/#header1 cause the approach i am using i have to make 5 separate files for my task and update all of them.
If it can be done by including any piece of code in my one file then it'll be best for me.
I want the scroll on div with the url request something like abc.com/#def where def is the id of the div the page should load.
In relation to your previous question, this is how you can do it:
$(function(){
// get hash value
var hash = window.location.hash;
// now scroll to element with that id
$('html, body').animate({ scrollTop: $(hash).offset().top });
});
You need to put that code in page where you want element to scroll. So if you visit yourdomain.com/#foo, it would scroll to an element with id set to foo.
You can use jQuery to load some url in particular div within the page.
Here is an example with fraction of code :
$('#result').load('test.html', function() {
alert('Hello,I am in the div');
});
If you need the data of that particular url to be shown.Then,you can use Ajax along with Jquery.
Here is a small code for it:
$(document).ready(function(){
$("#result").load(function(){
$.ajax({
type: 'GET',
url: "http://localhost/a.html",
success:function(data){
alert(data);
}
});
return false;
});
});
Hope this helps you.
try this : document.getElementById('elmID').scrollIntoView(true);

How to update a value by jQuery AJAX

I load content of a page by jQuery AJAX as
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php?start="+$('#lastid').text(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
In the current document, I have <div id="lastid"></div> and in the external php file <div id="start"></div>
The value for id="start" is updated from database, and it will be transferred to id="lastid". However, this code only works for FIRST click. For default <div id="lastid">1</div>, when clicking the button (id="more") it will read load.php?start=1 and updates the current document to <div id="lastid">11</div> (it's visible). But the second click will not load load.php?start=11
It seems that $('lastid') well reads the default value of <div id="lastid"></div>, but NOT when it has been updated by $("#lastid").empty().load('html #start')
How can I modify this code to work for subsequent clicks?
Wow, what a mess! Let's clean up a bit :)
You need to get rid of the id, as an id has to be unique and if you load another div with id lastId into your site, jQuery will not know which id to get. If you have many divs, each containing the id, you can just read the last id by using ('div:last').text();
So your ajax would look like this:
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php",
data: "start="+$('div:last').text()
success: function(html){
$("#results").append(html);
}
});
});
});
I also don't know what you do with the last line in the success, as load should be used to load data from the server with ajax, what is what you do by using $.ajax(). Also load() takes at least an url as parameter, see here.
try .live() function instead of .click()
Mate,
What I see from you code is that you are attaching an event once the page is loaded. And this creates a static call with static values that don't get updated as you continue.
My suggestions is to use a function that will feed an Id dynamically to your ajax call as follows:
$(document).ready(function(){
$(document).on("click", '#next', function(event){
$.ajax({
url: buildurl(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
function buildurl()
{
return "load.php?start="+ $('#lastid').text();
}
This will force your event to always call this function and the function to get a fresh value from lastid.
Regards
you have to change your success function because you have multiple #lastid when clicking twice.
try something like:
success: function(html){
$("#lastid").removeAttr("id"); // remove's the id from #lastid
$("#results").append(html); // appends the new one
$("#lastid").empty().load('html #start');
}

Categories