jQuery GET html as traversable jQuery object - ajax

This is a super simple question that I just can't seem to find a good answer too.
$.get('/myurl.html', function(response){
console.log(response); //works!
console.log( $(response).find('#element').text() ); //null :(
}, 'html');
I am just trying to traverse my the html response. So far the only thing I can think of that would works is to regex to inside the body tags, and use that as a string to create my traversable jQuery object. But that just seems stupid. Anyone care to point out the right way to do this?
Maybe its my html?
<html>
<head>
<title>Center</title>
</head>
<body>
<!-- tons-o-stuff -->
</body>
</html>
This also works fine but will not suit my needs:
$('#myelem').load('/myurl.html #element');

It fails because it doesn't like <html> and <body>.
Using the method described here: A JavaScript parser for DOM
$.get('/myurl.html', function(response){
var doc = document.createElement('html');
doc.innerHTML = response;
console.log( $("#element", doc).text() );
}, 'html');
I think the above should work.

When jQuery parses HTML it will normally strip out the html and body tags, so if the element you are searching for is at the top level of your document structure once the html and body tags have been removed then the find function may not be able to locate the element you're searching for.
See this question for further info - Using jQuery to search a string of HTML

Try this:
$("#element", $(response)).text()
This searches for the element ID in the $(response) treating $(response) as a DOM object.

Maybe I'm misunderstanding something, but
.find('#element')
matches elements with an ID of "element," like
<p id="element">
Since I don't see the "tons of stuff" HTML I don't understand what elements you're trying to find.

Related

I need a clue about what code goes where for a simple AJAX query

I'm just blundering into AJAX, and I swear I'll actually learn my way around it real soon now, but all I need at the moment is to get the inner browser height, so I can ask the Google Maps Engine for a map of the appropriate height. (I'm actually making that request via the Google Maps plugin under Joomla. If I could somehow make that request on the client side, then I might not really have to mess with AJAX, but this would still be a good introductory exercize for me.)
I'm trying to grasp the basic AJAX setup by putting together a working minimal document incorporating code from the first answer at how to get screen width through php?. I realize that example is asking for a different attribute than I'll be asking for, but I'm just keeping the code as close to the original as possible.
I'm not totally clear on what code goes where, but apparently it is not this, at http://allbluesdance.com/testajax.php :
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Test Ajax</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
var width = $(window).width();
//This is ajax code which will send width to your php page in the screenWidth variable
$.ajax({
url: "http://allbluesdance.com/testajax.php", //this will be your php page
data : {screenwidth:width}
}).done(function() {
$(this).addClass("done");
});
</script>
(Yeah, it's running)
<!-- example.php code is here : -->
<?php
echo $width = $_REQUEST['screenwidth'];
?>
</body>
</html>
So unless I've made a dumb syntax error I could use a clue.
Thanks,
Drew
I think you need to specify how AJAX gets the data, either through GET or POST. I Have been using this snippet and it works for me.
// fire off the request
var request = $.ajax({
url: "/list/server.php",
type: "POST",
data: send_data
});
// callback handler that will be called on success
request.done(function (response){
// log a message to the console
console.log(response);
});

Accessing Oracle ATG variables with Javascript

I am trying to pass the contents of a bean to javascript so that I can parse it and create a JSON object... (Yes I am still on ATG 9.1). However I am having trouble getting from serverside to client side.... I am new with this stuff and would appreciate any explanation as documentation on this is scarce and not helpful.
<dsp:tomap var="cartMap" bean="MyShoppingCartModifier.order" recursive="true"/>
<script>
var myCartMap = "${cartMap}";
//Logic (easy)
</script>
Doing this generates an "Uncaught SyntaxError: Unexpected token ILLEGAL" on my browser (Chrome)
Any wisdom will greatly help me in my quest in learning this stuff.
The problem is your usage of the tomap tag. You can't just pass in an entire tomap'd object because the tomap tag isn't going to create a nice, parsable json object.
You should either:
1) Format the json yourself right within your tags. Choose only the values that you want from the order.
<script>
var myCart = {
total : '<dsp:valueof bean="MyShoppingCartModifier.order.priceInfo.total">'
...
}
// Then use myCart for something here
</script>
or 2) There's a little known JSP to JSON library found here, http://json-taglib.sourceforge.net, that is very useful. To use that, you'd create a separate page, something like orderJSON.jspf, that is used to generate a pure json object from your order. Then in the page that you require this js, you can do:
<script>
var myCart = <%# include file="/path/to/orderJSON.jspf" %>
// Then use myCart for something here.
</script>

Reloading everything but one div on a web page

I'm trying to set up a basic web page, and it has a small music player on it (niftyPlayer). The people I'm doing this for want the player in the footer, and to continue playing through a song when the user navigates to a different part of the site.
Is there anyway I can do this without using frames? There are some tutorials around on changing part of a page using ajax and innerHTML, but I'm having trouble wrapping my head aroung getting everything BUT the music player to reload.
Thank you in advance,
--Adam
Wrap the content in a div, and wrap the player in a separate div. Load the content into the content div.
You'd have something like this:
<div id='content'>
</div>
<div id='player'>
</div>
If you're using a framework, this is easy: $('#content').html(newContent).
EDIT:
This syntax works with jQuery and ender.js. I prefer ender, but to each his own. I think MooTools is similar, but it's been a while since I used it.
Code for the ajax:
$.ajax({
'method': 'get',
'url': '/newContentUrl',
'success': function (data) {
// do something with the data here
}
});
You might need to declare what type of data you're expecting. I usually send json and then create the DOM elements in the browser.
EDIT:
You didn't mention your webserver/server-side scripting language, so I can't give any code examples for the server-side stuff. It's pretty simple most of time. You just need to decide on a format (again, I highly recommend JSON, as it's native to JS).
I suppose what you could do is have to div's.. one for your footer with the player in it and one with everything else; lets call it the 'container', both of course within your body. Then upon navigating in the site, just have the click reload the page's content within the container with a ajax call:
$('a').click(function(){
var page = $(this).attr('page');
// Using the href attribute will make the page reload, so just make a custom one named 'page'
$('#container').load(page);
});
HTML
<a page="page.php">Test</a>
The problem you then face though, is that you wouldnt really be reloading a page, so the URL also doesnt get update; but you can also fix this with some javascript, and use hashtags to load specific content in the container.
Use jQuery like this:
<script>
$("#generate").click(function(){
$("#content").load("script.php");
});
</script>
<div id="content">Content</div>
<input type="submit" id="generate" value="Generate!">
<div id="player">...player code...</div>
What you're looking for is called the 'single page interface' pattern. It's pretty common among sites like Facebook, where things like chat are required to be persistent across various pages. To be honest, it's kind of hard to program something like this yourself - so I would recommend standing on top of an existing framework that does some of the leg work for you. I've had success using backbone.js with this pattern:
http://andyet.net/blog/2010/oct/29/building-a-single-page-app-with-backbonejs-undersc/
You can reload desired DIVs via jQuery.ajax() and JSON:
For example:
index.php
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<a href='one.php' class='ajax'>Page 1</a>
<a href='two.php' class='ajax'>Page 2</a>
<div id='player'>Player Code</div>
<div id='workspace'>workspace</div>
one.php
<?php
$arr = array ( "workspace" => "This is Page 1" );
echo json_encode($arr);
?>
two.php
<?php
$arr = array( 'workspace' => "This is Page 2" );
echo json_encode($arr);
?>
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event) {
event.preventDefault();
// load the href attribute of the link that was clicked
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html(snippets[id]);
}
});
});
});

Running a function in a jQuery implicit context

My html document looks like this:
<html>
<head> .. load jquery and other stuff </head>
<body>
<div id="cool_container">
<div class="cool">.. no script friendly markup ..</div>
</div>
<a id="cool_link">Link</a>
<script>
function installStuff(){
$('.cool').coolPlugin();
$('#cool_link').click(function(){
$('#cool_container').load('/anothercooldiv.html');
});
}
$(document).load(function(){ installStuff(); });
</script>
</body>
</html>
Of course, /anothercooldiv.html gives another <div class="cool"> .. etc ...</div> fragment.
So what's the best way to turn the fresh cool div into a coolPlugin without breaking everything (and writing some nasty hacks) ?
It'd would be great to be able to either:
Call installStuff with a default jQuery context '#cool_container', so I could call something like:
$.doThisInContext(function(){installStuff();}, $('#cool_container');
In the load callback.
Or, have an equivalent of 'live' (that would solve the problem of links if cool contains links), but on an element existence, that I could use like that in my function installStuff:
$('.cool').exists(function(what){ what.coolPlugin() };
Then the coolPlugin would be installed on all cool elements now and in the future.
I'd suggest the .livequery() plugin for this still:
$(function() {
$('.cool').livequery(function() {
$(this).coolPlugin();
});
$('#cool_link').click(function(){
$('#cool_container').load('/anothercooldiv.html');
});
});
The important bit:
$('.cool').livequery(function() {
$(this).coolPlugin();
});
Will run for every current and future .cool element as they're added, running the plugin on each.
Applying the plugin to the newly ajax loaded content shouldn't be too tricky:
$('#cool_container').load('/anothercooldiv.html', function() {
$(this).coolPlugin();
});

Ajax append load

it must be jquery
I have file text.html with 6 div in (a,b,c,d,e,f)
In another file i have a div, i like it to populate the content of a+b+c+d+e+f into that single div
I have try .load = but b remplace a
i have try append, but i need a temp var
so now i am stuck
That code get the content from the file textes.html ... div #a and put the content into div #right, but the second libe REMPLACE the content of right a with right b
I like to append the content a + b NOT a over b
$(document).ready(function(){
var temp = load('textes.html #nicolas');
$('#right').append(temp);
var temp = load('textes.html #antoine');
$('#right').append(temp);
.
.
.
.
return false;
});
that code is the idea behind what should work, but i cannot make a ajax .load() to load content into a variable to append the content to the div...
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "textes.html",
cache: false,
success: function(html){
$("#right").append(html);
}
});
});
</script>
That code load the WHOLE html file, i like to get only some selected DIV #
$(document).ready(function(){
$.get("textes.html",function(data){
$("#right").append($("#nicolas",data)).end().append($("#antoine",data));
},'html');
});
I had a similar issue just now and I think I figured out a way to do what we want using the .load() function. It's not pretty but never mind ;)
First off, I added a "TempDiv" to my html with a "visibility:hidden" style.
<div id="TempDiv" style="visibility:hidden"></div>
Then you run the jQuery :
$(document).ready(function(){
$('#TempDiv').load('textes.html #nicolas', function(){
$('#right').append($('#TempDiv').html());
});
});
I'm not sure it's the best way !
PS : That is my first stackoverflow post ;)
try,
$.get('url.php', function(data) {
$("#right").append(data);
});
This sounds like jQuery? Please state what framework you are using since I can't really see any mention of it. Anyway, append should work. Just do something like:
mydiv.append(a.text());
mydiv.append(b.text());
mydiv.append(c.text());
mydiv.append(d.text());
mydiv.append(e.text());
mydiv.append(f.text());
They should all be appended into mydiv.
NOTE: if you also want the html, use the .html() function instead of .text().
JQuery ( http://jquery.com/ ) is a good javascript library that you can use to do an AJAX request to get the other file. See this question for more: Use jQuery to replace XMLHttpRequest

Resources