I have a page containing a set of hyperlinks. Clicking on any of the hyperlinks should take the user to a new page with the url sent as POST data.
What I am able to do:
1. Open the new page.
What issues I am facing:
1. In the new page, I am trying to access the url that was sent across as data. The url is not visible. Where am I going wrong?
The code I have so far:
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function takeMeHome(obj) {
var URL = obj.getAttribute("href");
//alert("Url = " + URL + " with id = " + obj.id);
console.log("URL = " + URL);
$.ajax({
type: 'POST',
url: './bbCloud.php',
data: {'tgt_url': URL},
success:function(data) {
console.log("Function invoked. It seems posting data was a success");
window.location = URL;
//alert('This was sent back: ' + data);
}
});
return false;
}
</script>
</head>
<body>
<p>
Choose one of the links below to access content:</p>
<p>1. Email Etiquette</p>
</body>
</html>
bbCloud.php:
<?php
//the function below displays data from bbMainPage javascript.
function getDataFromLibrary() {
$tgt_url = $_POST["tgt_url"];
echo "Data received = " . $tgt_url . "<br/>";
return $tgt_url;
}
?>
<html>
<head>
<style>
.hlight{background-color:#ffcc00;}
textarea {
width:100%;
height:100%;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://myDomain/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
//mention all global variables here.
console.log("this is the start of javascript");
//get all data from the previous script.
var tgtURL = "<?php getDataFromLibrary(); ?>";
console.log("URl obtained = " + tgtURL);
</script>
<body>
<div>
<audio id="playText" src="" controls></audio>
</div>
</body>
</html>
try dynamically creating and submiting a form instead of trying to ajax it:
<script type="text/javascript">
function takeMeHome(obj) {
var URL = obj.getAttribute("href");
$('<form>', {
"html": '<input type="text" name="tgt_url" value="' + URL + '" />',
"action": URL
}).appendTo(document.body).submit();
}
</script>
Hmm, if I recall correctly, what is happening is that your $.ajax does indeed send the POST data to your php file. The problem is, that it sends the post data, the php file is executed, and a response is sent back, but its sent back to the $.ajax call itself. You THEN redirect to the php file (and thus run it again), but without the post data coming along. Also, something along the lines of $.('a').click(function(event) { event.preventDefault(); } might be a good idea. I'll try and make a better answer for you when I get home (currently on my phone, shouldn't be long).
Related
I am trying to put some HTML code into iframe to present data. Everythink works fine, but when I want to put any java script in an iframe there is no result. It seems that iframe cannot see any local javascript.
Here is a code:
<html>
<head>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="testJSON.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<p id="demo"></p>
<script src="names.js"></script>
<script type="text/javascript">
$("#frame").attr(
"src", "data:text/html;charset=utf-8," +
"<html><head>"+
"<script src='jquery.min.js'><"+"/script>"+
"<script src='testJSON.js'><"+"/script></head>"+
"<body><p id='demo'></p>"+
"<script src='name.js'><"+"/script>"+
"<h1>Test</h1>"+
"</body></html>"
);
</script>
</body>
</html>
testJSON.js:
var dane = '{ "names" : [' +
'{ "firstName":"Ana" , "lastName":"Doe" },' +
'{ "firstName":"Bill" , "lastName":"Smith" },' +
'{ "firstName":"Dory" , "lastName":"Jones" } ]}';
names.js:
var nameID =function() {
return 2;
};
obj = JSON.parse(dane);
document.getElementById("demo").innerHTML =
obj.names[nameID()].firstName + " " + obj.names[nameID()].lastName;
Has anyone have a solution to this problem?
Thank you
I assume DataURIs cannot contain external scripts for security reasons but I cannot find the duplicate SO post that confirms this. Anyway, document.write the html and script into the frame. That works
$("#frame")[0].document.contentDocument.write(
"<html><head>"+
"<script src='jquery.min.js'><\/script>"+
"<script src='testJSON.js'><\/script></head>"+
"<body><p id='demo'></p>"+
"<script src='name.js'><\/script>"+
"<h1>Test</h1>"+
"</body></html>"
);
$("#frame")[0].contentDocument.close();
you may need to fully qualify the URLs of the external files
Thats a race problem: youre trying to access the json, before the iframe is loaded, therefore, dane will be undefined. Use listeners or kinda callback.
Callback:
//in your page:
function parse(json){
//do sth with json
}
//in the iframe:
parse("{}");
Listeners:
document.getElementsByTagName("iframe")[0].onload=function(){
//you parsing js
};
I am using a PHP Simple HTML DOM Parser to save a website as a htm file. I then use jQuery to extract a div from the file and put it into a div. I want to create a
Previous and Next button but the problem I have is that to do this I have to change the URL so the parser can get the page. I would really appreciate if you can help. Below is the code I am using.
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=1');
$html->save('site/rtnews.htm')
?>
<script type="text/javascript" src="site/jquery.js"></script>
<script type="text/javascript">
$('document').ready(function() {
$('#wrap').click(function (event){
event.preventDefault();
});
$("#wrap").load('site/rtnews.htm #postsArea');
});
</script>
</head>
<body>
<div id="wrap">
</div>
</body>
You will have to create a new php file for this and make an AJAX request to that file. I assume you have already realised that you cannot make a cross-domain request due to CORS.
Here is your new php file, let's call it proxy.php. It will proxy the request, responding with the page that is passed to it via GET :
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=' . $_GET["page"]);
echo $html;
?>
Your new JavaScript;
$('document').ready(function() {
var $wrap = $('#wrap'),
page = 1;
$('#next').on('click', function () {
getPage(++page);
});
$('#prev').on('click', function () {
getPage(--page);
});
var getPage = function (page) {
$wrap.load('proxy.php?page=' + page + ' #postsArea');
};
getPage(page);
});
Hello and thanks for looking this over. Very new to jQuery/ajax etc. This website has FTP access to appropriate server, so I (as far as I know) am not violating cross-domain policy.
This is website works fine on any desktop browser but does not work on any mobile browser.
I feel like the issue is obviously but I don't know what to do. Can someone help me with This?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GRID Mobile</title>
<meta name = "viewport" content="width=device-width, user-scalable=no"/>
<link href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" rel="stylesheet" type="text/css"/>
<script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'http://www.e-grid.net/BayAreaTech/wp-rss2.php?cat=1',
dataType: 'xml',
success: function (xml) {
$(xml).find("item").each(function () {
var title = $(this).find("title").text();
var description = $(this).find("description").text();
var linkUrl = $(this).find("link").text();
var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>";
$('#feedContainer').append('<h3>'+title+'</h3><p>'+description+link+'</p>');
});
}
});
</script>
</head>
<body>
<div data-role="page" id="page">
<div data-role="header" data-theme="b">
<h1>GRID MOBILE</h1>
</div>
<div data-role="content">
<div id="feedContainer"></div>
<h3></h3>
<p></p>
</div>
<div data-role="footer">
<h4>Advertisements</h4>
</div>
</div>
</body>
</html>
Just a thought, have you tried wrapping your ajax call in a load event. I havent tested this on a mobile browser. However try.
<script type="text/javascript">
$(function () {
$.ajax({
type: 'GET',
url: 'http://www.e-grid.net/BayAreaTech/wp-rss2.php?cat=1',
dataType: 'xml',
success: function (xml) {
$(xml).find("item").each(function () {
var title = $(this).find("title").text();
var description = $(this).find("description").text();
var linkUrl = $(this).find("link").text();
var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>";
$('#feedContainer').append('<h3>' + title + '</h3><p>' + description + link + '</p>');
});
}
});
});
</script>
Note the only changes was the $(function() { }); wrapping.
EDIT: Tested on OSX.
Just a quick FYI I tested your page on an IPhone 5s on OSX and there are definitly Cross site origin problems.
The actual error is
XMLHttpRequest cannot load http://www.e-grid.net/BayAreaTech/wp-rss2.php?cat=1 Origin. xxxx is not allowed by Access-Control-Allow-Origin.
Now this is the error that is coming from the IPhone using the Safari web inspector. Additionally when this file was not hosted on a webserver and run as a simple HTML file the request works fine. Its as soon as you host the file in a webserver you will get the CORS issue.
To resolve this you will need to contact the webmaster and allow cross site origin, switch to a different method of retrieving the issue. There are other methods to try and get around CORS issues.
Sorry if this is not that helpful.
FINAL EDIT: The actual problem.
Ok from what I can tell the problem is the fully coded url http://www.e-grid.net/BayAreaTech/wp-rss2.php?cat=1 in your script. As you are on the same webserver on the same host i would suggest using a relative url as
/BayAreaTech/wp-rss2.php?cat=1
The reason for this is if you are browsing without the www. in your browser (or device) then the script thinks it is calling another service as the URLs done match. However as you are hosting the service on the same server you can eliminate the http://www. part and this should work fine.
To test this open your desktop browser to.
http://www.e-grid.net/mobile/index.html
When you do this all works well. Now try. (note without the WWW). This does not work as you are now executing cross domain (as you have hard coded the www portion. portion in the url.
http://e-grid.net/mobile/index.html
Give this a try and let me know how it goes.
Try the following script block.
<script type="text/javascript">
$(function () {
$.ajax({
type: 'GET',
url: '/BayAreaTech/wp-rss2.php?cat=1',
dataType: 'xml',
success: function (xml) {
$(xml).find("item").each(function () {
var title = $(this).find("title").text();
var description = $(this).find("description").text();
var linkUrl = $(this).find("link").text();
var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>";
$('#feedContainer').append('<h3>' + title + '</h3><p>' + description + link + '</p>');
});
}
});
});
</script>
I'm reading this tutorial and I'm having some problems with the examples... I tried to run the examples in localhost but I'm encountering with some errors and really don't know what could it be. I should be getting the first post of WP, but instead of that I'm getting this error Uncaught ReferenceError: url is not defined. Any sugestions??? Thanks!
<!DOCTYPE HTML>
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
(url,target_div) {
var URL = url
jQuery.ajax({
url: URL,
dataType: 'json',
success: function(data) {
jQuery(target_div).html(data.post.content);
}
});
}
jQuery(document).ready(function() {
jQuery("#title").html("<h1>Hello World</h1>");
varurl = "http://localhost/phonegap/?json=get_post&dev=1&p=1";
vartarget_div = "#contents";
readSinglePost(url, target_div);
});
</script>
</header>
<body>
<div id="main">
<div id="title"></div>
</div>
</body>
</html>
It looks like "varurl =" should have a space to be "var url =" and same with "vartarget_div =" should be "var target_div =" instead.
Change a code as var url not varurl and var target_div not 'vartarget_div'. Give space to keyword var and the variable.
jQuery(document).ready(function() {
jQuery("#title").html("<h1>Hello World</h1>");
var url = "http://localhost/phonegap/?json=get_post&dev=1&p=1";
var target_div = "#contents";
readSinglePost(url, target_div);
});
I have a script here, copied pretty much directly off this. Why doesn't the code, listed below, return anything?
ajax.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cross-Domain Ajax Demo</title>
</head>
<body>
<div id="container">
<form>
<p><label>Type a URL:</label><input type="text" name="sitename" id="sitename"/></p>
<p><input type="submit" name="submit" id="submit" value="Make Cross Domain Ajax request"</p>
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="cross-domain-requests.js"></script>
<script type="text/javascript">
$('form').submit(function() {
var path = "www.google.com";
requestCrossDomain(path, function(results) {
$('#container').html(results);
});
return false;
});
</script>
</body>
</html>
cross-domain-requests.js:
// Accepts a URL and a callback function to run.
function requestCrossDomain( site, callback ) {
// If no URL was passed, exit.
if ( !site ) {
alert('No site was passed.');
return false;
}
// Take the provided URL, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=cbFunc';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, cbFunc );
function cbFunc(data) {
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}
(I'm relatively new to scripting and Ajax, so I apologise in advance if I do anything stupid.)
Try changing the callback in var yql to callback=? and the select statement to 'from xml' like this:
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';