Setting baseurl in cakephp - url

I am working on an application which is running in CakePHP and I am using AJAX queries from within.
In all the cases for all the ajax post i have used the url as
var ht = $.ajax({
type: "GET",
url: "http://172.20.52.99/FormBuilder/index.php/forms/viewChoices/"+attribute_id,
async: false
}).responseText;
var myObject = eval('(' + ht + ')');
Is there any way in CakePHP where I can give my base URL as http://172.20.52.99/FormBuilder/index.php/ and to call the base URL in all the places I want.

Try writing following code
'http://'.$_SERVER['HTTP_HOST'].$this->base
$_SERVER['HTTP_HOST']----it will give you working host
and $this->base---will give you working url

You can use $this->base to get base url.

you may use
<?php echo Router::fullbaseUrl();?>
as well.
Refer http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html for more details.

You could set default URL for all your ajax requests that way:
$.ajaxSetup({
url: 'http://172.20.52.99/FormBuilder/index.php/'
});

Use any one method of following
<?php echo $this->Html->url('/');?>
<?php Router::url('/', true); ?>
<?php echo $this->base;?>
<?php echo $this->webroot; ?>
Define constant in Config/core.php as define("BASE_URL", "www.yoursite.com/"); and use BASE_URL anywhere in your project

I assume I've the same scenario: for development, the site is available at localhost/cake, whereby in production the site is deployed in the root dir of example.com. In the header I set:
<base href="<?php echo $base_url ?>" />,
in AppContoller::beforeRender() I set:
$this->set('base_url', 'http://'.$_SERVER['SERVER_NAME'].Router::url('/'));.
This works fine for everything, except JS (so thus AJAX), as it ignores base_url.
Therefore I have a workaround (uses jQuery, but easy to substitute without):
forUrl = function(url) {
return $('base').attr('href')+url.substr(1);
}
login = function() {
$.post(forUrl('/ajax/profileDiv'), $('#profile-login-form').serialize(),
function(data) {
(...)
});
}

This might also be helpful:
http://book.cakephp.org/view/1448/url
<?php echo $this->Html->url('/posts', true); ?>
//Output
http://somedomain.com/posts

Related

YQL: html table is no longer supported

I use YQL to get some html-pages for reading information out of it.
Since today I get the return message "html table is no longer supported. See https://policies.yahoo.com/us/en/yahoo/terms/product-atos/yql/index.htm for YQL Terms of Use"
Example in the console: https://developer.yahoo.com/yql/console/#h=select+*+from+html+where+url%3D%22http%3A%2F%2Fwww.google.de%22
Did Yahoo stop this service? Does anybody know a kind of announcement from Yahoo? I am wondering whether this is simply a bug or whether they really stopped this service...
All documentation is still there (html scraping):
https://developer.yahoo.com/yql/guide/yql-select-xpath.html ,
https://developer.yahoo.com/yql/
A while ago I posted in an YQL forum from Yahoo, now this one does not exist anymore (or at least I do not find it). How can you contact Yahoo to find out whether this service really stopped?
Best regards,
hebr3
It looks like Yahoo did indeed end their support of the html library as of 6/8/2017 (according to my error logs). There doesn't appear to be any official announcement of it yet.
Luckily, there is a YQL community library that can be used in place of the official html library with few changes to your codebase. See the htmlstring table in the YQL Console.
Change your YQL query to reference htmltable instead of html and include the community environment in your REST query. For example:
/*/ Old code /*/
var site = "http://www.test.com/foo.html";
var yql = "select * from html where url='" + site + "' AND xpath='//div'";
var resturl = "https://query.yahooapis.com/v1/public/yql?q="
+ encodeURIComponent(yql) + "&format=json";
/*/ New code /*/
var site = "http://www.test.com/foo.html";
var yql = "select * from htmlstring where url='" + site + "' AND xpath='//div'";
var resturl = "https://query.yahooapis.com/v1/public/yql?q="
+ encodeURIComponent(yql) + "&format=json"
+ "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
Thank you very much for your code.
It helped me to create my own script to read those pages which I need. I never programmed PHP before, but with your code and the wisdom of the internet I could change your script to my needs.
PHP
<?
header('Access-Control-Allow-Origin: *'); //all
$url = $_GET['url'];
if (substr($url,0,25) != "https://www.xxxx.yy") {
echo "Only https://www.xxxx.yy allowed!";
return;
}
$xpathQuery = $_GET['xpath'];
//need more hard check for security, I made only basic
function check($target_url){
$check = curl_init();
//curl_setopt( $check, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip"));
//curl_setopt($check, CURLOPT_INTERFACE, "xxx.xxx.xxx.xxx");
curl_setopt($check, CURLOPT_COOKIEJAR, 'cookiemon.txt');
curl_setopt($check, CURLOPT_COOKIEFILE, 'cookiemon.txt');
curl_setopt($check, CURLOPT_TIMEOUT, 40000);
curl_setopt($check, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($check, CURLOPT_URL, $target_url);
curl_setopt($check, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($check, CURLOPT_FOLLOWLOCATION, false);
$tmp = curl_exec ($check);
curl_close ($check);
return $tmp;
}
// get html
$html = check($url);
$dom = new DOMDocument();
#$dom->loadHTML($html);
// apply xpath filter
$xpath = new DOMXPath($dom);
$elements = $xpath->query($xpathQuery);
$temp_dom = new DOMDocument();
foreach($elements as $n) $temp_dom->appendChild($temp_dom->importNode($n,true));
$renderedHtml = $temp_dom->saveHTML();
// return html in json response
// json structure:
// {html: "xxxx"}
$post_data = array(
'html' => $renderedHtml
);
echo json_encode($post_data);
?>
Javascript
$.ajax({
url: "url of service",
dataType: "json",
data: { url: url,
xpath: "//*"
},
type: 'GET',
success: function() {
},
error: function(data) {
}
});
Even though YQL does not support the html table anymore, I've come to realize that instead of making one network call and parsing out the results it's possible to make several calls. For example, my call before would look like this:
select html from rss where url="http://w1.weather.gov/xml/current_obs/KFLL.rss"
Which should give me the information as such below
Now I'd have to use these two:
select title from rss where url="http://w1.weather.gov/xml/current_obs/KFLL.rss"
select description from rss where url="http://w1.weather.gov/xml/current_obs/KFLL.rss"
.. to get what I want. I don't know why they would deprecate something like this without a fallback clearly listed but you should be able to get your data this way.
I build an open source tool called CloudQuery (source code)provide similar functionality as yql recently. It is able to turn most websites to API with some clicks.

Can Meteor's Backbone Router handle POST requests?

I have a Meteor app which uses a router as per the sample Todos app, eg.:
var TodosRouter = Backbone.Router.extend({
routes: {
":list_id": "main"
},
main: function (list_id) {
...
},
...
});
Router = new TodosRouter;
I have an external service that lets me know when it is finished via a POST request to a URL that I specify. On receiving the POST request, it needs to perform some functions. Can I set this up consistent with the above framework? If not, am I better off writing a separate non-Meteor (eg. nodejs) app to handle the POSTs, or is there a way to make it work within Meteor?
I know this, this and this StackOverflow question are similar, but none of the answers explains how to do it with the Backbone.Router.
Thanks!
Here's how I migrated from the Backbone.Router to Iron-Router. I couldn't see a way to use them both at once.
First, I put code like in #Christian Fritz's answer, in the server folder:
Router.map(function () {
this.route('foo', {
path: '/foo',
where: 'server',
action: function() {
if (this.request.method == 'POST') {
console.log('post request received');
} else {
this.response.writeHead(404);
}
}
})
});
That handles the POST request, as tested by including a console.log in the action (which will write to the terminal window where meteor is running), and typing:
curl --data "p=bar" localhost:3000/foo
Then I replaced the Backbone.Router call with code in the client folder, as described in the Iron-Router docs, eg.
Router.configure({
layoutTemplate: 'layout'
});
Router.map(function () {
this.route('home', {
path: '/',
template: 'homepage',
});
});
Then I had to rewrite my templates so that pages were generated from different templates, instead of from different Session variable settings. This actually simplified my code, eg. instead of:
<body>
{{#if onPage 'home'}}
{{> homepage }}
{{/if}}
{{#if onPage 'help'}}
{{> helppage }}
{{/if}}
...
</body>
and
UI.registerHelper("onPage", function(name) {
return Session.equals('page', name);
});
it's just:
<template name="layout">
{{>yield}}
</template>
Any javascript that needs to direct the user to a specific page uses Router.go() with the route name:
Router.go('home');
Beyond that, I found a few places where I used to be able to assume my collections .findOne() had found one, but seem to have broken with Iron-Router. Wrapping these in ifs fixed them.
In Meteor 0.8, to check what page you are on you can use (see here):
Router.current().lookupProperty('template')

InAppBrowser inject script (using executeScript)

InAppBrowser js scripts injection using {code: 'some code'} param is working perfectly but not with {file: 'local file url'} param.
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeSript({file: "myscript.js"});
});
how do I go about injecting script using the file param to inject my local js script?
does it require absolute file path or relative?
Must file be hosted on the child website?
It seem like a mysterious complicated thing to do as I have a few lines of script and can't embed it all using ref.executeSript({codedetails, callback: "myscript.js"});
I had the same problem. Using cordova3.1.0.
ref.executeScript(
{
file: "http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"
//webURL works fine with 'file'
}, function()
{ 
$.get("js/myscript.js", function(data)
{ //workaround to obtain code using jQuery.get
ref.executeScript(
{
code: data
}, function()
{ 
console.log('ref.executeScript done');
});
});
});
When I set the file URL as webURL http://.... ,
it worked, but I could not figure out how to point the local js file,
so I obtain code strings using $.get "js/myscript.js".
The sample code illustrates: jQuery is already installed on the phonegap App, and also trying to use jQuery on the target inAppBrowser app. Just in case.

Jquery AJAX from remote host

Hi I am trying to get json from a remote host using this piece of code Example at fiddle,
Here i want to add that i am using jquery cross domain ajax plugin
$("button").click(function() {
jQuery.ajax({
url: "http://50.116.19.49/rest/user.json",
type: 'GET',
success: function(result) {
$("div").html(result.responseText);
}
});
});​
I am using jquery AJAX GET method. The problem is when i try to use POST instead of GET it stops working, Need help.!
Thanks
It's possible to limit request by method on server side.
So that doesn't mean If it works with GET than that also must work with POST. As I see your web service doesn't allow origin access for POST method.
Here is an example how it's allowed for different type of request in PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET")
header("Access-Control-Allow-Origin: *");
echo "lan";
else {
echo "disabled";
}
?>

Broken relative Url in jQuery getJSON Ajax Method

The Url for my development environment is:
http://localhost/mysite/blah...
I am using jQuery & getJSON to perform some ajax actions on my site, which work fine all the time I specify the url as:
/mysite/controller/action
..but this is not ideal as I don't want to hardcode my development url into my seperate jQuery include files.
When the site goes live, it'll be fine to have controller/action or /controller/action as the url as that will resolve ok, but for the development site, it's no go.
I've tried:
controller/action
..but this returns a 404, which suprised me as I thought the lack of / at the front of the url would prevent from looking at the website root.
There must be a neat solution to this?
I would do this by inserting a global constant in my HTML header:
<script type="text/javascript">
var BASE_URL = '/mysite/';
</script>
That would be inserted from your server so it can be dynamically changed.
Later in your script, you'll be able to make AJAX requests with (jQuery style here):
$.ajax( BASE_URL + '/controller/action', ...);
If you're in
/mysite/controller/action
then the correct relative path to
/mysite/some_other_controller/some_other_action
is
../../some_other_controller/some_other/action
You can use this code to get the current path of the .js script and use it for calculate your relative path.
var url;
$("script").each(function () {
if ($(this).attr("src").indexOf("[YOUR_SCRIPT_NAME.JS]") > 0) {
url = $(this).attr("src");
url = url.substr(0, url.lastIndexOf("/"));
return false;
}
});
var final_url = url + "/your_target_script.js"
Replace YOUR_SCRIPT_NAME with the unique name of your script.

Resources