Why can't I use part of this AJAX response? - javascript

I have a jQuery ajax call:
$.ajax ({
url : 'foo/bar/',
success: function(data) {
console.log(data);
var newHeaderText = $(data).find('#header-text').text();
$("#header-text").text(newHeaderText);
var newContent = $(data).find('#content').html();
console.log(newContent);
$("#content").html(newContent);
}
});
The logged data successfully shows the complete html of the target page.
The header-text section works as expected.
The console.log(newContent), however, returns undefined. Short of posting the entire html of foo/bar/ here, suffice it to say that I am quite sure a div of id content is in data, and that it has many child elements.
Why is my attempt at grabbing the content of one page and plopping it into the content of another page not working. It is especially confusing to me as header-text seems to work just fine.

You could try $.parseHTML instead:
var newContent = $($.parseHTML(data)).find('#content');
If #content is a top-level element, then the above code might still miss it. You could then solve this by first loading the HTML in container, and then find the element in there:
var newContent = $('<div>').append($.parseHTML(data)).find('#content');

Related

Trying to convert jQuery get request into parseable object

I am trying to parse a jQuery get request into an object or some other way of getting a particular div on a page.
Here's my code:
$.get("http://en.wikipedia.org/wiki/Afghanistan", function(response) {
var elements;
elements = $.html(response);
console.log(elements);
});
The only problem is that elements is not HTML to parse. Let's say I want to get a specific div on the response variable - how would I go about doing that? This is with the intention of (eventually, after some processing) copying it to a div on my local page.
Don't worry about cross domain issues - this is for a Phonegap application
Use $.parseHTML() so you can convert that response to a set of DOM nodes and later insert that to the document.
You can do it like this:
$.get("http://en.wikipedia.org/wiki/Afghanistan", function(response) {
var elements;
elements = $.parseHTML(response);
console.log(elements);
var myDiv = $(elements).find('#idForDiv');
});
It sounds like the jQuery load function does exactly what you want. You can specify a selector after the url to load a particular part of the page:
$("#mydiv").load( "http://en.wikipedia.org/wiki/Afghanistan #divonpage");
http://jqapi.com/#p=load
If the response from the server is HTML then you can wrap it in a jQuery object and act upon it.
I would vouch for this approach:
var server_response = '<div style="background-color:yellow;"><div class="find-me">Hello</div></div>';
$('span').html($(server_response).find('.find-me'));
.find-me {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span></span>

getElementById from another page

I am trying to get one div from one webpage URL to another webpage and display in plain text using getElementById without using AJAX or jQuery because I'm going to implement it in FitNesse. Is there a way to pass the URL?
You could load the URL in a hidden iframe.
Then use iframe.contentWindow.document.getElementById($id) as outlined here: How to pick element inside iframe using document.getElementById
Something along the lines of:
<iframe src="urlWithinYourDomain.html" style="display:none"></iframe>
Followed by a function something like:
var divElement = document.getElementById('iframeId').contentWindow.document.getElementById('elementIdOnSourcePage');
document.getElementById('targetParentId').appendChild(divElement);
I'm afraid I can't test this at the moment, so there may be syntax errors, but I think it conveys the idea. It's a bit of a dirty approach, but given your constraints it's the best way I can see to do what you're asking.
On page 1.
<div id="dataDiv">1234</div>
<a id="getData" href="">Page2</a>
<script>
var data = document.getElementById('dataDiv').innerHTML;
//This will get the content from the div above with the id of "dataDiv"
document.getElementById("getData").setAttribute("href","page2.html?var="+data);
//This will set the url of the anchor with the id of "getData" with your url and the passing data.
</script>
And on page 2
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var var1 = getUrlVars()["var"];
This will send the content in your div on page one to page two. the result url on page 1 will be page2.html?var=1234

jQuery: selectors not working over ajax downloaded page

I'm trying to extract an element from an ajax downloaded page to later append it to the DOM. I'm fetching the page like this:
$.ajax({
url: pagePath,
success: function (data) {
//data is correctly shown in debugger, all the elements exist.
var $div = $(data).find("[data-custom-attr]").first();
//$(data) has lenght > 0, however $div has length 0!
//$(data).find("#ajaxpage") also has lenght 0!
},
dataType: "html"
});
This is the fetched page:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="ajaxpage" data-custom-attr="ajaxpage">
<h2>Ajax downloaded page!</h2>
</div>
</body>
</html>
I've tried with a few different selectors and everyone fails. I feel like there must be a really silly mistake somewhere in the code but can't see it.
What is the problem with those selectors?
The reason for this is that jQuery throws away all the nonsense you've given it, and only parses the div with h2:
$("<!DOCTYPE html><html><head></head><body><div id='ajaxpage' data-custom-attr='ajaxpage'><h2>Ajax downloaded page!</h2></div></body></html")
is exactly the same as
$("<div id='ajaxpage' data-custom-attr='ajaxpage'><h2>Ajax downloaded page!</h2></div>")
(jQuery's $("...") doesn't create full documents, it'll only build DOM fragments)
Since the first element is already your div, you cannot find [data-custom-attr] in its subtree, so the result will be []. If you do a find("h2"), that'll work fine, since it's in the subtree of your div, but you can't find the div itself.
var $div = $('<div/>').html(data).find("[data-custom-attr]").first();
Try this:
var $div = $('<div></div>').html(data).find("[data-custom-attr]").first();

Multiple classes map with Jquery and load the content

I have a Div of Class
<div class='navigation five-icons'></div>
and i want to load a URL which returns html inside it, how can i select that div with jquery,
what i have tried is
$('.navigation .five-icons').load('URL');
$('.navigation.five-icons').load('http://www.astuffaday.com/shot/menu.php');
but no use.
I dont know about loading but you can use below code to select more than one class
$('.navigation, .five-icons')
Are you trying to get the data asynchronously?
Use $.post() or $.get()
$.post('filename.php', {'name1':'value1', 'name2':'value2'}, function(result) {
alert(result); // result has the HTML content returned by filename.php
$('#resultDiv').html(result); // resultDiv will have its contents
// Now you need to get only particular div
// You can use 'find()'
// Something like this may help [Have not been tested]
var data = $('result').find('.navigation .five-icons');
alert(data);
})
References
$.ajax()
$.post()
$.get()
$.load()
.find()

Counting classes on another page and displaying them

To save me a lot of work editing a number in when adding a document to a site I decided to use javascript to count the number of elements with a class doc .
I am two main problems:
There is trouble displaying the variable. I initially thought this was because I hadn't added function, however when I tried adding this the variable was still not displayed.
The elements with the class I want to count are on another page and I have no idea how to link to it. For this I have tried var x = $('URL: /*pageURL*/ .doc').length; which hasn't worked.
Essentially I want the total elements with said class name and this to be displayed in a span element.
Currently I have something similar to what's displayed below:
<script>
var Items = $('.doc').length;
document.getElementById("display").innerHTML=Items;
</script>
<span id="display"></span>
Found an example of something similar here where the total numbers of articles are displayed.
Edit:
#ian
This code will be added to the homepage, domain.net/home.html. I want to link to the page containing this documents, domain.net/documents.html. I've seen this done somewhere before and if I remember correctly they used url:domainname.com/count somewhere in their code. Hope this helps.
Here is a jQuery call to retrieve the url "./" (this page) and parse the resulting data for all elements with class "lsep" "$('.lsep', data)". You should get back a number greater than 5 or so if you run this from within your debug console of your browser.
$.get("./", function(data, textStatus, jqXHR)
{
console.log("Instances of class: " + $('.lsep', data).length)
});
One important thing to remember is that you will run into issues if the URL your are trying to call is not in the same origin.
Here's an updated snippet of code to do what you're describing:
$(document).ready(
function ()
{
//var url = "/document.html" //this is what you'd have for url
//var container = $("#display"); //this is what you'd have for container
//var className = '.data'; //this is what you'd have for className
var url = "./"; //the document you want to parse
var container = $("#question-header"); //the container to update
var className = '.lsep'; //the class to search for
$.get(url, function (data, textStatus, jqXHR) {
$(container).html($(className, data).length);
});
}
);
If you run the above code from your browser's debug console it will replace the question header text of "Counting classes on another page and displaying them" with the count of instances the class name ".lsep" is used.
First, you have to wait until the document is ready before manipulating DOM elements, unless your code is placed after the definition of the elements you manipulate, wich is not the case in your example. You can pass a function to the $ and it will run it only when the document is ready.
$(function () {
//html() allows to set the innerHTML property of an element
$('#display').html($('.doc').length);
});
Now, if your elements belongs to another document, that obviously won't work. However, if you have used window.open to open another window wich holds the document that contains the .doc elements, you could put the above script in that page, and rely on window.opener to reference the span in the parent's window.
$('#display', opener.document.body).html($('.doc').length);
Another alternative would be to use ajax to access the content of the other page. Here, data will contain the HTML of the your_other_page.html document, wich you can then manipulate like a DOM structure using jQuery.
$.get('your_other_page.html', function(data) {
$('#display').html($('.doc', data).length);
});

Categories

Resources