Pulling DOM content as jQuery object from $.get() - javascript

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();
});

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

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

jQuery AJAX : How to query an returned HTML document

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.

backbone model fetch JSON element by ID

I am using backbone for the first time and I am really struggling to get it to function correctly with a JSON data file.
I have a model Like so:
window.Test = Backbone.Model.extend({
defaults: {
id: null,
name: null,
},
url: function() {
return 'json/test.json/this.id';
},
initialize: function(){
}
});
When a test item is clicked I then try to bring up the details of the pacific model that was clicked by doing
testDetails: function (id) {
var test = new Test();
test.id = id;
test.fetch({ success: function(data) { alert(JSON.stringify(data))}});
},
However this does not work, I am unable to correctly say "get the JSON element with the passed ID"
Can anyone please show me how to correctly structure the models URL to pull the element with the ID.
Thanks
The problem here is that you're treating your JSON data file like a call to a server. That won't work and it's the reason you're getting a 404. If you're accessing a file locally, you have to load the file first. You can do this with jQuery using the .getJSON() method, or if the file's static, just load it into memory with a script block (though you'll probably need to assign a var in the file). Most likely, you'll use jQuery. An example of this can be found here:
Using Jquery to get JSON objects from local file.
If this is an array of JSON, you can load the array into a collection, and use the "at" method to access the particular element by id. If it's entirely JSON, you'll have to create a custom parser.
your url is incorrect for one. you are returning the literal string 'this.id'. you probably want to do something more along the lines of
url: function () {
return 'json/test.json/' + this.id;
}
I would start by fixing your url function:
url: function() {
return 'json/test.json/' + this.get('id');
}
The way you have it now, every fetch request, regardless of the model's id, is going to /json/test.json/test.id

Categories

Resources