Let me ask very short comparative past questions.
I got the result from YQL CONSOLE not my terminal.
Below is my code.
new YQL.exec('select * from html where url="http://fortune.daum.net/external/4/run/star_free/index.php" and xpath="//td[contains(#style,"font-family:굴림; font-size:12px; color:#333333; line-height:18px; padding-right:10px")]/"', function(response) {
console.log(response);
//response consists of JSON that you can parse
if (response.error) {
console.log('error');
}
else {
//var location = response.query.results.result;
var location = response.query.results.result;
console.log(location);
}
});
It seems that you have mistaken multi-level quote marks, try below:
new YQL.exec('select * from html where url="http://fortune.daum.net/external/4/run/star_free/index.php" and xpath="//td[contains(#style,\'font-family:굴림; font-size:12px; color:#333333; line-height:18px; padding-right:10px\')]"')
Related
I have used cordova(navigator.camera.getPicture) to capture image from device. I converted the fileURI into base64 using file reader. But, when i assign the base64 url as img src whereas If i pass the same string to HTTP adapter(Worklight), I saw the encoded data truncated. Please help.
Thanks in advance.
Source Code:
function tryToSend(evt) {
encoding = evt.target.result;
console.log("Encoded File: "+encoding);
Ext.ComponentQuery.query('#encodedImage')[0].setHtml('<img style="height: 100px; width: 100px;" src="'+encoding+'" />');
Ext.ComponentQuery.query('#encodedImage')[0].setHidden(false);
}
function win(file) {
alert("FileName:"+file.name + ' & Type:' + file.type);
selectedFileName = file.name;
Ext.ComponentQuery.query('#originalImage')[0].setHtml('<img style="height: 100px; width: 100px;" src="'+file.fullPath+'" />');
Ext.ComponentQuery.query('#originalImage')[0].setHidden(false);
var reader = new FileReader();
reader.onloadend = tryToSend;
var encoded = reader.readAsDataURL(file);
}
function fail(error) {
console.log(error);
}
function onResolveSuccessCompleted(fileEntry) {
fileEntry.file(win, fail);
}
function onResolveFailed(error) {
console.log(error);
}
//Call on click of take pic button
function capPic(){
navigator.camera.getPicture(onCapturePhoto, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
mediaType: navigator.camera.MediaType.ALLMEDIA,
});
}
//Success
function onCapturePhoto(fileURI) {
window.resolveLocalFileSystemURI(fileURI, onResolveSuccessCompleted, onResolveFailed);
fileDetails.push({
base64ImageData:encoding,
fileName: selectedFileName,
});
alert("File Selected. Please Upload Now");
}
//Sending fileDetails array to HTTP adapter as parameter
var invocationData = {
adapter : 'SAMPLE_ADAPTER',
procedure : 'uploadFileNow',
parameters : [fileDetails]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : fileUploadOK,
onFailure : fileUploadFail,
});
1) In Logcat, encoding in tryToSend Fn prints completely whereas the next line console.log gives truncated code
//Ajax call
Ext.Ajax.request({
url: url,
method:'POST',
params:fileDetails,
success: function(response){
console.log(response);
},
failure:function(response){
console.log(response);
}
});
In my logcat the console.log can only print about 4k characters one time. So try to compare the encoded url's length to check if it's really be truncated.
I would like to send a post request to my API. It works with jQuery :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",
url: "api.php?option=inscription",
data: {lol : "mess"}
});
</script>
But it doesn't with AngularJS :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
{{1+1}}
<script>
$http.post('api.php?option=inscription', {lol : "mess2"})
.success(function(){alert('cool');});
</script>
If someone can help me. Thank you !
UPDATE :
Thank for your answers, I wanted to simplify but it wasn't clear anymore. So with your help, this is my new code, and the problem is the same. The data in the backend is empty ;
frontend :
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<div ng-controller="MainCtrl"></div>
{{data}}
<script>
var app = angular.module('myApp', []);
app.service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
var back = $http.post(dataUrl, dataTobePosted);
back.success(function(data){
console.log(data);
return data;
}).error(function(data, status, headers, config) {
return status;
});
}
});
app.controller('MainCtrl', function($scope, $http, SomeService){
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
$scope.data = SomeService.readData(url, dataTobePosted);
}
$scope.readData('api.php?option=inscription');
});
</script>
</html>
For clarity, I am suggesting a simple implementation. However, further reading may needed in order to understand the behaviour precisely.
angular.module('myApp').service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
// read data;
return $http.post(dataUrl, dataTobePosted)
.then(function(res) {
return res.data;
}, function(res) {
return res;
}
}
return this;
});
angular.module('myApp').controller('MyController', function($scope, SomeService) {
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
SomeService.readData(url, dataTobePosted)
.then(function(res) {
$scope.data = res;
}, function(res) {
// Display error
}
}
$scope.readData('api.php?option=inscription');
}
Usage in the HTML page
<div ng-controller="MyController">
{{data}}
</div>
You're using AngularJS as if it's jQuery. It's not. AngularJS works with dependency injection, so you need to wrap your $http call inside a controller.
You should probably read up on AngularJS. A few useful links:
https://docs.angularjs.org/guide/introduction
https://docs.angularjs.org/guide/controller
https://docs.angularjs.org/guide/di
"Thinking in AngularJS" if I have a jQuery background?
My bad, my problem came from my backend in the php I just get my data with :
$data = json_decode(file_get_contents("php://input"));
and not with $_POST
I'm new to socket.io and i already have a problem, minor i think.
I have installed node.js properly and socket.io too with npm. Then just for testing i cut and paste a sample of code from socket.io and everything works well.
Now, i want to strcuture my code and folders and i have created a folder "client" to put a fresh new js file client.js with the client code from the example.
Here is my architecture
/client
client.js
index.html
server.js
client.js :
var socket = io.connect('http://localhost:80');
socket.on('news', function (data) {
alert('sqd');
console.log(data);
socket.emit('my other event', { my: 'data' });
});
server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html', 'utf-8',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html ' + __dirname);
}
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
index.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<script type="text/javascript" src="/client/client.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
</head>
<body>
</body>
</html>
When i refresh my browser at localhost:80 i have a error on my client.js :
Uncaught SyntaxError: Unexpected token <
Resource interpreted as Script but transferred with MIME type text/html
It seems that there's a problem to interpret my js file as a js file. I've read some threads on the question but nothing works.
Can you help me please ?
Thanx :)
Ok i've found a solution... You have to specify the content type for each file request in a static webserver. May be it could help someone.
Here is the handler function :
function handler (req, res) {
var filePath = req.url;
if (filePath == '/') {
filePath = './client/index.html';
} else {
filePath = './client/lib' + req.url;
}
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
}
else {
res.writeHead(404);
res.end();
}
});
}
Hope this can help someone.
I love to post a problem and respond by myself with no help. Somehow it meens that i'm desesperate too fast. And i love to tell my life in a post too :)
Ok i'm gonna eat something and drink more coffee !!!
Thank you so much! This solved my problem!! And I changed the switch to following code:
var extname = path.extname(filePath);
var contentTypesByExtention = {
'html': 'text/html',
'js': 'text/javascript',
'css': 'text/css'
};
var contentType = contentTypesByExtention[extname] || 'text/plain';
It may be easier to maintain :)
Only that solves:
function handler (request, response) {
var file = __dirname + (request.url == '/' ? '/index.html' : request.url);
fs.readFile(file, function(error, data) {
if (error) {
response.writeHead(500);
return response.end('Error loading index.html');
}
response.writeHead(200);
response.end(data, 'utf-8');
});
}
that's what i need! thank you!
and
we'll add one code line a top of
server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
**, path = require('path')**
You can use mime module as well:
var mime = require('mime')
, content_type = mime.lookup(filePath);
// handle the request here ...
response.setHeader('Content-Type', content_type);
response.writeHead(200);
response.end(data);
And you must made fs.readFile wrapped by a closure, otherwise some file (especially the last file) will be read more than once, and others will not be read at all. And the contentTypewill not be set as you wish. This is because of the callback strategy used by fs.readFile. The problem does not appear when the html file just load one external file, but as the external files(css, js, png) loaded more than one it will appear as i pointed out above. (I came upoon this by myself)
So your code should make a little change as follows:
;(function (filename, contentType) {
fs.readFile(filename, function(err, file) {
// do the left stuff here
});
}(filename, contentType));
Hi I can see this has been discussed but after perusing the issues/answers I still don't seem to be able to get even this simple AJAX call to bump out of ready state 1.
Here's the Javascript I have:
<script language="javascript" type="text/javascript">
var request;
function createRequest()
{
try
{
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
function loadClassesBySchool()
{
//get require web form pieces for this call
createRequest(); // function to get xmlhttp object
var schoolId = getDDLSelectionValue("ddlSchools");
var grade = getDDLSelectionValue("ddlGrades");
var url = "courses.php?grades=" + escape(grade) + "&schoolId=" + escape(schoolId);
//open server connection
request.open("GET", url, true);
//Setup callback function for server response
//+++read on overflow that some fixed the issue with an onload event this simply had
//+++the handle spitback 2 readystate = 1 alerts
request.onload = updateCourses();
request.onreadystatechanged = updateCourses();
//send the result
request.send();
}
function updateCourses()
{
alert('ready state changed' + request.readyState);
}
function getDDLSelectionValue(ddlID)
{
return document.getElementById(ddlID).options[document.getElementById(ddlID).selectedIndex].value;
}
</script>
The PHP is HERE just a simple print which if i navigate to in the browser (IE/Chrome) loads fine:
<?php
print "test";
?>
I'm quite new at this but seems like I can't get the most bare bones AJAX calls to work, any help as to how work past this would be greatly appreciated.
All I get out of my callback function 'updateCourses' is a 1...
Well after more digging I actually gave up and switched over to jQuery which should for all intents and purposes be doing the EXACT same thing except for the fact that jQuery works... I was just less comfortable with it but so be it.
Here's the jQuery to accomplish the same:
function loadCoursesBySchool(){
var grades = getDDLSelectionValue("ddlGrades");
var schoolId = getDDLSelectionValue("ddlSchools");
jQuery.ajax({
url: "courses.php?grades=" + grades + "&schoolId=" + schoolId,
success: function (data) {
courseDisplay(data);
}
});
}
function courseDisplay(response)
{
//check if anything was setn back!?
if(!response)
{
$("#ddlCourses").html("");
//do nothing?
}
else
{
//empty DLL
$("#ddlCourses").html("");
//add entries
$(response).appendTo("#ddlCourses");
}
}
In my index.html page I want to load a seperate ajax page when the app is loading,
what is the best way of doing that?
This is my index code:
loading ajax subpage here.....
And the subpage is just:
content..............
Thanks.
using JavaScript you can do that. You have to do that on page load. Here is an example in jQuery.
$(function(){
$('#content').load('/content.html');
});
As an example, you can call a javascript function when the body of your main page loads using the onload property of body:
<html>
<head>
...
</head>
<body onload="loadContent();">
...
</body>
</html>
Among your javascript functions, you will need your loadContent function as well as some functions that perform the HTTPRequest-related operations.
function loadContent()
{
var contentURL = "contentpage.xml";
http.Open("GET", contentURL, true);
http.onreadystatechange = useHttpResponse;
http.send(null);
}
var http = getXMLHTTPRequest();
function getXMLHTTPRequest()
{
try
{
req = new XMLHttpRequest();
}
catch (err1)
{
try
{
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (err2)
{
try
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (err3)
{
req = false;
}
}
}
return req;
}
function useHttpResponse()
{
if (http.readyState == 4)
{
if (http.Status == 200)
{
var xml = http.responseXML;
// do something with loaded XML (such as populate a DIV or something)
}
}
}
You should check out some AJAX tutorials online for more complete information.
Use jQuery: www.jquery.com
There are loads of examples and docs on the website, as well as tons of tutorials on the web.
Good luck