I'm trying to load a specific javascript function I found inside a webpage using webkit.
but I don't know how to write this javascript (no experience at all using java)
i have the link to the page containing the js functions and I'm able to print out all the content inside. (it contain many java functions)
// this a fake link
http://203.178.105.133:9090/fly/static/js/flightInfo.js
the function I want to call is
function getSysDate() {
$.ajax({
url: ctx + "/common/date",
data: "pattern=yyyy-MM-dd",
dataType: "JSON",
success: function (data) {
/*$("#start").val(data.date);
$("#end").val(data.date);*/
$("#sFltDate").val(data.date);
$("#eFltDate").val(data.date);
}, error: function () {
parent.layer.alert("Server Error.", {
title:'Error',
icon: 5,
btn: ['Close']
});
}
});
}
I tried with the following script but of course not work:
webView.evaluateJavaScript("http://203.178.105.133:9090/fly/static/js/flightInfo.js/getSysDate();", completionHandler: nil)
looking for a tips how to compose this script in order to run the function at that specific page.
Thanks
Related
I'm trying to do a Youtube API and I feel like I got everything working except this gapi and res thing? It says gapi is not defined. How can I make this work?
function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}
$(function() {
$("form").on("submit", function(e) {
e.preventDefault();
// prepare the request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
maxResults: 3,
order: "viewCount",
publishedAfter: "2015-01-01T00:00:00Z"
});
// execute the request
request.execute(function(response) {
var results = response.result;
$("#results").html("");
$.each(results.items, function(index, item) {
$.get("tpl/item.html", function(data) {
$("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}]));
});
});
resetVideoHeight();
});
});
$(window).on("resize", resetVideoHeight);
});
function resetVideoHeight() {
$(".video").css("height", $("#results").width() * 9/16);
}
function init() {
gapi.client.setApiKey("AIzaSyD646m4ZfK5yKBZj9p95LohN-PTUnRHBRY");
gapi.client.load("youtube", "v3", function() {
});
}
gapi is an object created by the Google API javascript library that manages all interactions (i.e. does all the heavy lifting of the requests) for you. If the object is not defined, you may not have included the library itself in your page. Somewhere in your HTML, you'll need a script tag that loads the library located at:
https://apis.google.com/js/client.js
Note that, in loading the library with a script tag, you should also pass it a callback ... this is a function that will be automatically called as soon as the library is done loading. So in your case, your init() method is that callback, and so your script tag would look like this:
<script src="https://apis.google.com/js/client.js?onload=init"></script>
The browser will get the library, load it, then run init() when the library is done loading, and all will be ready for your form to execute when triggered.
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
When I launch the page, I fire up the chrome dev tools and look in the sources window, load my file and I see
Uncaught TypeError: $(...).kendoNotification is not a function
Im trying to modify an existing application ive been given which uses Kendo UI. I just want to add in a notification popup.
Referring to the docs, a common cause of this is not including all required javascript resources, but they all seem to be there. jquery, kendo.all.min and were also using kendo.modernizr
Its obviously its my problem, since all the other kendo widgets work fine.
Im trying to follow this example
http://code.tutsplus.com/tutorials/adding-application-notifications-with-kendo-ui-core--cms-20989
Something is getting initialized correctly, im just not sure where/what it could be.
The page itself is rather large, but the notification is just
<span id="popupNotification"></span>
... more html
<script>
....more stuff
$.ajax({
...
success: function (result) {
var popupNotification = $('#popupNotification').kendoNotification({
appendTo: "#SalesGrid", autoHideAfter: 5000, width: 400
}).data('kendoNotification');
var d = new Date();
popupNotification.show({ time: kendo.toString(d, 'HH:MM:ss.') + kendo.toString(d.getMilliseconds(), "000") }, "time");
}
})
</script>
[update]
I just realized i was trying to show the notification from within an ajax call, so I found a more relevant example here.
[update 2, full source of function being called ]
function postBatch(e) {
//alert('made it');
$.ajax({
url: '#Html.Raw(#Url.Action("SalesAction", "SalesController"))',
data: { batchID: e, status: "POSTED" },
async: false,
dataType: "json",
type: 'POST',
success: function (result) {
var statementBatchDS = $('#SalesGrid').data().kendoGrid.dataSource;
statementBatchDS.data(result.Data);
// *** FAILS HERE *** note: SalesGrid is a KendoUI grid
var popupNotification = $('#popupNotification').kendoNotification({
appendTo: "#SalesGrid", autoHideAfter: 5000, width: 400
}).data('kendoNotification');
var d = new Date();
popupNotification.show('Batch post error, please review', 'error');
}
});
}
Where/which script source within Kendo UI is the KendoNotificaiton widget defined? Im using kendo.all.min.js, so I was assuming that included everything. Yet, when I call the notificaiton show method (see above), the error seems to indicate it cant construct the notification..which leads me to think the source isnt being included, yet the kendo.all.min.js file is clearly being pulled in as I inspect the source in Chrome's dev tools.
So off to Telerik I go, and I read these
http://docs.telerik.com/kendo-ui/intro/installation/what-you-need
http://docs.telerik.com/kendo-ui/intro/supporting/scripts-general
Yet, the "all" version is whats in the reference
http://demos.telerik.com/kendo-ui/notification/index
I had this same problem and solved removing the kendo call from inside the AJAX snippet with a function:
success: function(data){
notify();// here i call a function to send the notification
clean();//another function to clear form data.
},
...
function notify(){
var popupNotification = $("#popupNotification").kendoNotification().data("kendoNotification");
popupNotification.show("Some notification", "success");
}
Turns out it was just a matter of upgrading the version of the Kendo libraries I was using. At least im past the point of the Notification widget not being loaded.
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>')
I'm new to JQuery and web development in general. I'm trying to load some data from an XML file and build an unordered list. I've got that part working, now I'm trying to use the TreeView plugin so I can collapse/expand the data. The data is loaded like this:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "solutions.xml",
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data) {
var xml;
if (typeof data == "string") {
// Work around IE6 lameness
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
list = ""
$(xml).find("Group").each(function() {
group = $(this).attr("name");
list += "<li><span>" + group + "</span><ul>";
$(this).find("Solution").each(function() {
solution = $(this).attr("name");
list += "<li><span>" + solution + "</span></li>";
});
list += "</ul></li>";
});
$("#groups").html(list);
},
error: function(x) {
alert("Error processing solutions.xml.");
}
});
$("#groups").treeview({
toggle: function() {
console.log("%s was toggled.", $(this).find(">span").text());
}
});
});
and the HTML looks like this:
<html>
...
<body>
<ul id="groups">
</ul>
</body>
</html>
The unordered list shows correctly, but the little [+] and [-] signs don't show up and the sections aren't collapsible/expandable. If I get rid of my Ajax loading and insert an unordered list inside of #groups manually it works as expected.
What am I doing wrong? Is there any other plugins or Javascript libs that could make this easier? The solution needs to work on IE6 locally (i.e. webserver).
Update: I found a work-around: If I define my treeview stuff like this it works:
function makeTreeview() {
$("#container").treeview({
toggle: function() {
console.log("%s was toggled.", $(this).find(">span").text());
}
});
}
setTimeout('makeTreeview();', 50);
I think the problem is, when I create the treeview, the ajax stuff hasn't done it's work yet, so when treeview() is called, the unordered list hasn't been created yet. I haven't tested this with IE6 yet. Is there a nicer way to do this, without using SetTimeout()?
I made the same type of call for another project.
For other reasons you will probably want to wrap your ajax call in an anonymous function to create a closure so that your variables remain what you expect them to...
The success method is a callback function that happens after your call is complete , just create your treeview inside that method, or break it out into a seperate fumction if you need to for clarity.
in the example that you show - your treeview will still fail if the ajax call takes longer than 50ms - which could easily happen during initial load if more than two objects are being loaded from that same server.
This example used JSON, and concurrently loaded html data from a page method into a series of divs.
$(document).ready(function() {
for (i= 1;i<=4;i++)
{
(function (){
var divname ="#queuediv"+i;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "test12.aspx/GetHtmlTest",
data: "{}",
error: function(xhr, status, error) {
alert("AJAX Error!");
},
success: function(msg) {
$(divname).removeClass('isequeue_updating');
$(divname).html(msg);
$("#somethingfromthemsg").treeview();
}
});
})();
}
});
Hope that helps!
You need to get FireBug (Firefox add-in) and then you can see in the console what is being returned, and make sure it matches what you expect (And that it is actually doing the request..).
Once you get it working in FF, you can support the ancient 10-year old IE6 browser.
There's also some other things you may want to consider:
The whole ActiveXObject("Microsoft.XMLDOM") jumps out as me as unnecessary. If you pass XML in a string to $(), jQuery turns it into a DOM object.
Additionally, .Find can be replaced by:
$('Element', this);
So for example:
var xmlDoc = '<Group><Solution name="foo" /><Solution name="bar" /></Group>';
$('Solution', xmlDoc).each(function() {
document.write( $(this).attr('name') );
});
would spit out:
foo
bar
Also, with firebug, stick a console.log(list); at the end, to be sure you're generating the HTML you think you are. If you're really stuck in IE6, alert(list) somewhat works as a poor man's equivalent (as long as your file isn't too big).
In short, I think you're on the right track, you just need the tools to debug properly.
For anyone who also finds their way to this post. I had this trouble with an ajax call.
If you want to wait for the ajax call to be returned, you need to set async as false.
$.ajax({
type: 'POST',
async: false,
........