AJAX and YQL doesn´t work using dreamweaver (cross-domain-request) - javascript

I use a js to display some content on my app (I use Dreamweaver and PhoneGap). When i preview the html separately works, but when i load the html from other page dont.
I receive this msg on the Firefox Security: ReferenceError: requestCrossDomain is not defined
This is my HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Mobile Web App</title>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/cross-domain-request.js"></script>
</head>
<body>
<div id="container">
<p id="sitename"> http://catedralaltapatagonia.com/invierno/partediario.php? default_tab=0
</p>
function codeAddress(){
var elem = document.getElementById("sitename");
elem.value = "http://catedralaltapatagonia.com/invierno/partediario.php? default_tab=0";
var path =$('#sitename').val();
requestCrossDomain(path, function(results){
$('#container').html(results);
});
return false;
};
</script>
</body>
</html>
And my cross-domain-request.js:
/ JavaScript Document
// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {
// 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="' + 'http://catedralaltapatagonia.com/invierno/partediario.php?default_tab=0' + '"'+' AND xpath="//*[#id=\'meteo_recuadro\']"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, function(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.');
});
}
Some clue to resolve it?

You appear to have an error in your external JS file, and it's not running. The final else statement is not correct. Try this:
/ JavaScript Document
// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {
// 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="' + 'http://catedralaltapatagonia.com/invierno/partediario.php?default_tab=0' + '"'+' AND xpath="//*[#id=\'meteo_recuadro\']"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, function(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 add the line
<script src="js/cross-domain-request.js"></script>
and the js is loaded

Related

How to call a function from HTML to a Javascript file, in Node.JS

I am using Node.JS with Express. The following line fails, and I need help fixing it.
var routines = require("myJsRoutines.js");
When I run index.html and click MenuItem, I get the first alert, but not the second one.
I have both files in the same directory. Thanks
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
MenuItem
<script>function myMenuFunc(level) {
alert("myMenuFunc1:" + level);
var routines = require("myJsRoutines.js");
alert("myMenuFunc:2" + level);
routines.processClick(level);
alert("myMenuFunc:3" + level);
}</script>
</body>
</html>
myJsRoutines.js:
exports.processClick = function processClick (param1) {
console.log(param1)
}
Script in <script> tags only runs on the client, and script on the server never directly handles DOM events like clicks. There is no magical event wireup - you need to make them interact.
Assuming folder structure from http://expressjs.com/en/starter/generator.html
Updated module code, in /modules/myJsRoutines.js...
var myJsRoutines = (function () {
var multiplier = 2;
return {
processLevel: function (level, callback) {
console.log('processLevel:', level); // CLI or /logs/express_output.log
// validation
if (!level) {
// error is usually first param in node callback; null for success
callback('level is missing or 0');
return; // bail out
}
// processing
var result = level * multiplier;
// could return result, but need callback if code reads from file/db
callback(null, result);
}
};
}()); // function executed so myJsRoutines is an object
module.exports = myJsRoutines;
In /app.js, load your module and add a get method...
var myJsRoutines = require('./modules/myJsRoutines');
app.get('/test', function (req, res) {
var level = parseInt(req.query.level) || 0;
console.log('server level:', level);
myJsRoutines.processLevel(level, function (err, result) {
if (err) {
res.status(500);
return res.send(err);
}
res.send('result ' + (result || '') + ' from the server');
});
});
In /public/index.html, add client script to make an HTTP request to the get method...
<a class="test" href="#" data-level="1">Test Level 1</a>
<a class="test" href="#" data-level="2">Test Level 2</a>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(function(){ // jQuery DOM ready
$('.test').click(function () { // click event for <a class="test">
var level = $(this).data('level'); // from data-level="N"
var url = '/test?level=' + escape(level);
console.log('client url:', url);
// HTTP GET http://localhost:3000/test?level=
$.get(url, function (data) {
console.log('client data:', data); // browser console
});
return false; // don't navigate to href="#"
});
});
</script>
...start the server from the command line...
npm start
...open http://localhost:3000/ in your browser, Ctrl+Shift+i to open the browser console, and click the links.
Run from a node server..var routines = require("myJsRoutines.js"); in the server.js file and Just call a javascript onclick function..and post parameters..for posting parameters..you'll be needing Ajax...and console log the data in node..or After sending the data to the node server..run the function in node server.
Code snippet for calling the function from a href..
and
`MenuItem
<script type="text/javascript">
function myMenuFunc('Level 1') {
// return true or false, depending on whether you want to allow the `href` property to follow through or not
}
`
This line:
var routines = require("myJsRoutines.js");
fails because the require statement is a nodejs function. It does not work with the browser nor does it work with javscript natively. It is defined in nodejs to load modules. To see this
go to your command line and run this
> node
> typeof require
'function'
go to your browser console; firefox - press Ctrl + K
>> typeof require
"undefined"
To achieve your aim, there are two options that come to my mind
// Assumed Express server running on localhost:80
var express = require('express');
var app = express();
app.get("/myJsRoutines", loadRoutines);
app.listen(80);
Option I: XMLHttpRequest
This is a browser API that allows you to open a connection to a server and talk with the server to collect stuff using HTTP. Here's how you do this
<script>
var request = new XMLHttpRequest(); // create an xmlhttp object
request.open("GET", "/myJsRoutines"); // means GET stuff in there
request.link = link;
// wait for the response
request.addEventListener("readystatechange", function() {
// checks if we are ready to read response
if(this.readyState === 4 && this.status === 200) {
// do something with response
}
})
//send request
request.send();
</script>
Lookup XMLHttpRequest API or the new fetch API
Option II: Pug
Pug, formerly named jade is a templating engine for nodejs. How does it work? You use it to programmatically create the html on the server before sending it.
Lookup the site -> https://pugjs.org/

Get a source code from URL web page with JavaScript using JSONP

I'm trying to get the source code form a URL web page using JSONP.
This is the code:
<script type="text/javascript">
var your_url = '';
$(document).ready(function(){
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0]
// YQL screws with <script>s
// Get rid of them
.replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: your_url,
type: 'GET',
success: function(res) {
var text = res.responseText;
//document.getElementById("contenuto").innerHTML = text;
alert(text);
}
});
});
</script>
I printed with an alert all the source code, from the URL.
alert(text);
First, how to know if the printed code is all the web code of the page?
If I try to do in this way
document.getElementById("contenuto").innerHTML = text;
this is the result:
\ \ <'+'/ins>\ \ \ '); } ]]>
I tried to use HTML DOM to print just one element, doing in this way
document.getElementById("contenuto").innerHTML = text;
var elem = text.getElementById("strip_adv").innerHTML;
document.getElementById("contenuto_1").innerHTML = elem;
}
But this is the error on the JS console:
text.getElementById is not a function
Recap:
I would to get the source code of a web page from URL, using JSONP.
I would use HTML DOM from the returned text, to keep only the element/class I need. I'm a newbie on JS, I'm trying to learn more & more about JS.
getElementById() is present only in the document object. What you are trying to do is trying to access getElementId from a string object.
Instead what I would suggest is insert the returned html string inside iframe and you can access the elements within iframe otherwise you can use some kind of html parser in your application.
lets say your html looks like this after you insert your html string inside iframe
<body>
<iframe id="one">
<html>
<body> <h1 id="strip_adv">Heading</h1> </body>
</html
</iframe>
</body>
function iframeObj( frameEle ) {
return frameEle.contentWindow
? frameEle.contentWindow.document
: frameEle.contentDocument
}
var element = iframeObj( document.getElementById('strip_adv') );

JSON data to HTML using .html()

The code below is commented throughout. It is my understanding that I'm retrieving the JSON data and passing it to the 'results' div in my HTML view. This actually returns nothing, and it's difficult to debug because I can't output anything to the console.
// Here is how the final url should look:
// api.openweathermap.org/data/2.5/weather?q=Chicago&APPID=2e76bb25aa22d34ca062d764f4f3114b
var weatherSearch = '';
// weather-search is my html form id. On submit, send the input
// (which is city name) to the function getWeather.
$('#weather-search').submit(function(event) {
weatherSearch = $('#weatherQuery').val();
event.preventDefault();
getWeather(weatherSearch);
});
// getWeather has params q (city name), and APPID (API key).
function getWeather(weatherSearch) {
var params = {
q: weatherSearch,
APPID: '2e76bb25aa22d34ca062d764f4f3114b'
};
// This is the url that goes before the params.
url = 'http://api.openweathermap.org/data/2.5/weather/';
// Request data using url and params above.
// Does $.getJSON format the url properly?
$.getJSON(url, params, function(data) {
// Pass JSON data to showWeather function.
showWeather(data.items);
});
}
function showWeather(weather) {
// Show JSON data (weather) in html div id="weatherResults"
$('#weatherResults').html(weather);
}
Here is the associated HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>weather</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="openweather.js"></script>
</head>
<body>
<form id="weather-search">
<input type="text" value="" id="weatherQuery" />
<input type="submit" />
</form>
<div id="weatherResults">
</div>
</body>
</html>
Here's a codepen for the program
This answer demonstrates multiple ways to request and view data.
The code snippet below queries the web service using either jQuery or plain javascript. The returned data is displayed on the screen using JSON.stringify() and Google Prettify. The data is also sent to the console. Interestingly, the OpenWeatherMap service makes a good guess when the city name is misspelled.
The problem with OP's code appears to be this line: showWeather(data.items); which tries to display an object as html.
Run the snippet to try
var url = 'http://api.openweathermap.org/data/2.5/weather?APPID=2e76bb25aa22d34ca062d764f4f3114b';
// plain javascript version
function getWeather(city) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url + '&q=' + city, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
showData( data );
}
}
xhr.send();
}
// jQuery version
function getWeather2( city ) {
$.getJSON(url + '&q=' + city, showData );
}
// display json weather data
function showData( data ) {
window.city.value = data.name;
window.stdout.innerHTML = JSON.stringify(data, false, ' ');
window.stdout.className = 'prettyprint';
PR.prettyPrint();
if (window.console) window.console.log( data );
}
// sample data
getWeather('Berlin');
input {border: 1px solid black;}
button {width: 8em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/run_prettify.js?autoload=false&skin=sunburst&lang=js"></script>
Enter City: <input id="city" >
<button onclick="getWeather(window.city.value)">Use JS</button>
<button onclick="getWeather2(window.city.value)">Use jQuery</button>
<pre id="stdout" class="prettyprint"></pre>
You can use console.log or the dom to print messages for debugging. You can run a callback like this to find out if a request fails, this will tell you more infomation:
$.getJSON(url, params, function(data) {
// Pass JSON data to showWeather function.
showWeather(data.items);
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
Using the complete URL (http://api.openweathermap.org/data/2.5/weather/?q=Chicago&APPID=2e76bb25aa22d34ca062d764f4f3114b) directly in a browser returns some JSON with data about chicago -- but that JSON does NOT contain an item property. Thus, your data.items is null and nothing is shown.
Just check what you actually get from the browser and adopt your code accordingly (e.g. data.name would give you "Chicago", or simply use showWeather(data); to show all JSON you got).

Trigger cross domain YQL ajax request with input onBlur

I have a form to collect information about a product (i.e. from Amazon). I am attempting to trigger a YQL ajax request on blur of the URL input. Currently, no errors in console, but no results either. Here is my form input:
<div class="uk-form-row">
<div class="uk-form-label"><?php echo $this->form->getLabel('item_url'); ?></div>
<div class="uk-form-controls "><input type="text" name="jform[item_url]" id="jform[item_url]" value="<?php if (!empty($this->item->id)) { echo $this->item->item_url;}; ?>" class="uk-form-large uk-width-medium-1-1" placeholder="http://" aria-required="required" required="required"/></div>
</div>
<script type="text/javascript">
jQuery( "#jform[item_url]" ).blur(function() {
var path = jQuery('#jform[item_url]').val();
requestCrossDomain(path, function(results) {
jQuery('#url_results').html(results);
});
});
</script>
<div id="url_results">
</div>
My function:
// 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.
jQuery.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.');
}
}
Here's the fiddle: http://jsfiddle.net/FLY66/2/
This issue is more related to your server. You can simply set the Access-Control-Allow-Origin header on your server. Look for your server language to see how to set Access-Control-Allow-Origin
Setting it to * will accept cross-domain AJAX requests from any domain.
Another alternative is use 'JSONP' data type for returned data.
References
http://en.wikipedia.org/wiki/Same_origin_policy
https://developer.mozilla.org/en/http_access_control

Call MVC action method by javascript but not using AJAX

I have a MVC3 action method with 3 parameters like this:
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
and I want to call this by normal javascript function not AJAX (because it's not necessary to use AJAX function)
I tried to use this function but it didn't work:
window.location.assign(url);
It didn't jump to Insert action of QuestionController.
Is there someone would like to help me? Thanks a lot
This is more detail
I want to insert new Question to database, but I must get data from CKeditor, so I have to use this function below to get and validate data
// insert new question
$("#btnDangCauHoi").click(function () {
//validate input data
//chủ đề câu hỏi
var title = $("#txtTitle").val();
if (title == "") {
alert("bạn chưa nhập chủ đề câu hỏi");
return;
}
//nội dung câu hỏi
var content = GetContents();
content = "xyz";
if (content == "") {
alert("bạn chưa nhập nội dung câu hỏi");
return;
}
//danh sách Tag
var listTags = new Array();
var Tags = $("#list_tag").children();
if (Tags.length == 0) {
alert("bạn chưa chọn tag cho câu hỏi");
return;
}
for (var i = 0; i < Tags.length; i++) {
var id = Tags[i].id;
listTags[i] = id;
//var e = listTags[i];
}
var data = {
"_strTitle": title,
"_strContent": content,
"_listTags": listTags.toString()
};
// $.post(url, data, function (result) {
// alert(result);
// });
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
window.location.assign(url); // I try to use this, and window.location also but they're not working
});
This URL call MVC action "Insert" below by POST method
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
try
{
//some code here
}
catch(Exception ex)
{
//if some error come up
ViewBag.Message = ex.Message;
return View("Error");
}
// if insert new question success
return RedirectToAction("Index","Question");
}
If insert action success, it will redirect to index page where listing all question include new question is already inserted. If not, it will show error page. So, that's reason I don't use AJAX
Is there some one help me? Thanks :)
Try:
window.location = yourUrl;
Also, try and use Fiddler or some other similar tool to see whether the redirection takes place.
EDIT:
You action is expecting an HTTP POST method, but using window.location will cause GET method. That is the reason why your action is never called.
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
// Your code
}
Either change to HttpGet (which you should not) or use jQuery or other library that support Ajax in order to perform POST. You should not use GET method to update data. It will cause so many security problems for your that you would not know where to start with when tackling the problem.
Considering that you are already using jQuery, you might as well go all the way and use Ajax. Use $.post() method to perform HTTP POST operation.
Inside a callback function of the $.post() you can return false at the end in order to prevent redirection to Error or Index views.
$.post("your_url", function() {
// Do something
return false; // prevents redirection
});
That's about it.
You could try changing
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
to
var url = "/Question/Insert?_strTitle=" + title + "&_strContent=" + content + "&_listTags=" + listTags.toString();
I've removed the single quotes as they're not required.
Without seeing your php code though it's not easy to work out where the problem is.
When you say "It didn't jump to Insert action of QuestionController." do you mean that the browser didn't load that page or that when the url was loaded it didn't route to the expected controller/action?
You could use an iframe if you want to avoid using AJAX, but I would recommend using AJAX
<iframe src="" id="loader"></iframe>
<script>
document.getElementById("loader").src = url;
</script>

Categories

Resources