Is there anyway to reload just the AJAX request, so that it updates the content pulled from the external site in the code below?
$(document).ready(function () {
var mySearch = $('input#id_search').quicksearch('#content table', { clearSearch: '#clearsearch', });
var container = $('#content');
function doAjax(url) {
if (url.match('^http')) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var fullResponse = $(filterData(data.results[0])),
justTable = fullResponse.find("table");
container.append(justTable);
mySearch.cache();
$('.loading').fadeOut();
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
});
} else {
$('#content').load(url);
}
}
function filterData(data) {
data = data.replace(/<?\/body[^>]*>/g, '');
data = data.replace(/[\r|\n]+/g, '');
data = data.replace(/<--[\S\s]*?-->/g, '');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
data = data.replace(/<script.*\/>/, '');
data = data.replace(/<img[^>]*>/g, '');
return data;
}
doAjax('link');
});
Right now I have a button which reloads the entire page, but I just want to reload the AJAX request. Is this even possible?
Edit: I need to specify more. While it can easily call the AJAX again, can it also replace the info that is already there?
You just need to call the doAjax function again on button click...
$("#buttonID").on("click", function() {
doAjax("link");
});
Add that into the above document.ready code and set the button ID correspondingly.
Then change
container.append(justTable);
to
container.html(justTable);
In your doAjax function you append HTML onto an element. If you overwrite the element's HTML instead of appending to it then the HTML will be "refreshed" each time the doAjax function runs:
Simply change:
container.append(justTable);
To:
container.html(justTable);
And of-course you can bind a click event handler to a link (or any element) like the rest of the answers show. Make sure you bind the click event in the proper scope (inside the document.ready event handler) so the doAjax function will be accessible from the click event handler.
Related
I have a page displaying data from a json feed and I also have a button which loads more of the feed on click of a button. My aim is to append some content inside the page for each feed item. I have been able to create a function which does this on load of the page, but I am unsure how to make this work with the aysynchronous loading of more data.
I understand I need to use the .done() callback to make this work but need some guidance how to implement it correctly.
This function appends the new content initially:
function appendFeed() {
$('.feed__item').each(function (index) {
$feedItem = $('.feed__item', $(this));
$feedItem.append('<div class="feed-gallery"></div>');
for (var i = 1; i <= 5; i++) {
var $count = i;
if ($count > 1) {
$('.feed.gallery', $(this)).append('<div><img data-lazy="//placehold.it/50x50"></div>');
};
});
}
This is where the .done() callback is referred, on click of a button:
$('button').click(function(){
$.getJSON(uri, function (json, textStatus) {
// do stuff
}).done(function (json) {
// do stuff - in my case this would be appendFeed()
});
});
I have already called the appendFeed() function, but if I put it inside the .done() callback on click the button, then it appends the feed again. How do i prevent the duplication for the feed that is already on the page?
This is how you will write.
<script type="text/javascript">
$.getJSON("/waqar/file.php").done(function (data) {
$(".output").append(data);
});
</script>
So I'm fairly novice with jquery and js, so I apologise if this is a stupid error but after researching I can't figure it out.
So I have a list of data loaded initially in a template, one part of which is a dropdown box that lets you filter the data. My issue is that the filtering only works once? As in, the .change function inside $(document).ready() only fires the once.
There are two ways to reload the data, either click the logo and reload it all, or use the search bar. Doing either of these at any time also means the .change function never fires again. Not until you refresh the page.
var list_template, article_template, modal_template;
var current_article = list.heroes[0];
function showTemplate(template, data)
{
var html = template(data);
$("#content").html(html);
}
$(document).ready(function()
{
var source = $("#list-template").html();
list_template = Handlebars.compile(source);
source = $("#article-template").html();
article_template = Handlebars.compile(source);
source = $("#modal-template").html();
modal_template = Handlebars.compile(source);
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
$("#classFilter").change(function()
{
console.log("WOW!");
var classToFilter = this.value;
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.heroClass.search(classToFilter) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
$("#searchbox").keypress(function (e)
{
if(e.which == 13)
{
var rawSearchText = $('#searchbox').val();
var search_text = rawSearchText.toLowerCase();
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.name.search(search_text) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
}
});
$("#logo").click(function()
{
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
//$("#logo").click();
});
function displayModal(event)
{
var imageNumber = $(this).data("id");
console.log(imageNumber);
var html = modal_template(current_article.article[0].vicPose[imageNumber]);
$('#modal-container').html(html);
$("#imageModal").modal('show');
}
I should note two things: first, that the search bar works perfectly, and the anonymous function inside both of them is nearly identical, and like I said, the filtering works perfectly if you try it after the initial load. The second is that the same problem occurs replacing .change(anonymous function) with .on("change",anonymous function)
Any help or advice would be greatly appreciated. Thanks.
I agree with Fernando Urban's answer, but it doesn't actually explain what's going on.
You've created a handler attached to an HTML element (id="classFilter") which causes part of the HTML to be rewritten. I suspect that the handler overwrites the HTML which contains the element with the handler on it. So after this the user is clicking on a new HTML element, which looks like the old one but doesn't have a handler.
There are two ways round this. You could add code inside the handler which adds the handler to the new element which has just been created. In this case, that would mean making the handler a named function which refers to itself. Or (the easier way) you could do what Fernando did. If you do this, the event handler is attached to the body, but it only responds to clicks on the #classFilter element inside the body. In other words, when the user clicks anywhere on the body, jQuery checks whether the click happened on a body #classFilter element. This way, it doesn't matter whether the #classFilter existed when the handler was set. See "Direct and delegated events" in jQuery docs for .on method.
Try to use some reference like 'body' in the event listeners inside your DOM like:
$('body').on('click','.articleButton', function() {
//Do your stuff...
})
$('body').on('click','#classFilter', function() {
//Do your stuff...
})
$('body').on('keypress','#searchbox', function() {
//Do your stuff...
})
$('body').on('click','#logo', function() {
//Do your stuff...
})
This will work that you can fire it more than once.
i have script like this
function manualSeat(){
$('.dimmed').show();
$("#petaKursi").load('url');
$('#wagonCode').val('');
$('#wagonNumber').val('');
$('#selSeats').val('');
selectedGerbong = '';
selectedSeats = Array();
$('#manualSeatMap').show();
$('.dimmed').hide();
}
that code above doesn't work maybe because code doesn't wait until load syntax finish loading,..(maybe)
what i want to ask is,how to make my $('.dimmed')
works like loading that start when begin(show) loading and stop when loading finish(hide)
what i want is like this::
page load(with every div)=>click a button=>load a page to div(when loading,showLoader),when finish loading (hideLoader)
try this:
var dimmed = $('.dimmed');
var showLoader = function () {
dimmed.fadeIn();
};
var hideLoader = function () {
dimmed.fadeOut();
};
document.addEventListener('DOMContentLoaded', showLoader);
window.onload = hideLoader;
You can call showLoader and hideLoader methods whenever you want to show or hide the loader element.
thanks to Rayon Dabre
what i actually want is like this
function manualSeat(){
dimmed.fadeIn();
$("#petaKursi").load('blablabla', function() {
dimmed.fadeOut();
});
$('#wagonCode').val('');
$('#wagonNumber').val('');
$('#selSeats').val('');
selectedGerbong = '';
selectedSeats = Array();
$('#manualSeatMap').fadeIn();
}
The best way to do what you want is to use AjaxStart and AjaxStop function. This way you will fire when the Ajax call (.load is one of them) it will perform some actions.
So in your case:
$(document).ajaxStart(function (){
//I begin the ajax call so I show the layer
$('.dimmed').show();
//you can also do other stuffs like changing the tab title
document.title = 'loading...';
}).ajaxStop(function (){
//The ajax loading has ended
$('.dimmed').hide();
document.title = 'page';
});
I'd go for an ID for the layer that you use while loading to identify it.
If you want to fire this event only for some ajax call and not for other add the
global: false
attribute to that specific ajax call.
After returning to main content by ajax load, function onload didn't run.
I can understand why, but how can I make it run in that condition?
<script type="text/javascript">
onload = function() {
if (!document.getElementsByTagName || !document.createTextNode) return;
var rows = document.getElementById('chat').getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
$("#chat_main").load("chat", {
m: this.id,
ajax: 1 //here we are loading another page
});
}
}
}
</script>
<script>
function return_to_main() {
$("#chat_main").load("chat", {
ajax: 1 //here we trying to load back main page
});
}
</script>
P.S. return_to_main() is binded on input type="button"
You are binding to the window.onload call. It does not magically get called every time the page content is updated. It is only called once. You need to call a function every time you want the code to run. So when the Ajax call is complete, you would been to trigger it.
BUT You are using jQuery so use it.
There is no reason why you would need to bind to every row on the table. Use event delegation. Now when the content changes, you will still have the events bound.
$( function () { //document ready
var chatMain = $("#chat_main");
chatMain.on("click", "table tbody tr", function () { //listen for clicks on table row
chatMain.load("chat",
{
m: this.id,
ajax: 1 //here we are loading another page
}
);
});
});
Call your function after the request:
$("#chat_main").load("chat", {
ajax: 1 //here we trying to load back main page
}).done(onload); // <--
If .load does not produce a promise use:
$("#chat_main").load("chat", {
ajax: 1 //here we trying to load back main page
}, onload); // <--
I have a web application with a medium amount of ajax requests.
I load all jquery and jquery widgets on head then i load my base.js before close body tag.
function baseScripts() {
$(".open-dialog").click(function (event) {
event.preventDefault();
event.stopPropagation();
alert("Opening dialog");
href = $().buildUrl($(this).attr("href"), "&isAjax=true");
$().createDialog(href, "Window Title");
return false;
});
$("input:hidden.select").each(function () {
var element = $(this);
if (!($("#s2id_" + element.attr("id")).length)) {
$(element).select2({
// select2 properties...
});
}
});
}
}
SCRIPT BLOCK TO LOAD BASE SCRIPTS ON EVERY AJAX REQUEST
$(document).ajaxComplete(baseScripts);
The problem is after every ajax request the base scripts its called again and them opening dialog multiple times and attaching select2 multiples times too.
How i can detect if widget is already attached into element or class?
Execute scripts on every ajax request (like i did) its a bad pratice?
It doesn't make sense that you will want to re-bind the click event and select2 on ajaxComplete. They should be a one-time binding, in which case, you can just do:
$(document).ready(function(){
baseScripts();
function baseScripts() {
$(".open-dialog").click(function (event) {
event.preventDefault();
event.stopPropagation();
alert("Opening dialog");
href = $().buildUrl($(this).attr("href"), "&isAjax=true");
$().createDialog(href, "Window Title");
return false;
});
$("input:hidden.select").each(function () {
var element = $(this);
if (!($("#s2id_" + element.attr("id")).length)) {
$(element).select2({
// select2 properties...
});
}
});
}
});