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();
});
Related
I've just started to learn jquery&javascript, and in my project I've found this block of code, and I'm wondering what does it mean, some parts are confusing to me, all I've understand so far is that this is triggering on some control change event but how can I know which control and how does this work in fact?
<script type="text/javascript">
$(function () {
$("#MainGroupID").change(function () {
var val = $(this).val();
var subItems="";
$.getJSON("#Url.Action("GetSubgroupByMainGroup", "Article")", {id:val} ,function (data) {
$.each(data,function(index,item){
subItems+="<option value='"+item.Value+"'>"+item.Text+"</option>"
});
$("#SubGroupID").html(subItems)
});
});
});
</script>
Please some explanation line by line I'm trying to understand this stuffs how do they work with code behind etc etc :/
Maybe it's stupid question but .. :/
Thanks guys,
Cheers!
//$(function () {
this part is used to invoke the function when the DOM is ready.
$("#MainGroupID").change
//is a change event - like the value of the input has changed.
var val = $(this).val();
//You are picking up the value of the input
var subItems="";
// you are creating a placeholder variable to hold data
$.getJSON(
//this is a call to get json data.
$.each
//you are now looping through the data obtained from the json call
subItems+="<option value='"+item.Value+"'>"+item.Text+"</option>"
//you are now populating the variable you had set
$("#SubGroupID").html(subItems)
//this places the content of the obtained data and the structure from the placeholder into the div with the id SubGroupID
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.
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
As part of a jQuery plugin, a strange object format is pulled using $.get(), meaning that DOM traversal isn't possible in any of the post-function hooks:
$.get($href)
.done(function(){
$linkClicked.addClass('active')
})
.fail(function(){
$.get(settings.errorUrl, function(){
$('.main-navigation .active').removeClass('active')
})
})
.always(function(data){
// The below line does not work correctly
$(settings.target).hide().html( $(data).children(settings.target).html() ).fadeIn('fast')
})
If somebody could lend a hand, that'd be great. Many thanks.
I guess you can do like this:
$.get('ajax/test.html', function(data) {
var container = $('<div />').html(data);
var contentYouNeed = container.find('#ajaxID').html();
});
As you can see on the document here (
http://api.jquery.com/jQuery.get/), The returned data by
jQuery.get() is a PlainObject or a String.
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
To retrieve the contents from this object, you put this data in a <div> object like this.
var container = $('<div />').html(data);
And you can use find() to get the content.
var contentYouNeed = container.find('#ajaxID').html();
No no no no. You don't use regex for parsing HTML please read this.
Also, to solve you problem use jQuery selectors: $("#yourID").html()
So the response is always one div element? In that case it's just a matter of grabbing the contents of it. No matter what the ID and attributes are.
$.get('ajax/call.php', function(data) {
var contents = $(data).html();
});
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*/
})
})