how to append after load jquery - javascript

I already have some data in the elements i just want to load and append something more,
I want to load and append on each element that has the atribute data-load.
I was doing this but isn't working. Can someone help me on this, thanks.
$(function(){
$("[data-load]").each(function(index){
var $tmp = $('<div>');
var valueData = $(this).data("load")
$tmp.load(valueData);
$(this).append($tmp.html());
});
})

load() is a shortcut convenience method for $.ajax().
AJAX is asynchronous so the http request won't have completed at the time when you are trying to get the returned html from inside $tmp
You need to use the complete callback of load() to do anything within the returned result
To continue using load() method Try:
$("[data-load]").each(function (index) {
var $tmp = $('<div>'),
$el = $(this);
var valueData = $(this).data("load")
$tmp.load(valueData, function () {
/* the ajax has completed here */
$el.append($tmp.html());
});
});
Another shortcut method of $.ajax is $.get which I think would make this code more readable and a little shorter by not needing to create a temporary storage element
$("[data-load]").each(function (index) {
var $el = $(this);
$.get($el.data("load"), function(response){
$el.append(response);
});
});
Both solutions assume that data-load attribute is a valid url that returns the html expected.

Related

Extract piece of ajax request using jquery get

I'm struggling to get this get request to cooperate. I would like to begin by saying that the PHP side flawlessly. I am now trying to use ajax and jQuery to make it look smooth.
Here is the js:
$(".controls a").click(function(e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
$(".schedule").fadeOut(200, function() {
$(this).html(data).fadeIn(200);
});
});
});
$(this).attr("href") refers to a URL that is passed in order to get information from a MySQL database (e.g. hours.php?week=2014-08-11). The value passed in week is updated via PHP every time a link is clicked.
Here is what I get from console.log(data) http://pastebin.com/bGpfjq6r
I've tried converting data (raw HTML) into a jQuery object by doing the following:
var $data = $.parseHTML(data);
However, this just coverts the HTML into an array. I can perform a find for the element:
console.log($($data).find(".schedule"));
but when I view the output of this the context is undefined.
I also tried the accepted answer in this question Extract part of HTML document in jQuery with no avail:
var foo = $(".schedule", $data);
console.log(foo);
This still has an undefined context.
Ideally, I want to grab just the information in .section and replacing the current in .section with the information captured from the GET request. .section is part of the document as well as what is returned from the request.
There are no errors in the console. jQuery version is 1.11.1.
My apologies if the question is poorly written. I tried to write it in a general way so it may apply to other people too. Let me know if you need additional information.
Try using jQuery filter() function.
$(".controls a").click(function(e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
$(".schedule").fadeOut(200, function() {
// apply filter function here to find new schedule div
var newSchedule = $(data).filter(".schedule").eq(0).html();
$(this).html(newSchedule).fadeIn(200);
});
});
});
Try wrapping the response so you can parse it...
$(document).ready(function() {
// Create named function to Initialize the on click event capture
function initAJAX() {
$(".controls a").click(function(e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
var response = $('<div>' + data + '</div>');
var contents = response.find('.schedule').html()
$(".schedule").fadeOut(200, function() {
$(this).html(contents).fadeIn(200);
// After we get the content updated, we have to reinitialize those new anchors
initAJAX();
});
});
});
}
// We have to call this once to start or nothing will happen
initAJAX();
});

jQuery: How to find current object in Post callback data?

I have an ajax post function:
$(".button").click(function(){
var postData = ..some data..
var targetDiv = $(this).closest(".someDiv");
$.post(doucemnt.location, postData, function(data) {
content = ... How to find targetDiv inside data here? ..
targetDiv.html(content);
});
});
The data returned from post will be the whole webpage, and I need to filter it and only get the div I want to refresh. I do not want to use any selectors by ID or class, because there are many copies of the "someDiv" and "button" inside each div, so I want to just get the div object of currently clicked button and search for it in callback data.
is that possible?
I'm not sure I fully understand your question, so forgive me if I'm way off.
I think (if nothing else) this might help give you some ideas. I will parse through the response data looking for a specific 'hook'. Then return just that chunk of data...
JavaScript:
$('.button').click(function (event) {
// This would be your (real) ajax call.
doAjaxPost('www.location.com', postData, function (response) {
var $refresh = $($.parseHTML(response)).filter('#refresh');
$('#content').html($refresh);
});
});
JSFiddle

jQuery run another Ajax after first Ajax callback

I have the following code which loads via ajax contents to be appended:
$.get('http://mydomain.com/ajax1.php/', function(data){
var data_one = $(data).find('#ajax_editor_suggestion_container');
$('.ajax_editor_selection_container').append(data_one);
});
$.get('http://mydomain.com/ajax2.php/', function(data){
var data_one = $(data).find('#ajax_editor_suggestion_container');
$('.ajax_editor_selection_container').append(data_one);
});
My objective is to have the contents of ajax1.php appended first and then contents of ajax2.php appended after that. However sometimes the contents of ajax2.php gets loaded before that of ajax1.php and messes up the appended order.
So my question is, how do I ensure that the contents of ajax2.php are always appended after the contents of ajax1.php?
I'm using $.get() because it's easier for me but I'm open to any other jQuery ajax methods.
Thanks
I would use $.when:
$.when(
$.get('http://mydomain.com/ajax1.php/'),
$.get('http://mydomain.com/ajax2.php/')
).done(function (response1, response2) {
var data_one = $(response1).find('#ajax_editor_suggestion_container');
var data_two = $(response2).find('#ajax_editor_suggestion_container');
$('.ajax_editor_selection_container').append(data_one).append(data_two);
});
That will run the ajax requests at the same time, but won't call the callback until both have finished.

How to traverse with selectors in Jquery a callback data from a post-function like a document

How can I perform with JQuery traversing a callback data coming from a post ajax like a document:
$.post(URL,function(data){
alert($(data+'> div#xy').html(););
})
You need to create jQuery object from "data" by doing
var myData = $(data);
then you can simply use
var whatIWantToSelect = myData.find('enter selector here');
to find whatever you need

Translating ajax output with jQuery

I'm trying to translate some phrases with jQuery. This code mostly works great:
changeText = function(text, newText){
var currentText = $('span.example').html();
$('span.example').html(currentText.replace(text,newText)); };
window.setTimeout(function(){changeText("TranslateMe", "Translation")}, 0000);
However, it's mostly useless when you wait for ajax generated results. To clarify - this is a search script with the following procedure:
When you click Search, you get a part of the page loaded "normally". I can change these text strings without any problems.
Afterwards there are results loaded dynamically through ajax I guess and there are div "blocks" getting loaded one after another. These phrases don't get translated.
A workaround is to wait for some time until everything gets loaded and then it does work for some parts. E. g.:
window.setTimeout(function(){changeText("TranslateMe", "Translation")}, 20000);
However, that's not a good solution, because users see untranslated strings that way for some time.
Therefore, I'm looking for a solution that would change strings as they get displayed. Is there a way to do that?
Thanks in advance!
EDIT:
Trying charlie's approach:
<script>
changeText = function(text, newText, $el) {
$el.html(function(i, currentText){
return currentText.replace(text, newText);
});
};
$(function(){
changeText(text, newText,$('span.example'));
});
$.ajax({
success:function(data){
var $changeEl=$(data).find('span.example');
changeText(text, newText,$changeEl);
var currentText = $('span.example').html();
$('span.example').html(currentText.replace(TranslateMe,Translation));
};
})
})
</script>
Your best/cleanest approach would be to add a callback from where the AJAX Call is being made and the content has been inserted in the divs.
If that is not possible for you there might be a possibility for you to get a callback if the DOM changes as asked here and here
I agree with Tyron that if you can, you should add or modify the callback function to the AJAX calls.
as for detecting the changes and translating without access to the ajax. something like this might help.
var c = document.getElementById('[ID OF CONTAINER FOR UNTRANSLATED BLOCKS]');
c.__appendChild = c.appendChild;
//this function catches the element before it is appended
c.appendChild = function(){
//this applies the change
c.__appendChild.apply(c, arguments);
var newBlock = $(c).children().last();
//this hides the newly added block
newBlock.hide();
// now perform your translations on the newBlock contents
//here
// and then make the block visible again
newBlock.show();
};
If you change the function to add a context argument you could do something like:
changeText = function(text, newText, $el) {
/* html method allows for function as argument to modify element*/
$el.html(function(i, currentText){
return currentText.replace(text, newText);
});
};
Then on page load:
$(function(){
changeText( text, newText,$('span.example'));
});
And in AJAX success look for the new elements and modify them:
$.ajax({
success:function(data){
var $changeEl=$(data).find('span.example');
changeText( text, newText,$changeEl);
/* your code that inserts the new html here*/
})
})

Categories

Resources