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
Related
I have a view page where i have an object inside a div like :-
<div id="booking_id"><%#booking_id%></div>
I want to get the value of #booking_id to be passed in AJAX data params and my ajax function is like this :
<script type="text/javascript">
$(document).ready(function(){
$("#selecthotel2").change(function(){
var room = $(this).children(":selected").val();
var params = $('#booking_id').filter('#booking_id').val();
$.ajax({
url: "/rooms/assign_room",
data: {
room,
params
}
})
});
});
</script>
But i am not getting the #booking_id value to be passed to another action.
I think i am going somewhat wrong in the ajax syntax,kindly help.
change
$('#booking_id').filter('#booking_id').val();
to simply
$('#booking_id').text();
Currently your code is trying to look inside $("#booking_id") for another element with the same ID, instead of taking the value of $('#booking_id') itself.
Also since $("#booking_id") is a div and not an input, I think you need to get the contents using text(), not val().
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();
});
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();
});
My question is as follows: I have started using the $.ajax function with jQuery and I am wondering how I work with the return of an HTML page. The request completes and I can console.log the returned HTML page however I would now like to select a single element from that page. I have had several attempts which included:
$(data).find('p');
$('button').click(function() {
$.ajax(funciton() {
dataType: 'html',.
url: 'localhost/sw',
success: function(data) {
// This is where I would like to select a element or node from the complete
// returned html document
});
});
I know i can simply use .load() which you can provide select criteria but .ajax is the root function to begin with and I would like to learn that way as well for more complicated queries. Second half of this would be should I not be trying to select elements this way and just serve up json or a single key phrase instead of the entire html page? All help is appreciated.
Just pass the returned HTML to jQuery, and treat it like a regular jQuery collection:
$.ajax({
dataType: 'html',.
url: 'localhost/sw',
success: function (html) {
var paragraphs = $(html).find('p');
// Manipulate `paragraphs` however you like. For example:
$(document.body).append( paragraphs );
}
});
Joseph's answer above is correct if you just want to get the objects.But if you want to load the content of that element, you may change this:
var paragraphs = $(html).find('p');
to
var paragraphs = $(html).find('p').html();
Hope it helps.
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*/
})
})