I'm trying to implement the following code in a html document:
$(function () {
$.ajax({
type: "GET",
url: "/projects/img/Bathurst/PhotoGallery.xml", // location of your gallery's xml file
dataType: "xml",
success: function(xml) {
$(xml).find('img').each(function() {
var location = '/projects/img/Bathurst/'; // relative path to the directory that holds your images
var url = $(this).attr('src');
var alt = $(this).attr('alt');
$('<li></li>').html('<img class="thumb" src="'+location+''+url+'" alt="'+alt+'" title="'+alt+'" />').appendTo('#gallery-ul');
});
$('<script type="text/javascript"></script>').html('Shadowbox.clearCache(); Shadowbox.setup();').appendTo('#photo-gallery');
}
});
});
The code works perfectly when I use it in an external .js file, but I cant get it working when i implement it, it just renders with error in the code.
II'm I missing something and dos anyone have a suggestion to this? The reason why I need to implement it, in case some one wonderes, is that I'm building a custom webapp and the line "/projects/img/Bathurst/PhotoGallery.xml" and "/projects/img/Bathurst/" is dynamic variables.
All answers are very much appreciated! :)
The problematic line ($('<script type="text/javascript">...) is a convluted and unnecessarily complicated way to run two lines of Javascript.
You should replace it with simple method calls. (Shadowbox.clearCache(); Shadowbox.setup();)
You can't have a </script> inside a script.
Change
$('<script type="text/javascript"></script>')
to
$('<script type="text/javascript"><\/script>')
Related
I'm having an issue with sending some HTML code using AJAX please see my code below
<iframe src="http://www.w3schools.com" width="10" height="10" id="awc_frame"></iframe>
<script>var iframe = document.getElementById("awc_frame");</script>
Here is the AJAX code below
<script>
$.ajax({
type: "POST",
url: "mobileView.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
})
</script>
The code isn't sending the variable to the PHP file. Looking into the Network side of things it sends text ie if I put "" around iframe it sends this code
"val = iframe" but not the actual code within the iframe. The "var iframe"does work and pulls back the HTML code of the iframe
Please tell me what I'm doing wrongly.
Thanks in advance.
EDIT: I'm sorry. It's not the HTML code within the iFrame I need to send, It's the entire iFrame code I need to send.
Another Edit: What I'm trying to accomplish when a visitor from my company goes to my website I would like Javascript or Jquery to load an internal website from the visitors computer and then have all of the code from that website that's on the client's end to be sent to a Server which will store the entire iFrame code in a database.
This would send the entire html inside the iframe.
var iframe = $('#awc_frame').html();
First of all, var iframe does not contain HTML of the iframe element - it contains a DOM Node, which is kind of a wrapper around the iframe element (it contains various properties of that element, including the HTML).
Next thing, you probably want to wait for the iframe to completely load all the contents, so you'll have to bind to the load event of it.
Something like this should work:
var $iframe = $("#awc_frame");
$iframe.on("load", function () {
var iframeHTML = $iframe[0].contentWindow.document.body.innerHTML;
// jQuery alternative
var iframeHTML = $iframe.contents().find("body").html();
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: iframeHTML
},
success: function(data){
console.log(data);
}
});
});
Super important thing in this example
Just one more thing - please note that for websites outside of your own domain, this code won't work (due to Same Origin Policy). Any other code won't work too.
Since javascript has problems with getting the HTML from a cross-domain iframe, you can't do this across domains. However, why not just send the iframe's src attribute to the PHP page, and then just use file_get_contents to get the HTML, and then store that? Problem solved:
Javascript:
var iframe = $('#awc_frame').prop('src');
$.ajax({
type: "POST",
url: "posttest.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
});
PHP:
$html = file_get_contents($_POST['val']);
what are you trying to do?
var iframe = document.getElementById("awc_frame");
above code is an javascript object of your iframe which contains a lot of properties.. since you are using jQuery, you could get that with:
var iframe = $('#awc_frame');
keep in mind that above code is the element it self in jquery object format you could get element object like this:
var iframe = $('#awc_frame')[0];
** you're doing something wrong.
if you're trying to get iframe HTML content:
var iframe_contents = $("#awc_frame").contents();
if you explain more about what you are trying to do, i can update my answer to suit you.
* UPDATE *
considering what you are trying to do..
Method #1: (Easy Way)
you could use php to fetch content of the website you need:
<?php
$contents = file_get_contents('http://www.w3schools.com');
// Saving $contents to database...
?>
Method #2: (Hard Way)
as #mdziekon said, you first should wait until your iframe gets loaded then:
var iframe = $("#awc_frame");
iframe.on("load", function () {
var contents = $(this)[0].innerHTML;
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: contents
},
success: function(data){
console.log(data);
}
});
});
hope it solves your problem
I have some errors in my extension. I have this code that do a find() on an external page:
$.ajax({
url: 'http://www.subspedia.tv/traduzioni.php',
success: function(data) {
$(data).find('.itemListaSerie').each(function() {
console.log($(this).attr('title'));
});
}
});
The find function work correctly but after the result I have a lot of errors that say "File not found" on all images in the page that I'm doing the request.
The screen show my result:
You need to post process the relate links like immagini/serie/covers/33.png for each of the images, and convert them into something like
http://www.subspedia.tv/immagini/serie/covers/33.png
instead of using it as is
EDIT:
The images loaded are probably due to the $(data). If you need only the titles, then you should replace the src of all the tags before $(data)
success: function(data) {
var strippedData = data.replace(/src='(?:[^'\/]*\/)*([^']+)'/g, "");
$(strippedData).find('.itemListaSerie').each(function() {
console.log($(this).attr('title'));
});
Credit to #Gumbo for his answer on regex for matching src. Note, this will remove all src attributes in the page
After your success function, using $(data) you create an element that contain all the html from http://www.subspedia.tv/traduzioni.php so, the document is looking for all the script, css and the images included in that page.
try to replace all the img as words in data as string and then call $(data).find....
Hope this helps you! Anche se mi sarei spiegato meglio in Italiano ;)
I have some working JS code which I put on the sections of my create and edit views, and it's working fine.
However, when I attempted to move the code to a separate JS file, the code would no longer call the controller action.
Here the JS code:
<g:javascript>
$(document).ready(function(){
<g:remoteFunction controller="project" action="ajaxGetClient" onSuccess="updateClient(data)"/>
});
function updateClient(data){
var element = $("#project\\.client");
element.empty();
element.val(data.name);
}
</g:javascript>
Here's the controller action:
def ajaxGetClient = {
if(!params.id){
params.id = Project.find("FROM Project ORDER BY id").id
}
def projectInstance = Project.get(params.id)
render projectInstance?.client as JSON
}
And here's the GSP code:
<g:textField name="project.client" id="project.client" maxlength="9" required="" disabled=""/>
<g:select id="project" name="project.id" from="${myPackage.Project.list()}" optionKey="id" required="" value="${productInstance?.project?.id}" class="many-to-one"
onchange="${
remoteFunction(
controller: 'project',
action: 'ajaxGetClient',
onSuccess: 'updateClient(data)',
params: '\'id=\' + this.value'
)}"
/>
I added a resource to ApplicationResources.groovy and changed the above JS code to this:
<g:javascript library="updateclient"/>
I simply copy/pasted the code into a JS file and then got a message:
Uncaught SyntaxError: Unexpected token <
which I understood came from it not recognizing the GSP syntax, so I tried some AJAX, which I'm pretty unexperienced at:
$(document).ready(function(){
$.ajax({
type: 'POST',
url: "${remoteFunction(controller:'project', action:'ajaxGetClient', onSuccess:'updateClient(data)')}"
});
});
Here's what I'm getting from the browser console:
http://localhost:8080/MyApp/product/$%7BremoteFunction(controller:'project',%20action:'ajaxGetClient',%20onSuccess:'updateClient(data)')%7D 404 (Not Found)
Quite frankly, I'm at a loss right now. Any help would be appreciated.
The reason for this is that Javascript (.js) and other non GSP (.gsp) files aren't parsed through the Groovy server pages engine. Thus, tag libraries such as the or ${g.remoteFunction} aren't parsed.
There are several ways to accomplish this however.
One is to keep the code in your GSP and not externalize it into javascript files.
Second is to move your code into javascript files but have configuration values in your GSP file. Here is a very simple example of using the message taglib:
// inside the .js file
function myFunction() {
console.log("I would use this value: "+_VALUE_FROM_GSP);
}
<script type="text/javascript">
// inside the .gsp file
var _VALUE_FROM_GSP = "${message(code: 'just.an.example')";
</script>
Finally, there plugins (listed below) that allows you specify some resources (javascript files in your case) to be parsed through the Groovy Server Pages engine.
GSP-arse plugin and GSP Resources
I'll be answering my own question here, since the bulk of it came from valuable advice from a friend of mine, but Joshua's answer was also very important, so I ended up combining both of them.
This is how I solved it:
On the GSP:
<script type="text/javascript">
var _URL = '${resource(dir: "")}/project/ajaxGetClient';
</script>
<g:javascript library="updateclient"/>
The reason I'm using the <script> tag is because in order for the _URL variable to become usable across different files, it had to be declared before the file using it. At least that's what this other SO answer said:
Global variables in Javascript across multiple files
Separate JS file:
$(document).ready(function(){
getClientAjax(null);
});
function getClientAjax(id) {
$.ajax({
url: _URL,
type: "POST",
data: { id: id },
success: function(data) {
updateClient(data);
}
});
}
function updateClient(data){
var element = $("#project\\.client");
element.empty();
element.val(data.name);
}
And the controller action remained the same.
At the end, there had to be created another JS function, but I gotta say I'm happy with the result.
Thanks for all the help.
Okay, I'm pulling data from an XML file to populate my elements of my webpage dynamically. My problem is that when I use JQuery .ajax to pull the xml file, it strips my HTML tags.
For example,
Data in XML file:
<transcript><p>Hello, world</p></transcript>
Desired output on webpage:
<p>Hello, world</p>
Actual output:
Hello World
Here is my code inside of my ajax function:
$(xmlData).find('item').each(function() {
var n = $(this).find('transcript').text();
I've tried to use JQuery's '.html()' but it returns null. What is the simplest way I can fix this? Preferably without changing too much of what I've already done.
Thanks in advance.
Using text will strip the tags as you experienced. You can instead use the jQuery children method (reference) on the transcript node to get the HTML. Here is a working example: http://jsfiddle.net/gjwyd/
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/echo/xml/",
dataType: "xml",
data: {
xml: "<transcript><p>Hello, world</p></transcript>"
},
success: function(xml) {
var container = $('#content');
var html = $(xml).find('transcript').children();
container.html(html);
}
});
});
The key is this line:
var html = $(xml).find('transcript').children();
And being sure to set the dateType as xml.
Issues
When taking HTML from an XML response it may be missing the default styles. For example, a paragraph tag may not have display: block. Resetting the styles may be one way around this issue. A more correct and probably easier way would be to put the HTML content inside of CDATA within the XML as one of the other commenters suggested.
http://jsfiddle.net/tZJQp/
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/echo/xml/",
dataType: "xml",
data: {
xml: "<transcript><![CDATA[<p>Hello, world</p><p>Bye</p>]]></transcript>"
},
success: function(xml) {
var container = $('#content');
var html = $(xml).find('transcript').text();
container.html(html);
}
});
});
As others note, html won't work on XML.
I'm trying to get some page details (page title, images on the page, etc.) of an arbitrarily entered URL/page. I have a back-end proxy script that I use via an ajax GET in order to return the full HTML of the remote page. Once I get the ajax response back, I'm trying to run several jQuery selectors on it to extract the page details. Here's the general idea:
$.ajax({
type: "GET",
url: base_url + "/Services/Proxy.aspx?url=" + url,
success: function (data) {
//data is now the full html string contained at the url
//generally works for images
var potential_images = $("img", data);
//doesn't seem to work even if there is a title in the HTML string
var name = $(data).filter("title").first().text();
var description = $(data).filter("meta[name='description']").attr("content");
}
});
Sometimes using $("selector", data) seems to work while other times $(data).filter("selector") seems to work. Sometimes, neither works. When I just inspect the contents of $(data), it seems that some nodes make it through, but some just disappear. Does anyone know a consistent way to run selectors on a full HTML string?
Your question is kind of vague, especially w/r/t what input causes what code to fail, and how. It could be malformed HTML that's mucking things up - but I can only guess.
That said, your best bet is to work with $(data) rather than data:
$.ajax({
type: "GET",
url: base_url + "/Services/Proxy.aspx?url=" + url,
success: function(data) {
var $data = $(data);
//data is now the full html string contained at the url
//generally works for images
var potential_images = $("img", $data);
//doesn't seem to work even if there is a title in the HTML string
var name = $data.filter("title").first().text();
var description = $data.filter("meta[name='description']").attr("content");
}
});