Saving Angular expression output in PHP variable - php

How I can save the expression output in a php variable?
I am looking for something like this
$document_id = {{Document.id}};
Thanks

use $http service injecting it to controller.
Use its ajax function ( here i am doing post method, but you can use get - look at documentation of
$http
directive.
.controller('MyCtrl',['$http',function($http){
//your additional code
$http.post('/myurl.php', {param:'Document.id'}).
success(function(data, status, headers, config) {
// execute after succesfully sent
})
}]);
Then create a php file named myurl.php
and in it:
$document_id = $_POST['param'];
The post url 'myurl.php' should reflect current php url, so it depends on application structure. You can also set direct url like: 'localhost:8080/myurl.php'. If you use on same domain it is ok, otherwise you can get origin policy problem.
What is done here is sending through AJAX to server where php interpreter handle it.

Related

Can't get JSON from remote server with AngularJS $http.json/get

I'm having real trouble getting remote JSON file using AngularJS from a remote server, and even when I get it, I can't find a way of using the data.
Here is the angular code:
var artistControllers = angular.module('artistControllers', ['ngAnimate']);
artistControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.json('http://remotehost.mobi/temp.json').
success(function(data){
console.log('success');
console.log(data);
}).
error(function(data, status ){
console.log('error');
console.log('status');
});
}]);
Usually what I get are just all type of errors:
when trying to get dynamic JSON from PHP script, I need to send a
callback, which sometimes works, but the callback fires a function
which is outside the scope, so it is irrelevant for my needs.
when trying to load JSON from a .json file (like in the example)I get
errors.
when using $http.get I always get the cross domain security
message.
I'm looking for a way to load json data from a remote server, generated dynamically by PHP,with angular JS controller and use it inside that controller.
Thanks
You need to change the server to allow CORS (see this) or use $http.jsonp and change the response to JSONP format (JSON body wrapped in a callback function call).
If you do not control the remote server, you can proxy the request through your own server so that it is no longer cross-domain.
A example of a proxy that enables CORS is corsproxy.com
CORE is safer then jsonp cuz it has no way of executing javascript code. On the plus side you get more control over statechange/timeout/progress and abortion with CORS since its now ajax
The only risk now is do you trust corsproxy.com to read the data that are being passed through & the updown?
The only thing you have to do is replace http:// with http://www.corsproxy.com/ (don't think it works for https...)
var artistControllers = angular.module('artistControllers', ['ngAnimate']);
artistControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.json('http://www.corsproxy.com/kinneret.mobi/temp.json').
success(function(data){
console.log('success');
console.log(data);
}).
error(function(data, status ){
console.log('error');
console.log('status');
});
}]);
Thanks for the help. I guess my issue was a bit different, that's why I post this solution.
Evantualy I have added the a new header to allow cross origin to my PHP that dynamically generates the JSON code:
header('Access-Control-Allow-Origin: *');
header('content-type: application/json; charset=utf-8');
This goes right before the function encode and returns the json. Another thing I have added is formatting the JSON before it sent back. I have found that sending the "raw" unformatted JSON back cause unexpected problems. Since PHP 5.4 you can add JSON_PRETTY_PRINT to the json_encode:
echo json_encode($data_array, JSON_PRETTY_PRINT);
In the angular code, I checked many combinations, include #Endless suggestion to use corsproxy.com, but found that after these adjustments you can simply use $http.get .
Hope this helps if anyone encounter strange problems with this cross domain policy.

What's the use of jsoncallback argument in .getJSON()?

In many example code I saw the format of .getJSON() is something like
$.getJSON("url?jsoncallback=?", function(data){
...}
And at back-end the response is written like
$response = $_GET["jsoncallback"]."(".json_encode($orders).")";
echo $reponse
I delete "?jsoncallback=?" from the url and $_GET["jsoncallback"] and square brackets at back-end and it seems that everything still works. So what is the use of that jsoncallback stuff indeed?
If you don't have the jsoncallback=? it will just do normal JSON request not JSONP*. You can do normal JSON request just fine on your own server or a server that sends CORS headers.
* forget about JSONP, this is a fancy name for inserting a script element in your document that runs code from a foreign server but with same authorization as your own scripts. The $_GET["jsoncallback"], makes it a javascript function call like this:
fn({"data": "value"});
This is the code in a script like <script src="http://foreign.org/data?jsoncallback=fn"></script>. As you can see, that's Javascript, not JSON. With this, foreign.org (or someone hacking them) can change their script to do anything with authorization on your page, so be careful when using "JSONP" and prefer CORS JSON.
The callback name is used for JSONP, which is a way to circumvent the same origin policy.
JSON callback can be used to display cross domain data with jQuery. JSONP is used to make cross domain calls since it's not allowed by the same origin policy. Check out the example below.
http://www.9lessons.info/2009/12/display-cross-domain-data-json-callback.html

HTTP get request communication js to PHP doesn't return a result?

So I have a little js program running in a HTML5 canvas and I have a little http get request function in my js. The function itsself works(tested it with quite a few examples on the internet and it worked), but my own webserver doesnt return the right stuff when a request is sent to it.
my PHP looks like this:
<?php echo VVV::getUser()->userID ?>
When I open it in my browser it returns me the correct values the getUser()->userID returns. However when I send a Http request from my js it gets an empty result, however it works when used on various testing pages in the internet, so it must be my PHP or my server that cause this problem. any ideas?
This sounds like a cross-domain AJAX request problem. To solve this you really have just two options:
Have PHP make the cross-domain request. So whatever site that uses your AJAX will make a request to it's own server (like to its own ajax.php script) which then makes a request to your server and then returns it to the client.
Try to use something like easyXDM JavaScript library for cross-domain AJAX requests and see if that helps.
Here is a little sample for a simple cross-domain request (JSONP style):
1) On your server side, change the response to something like:
<?php echo( 'callbackFunc(' . VVV::getUser()->userID . ');' ) ?>
2) On the client side do something like:
function callbackFunc( userId )
{
// Do something with the userId
}
// Create a script tag which will load the call to the callback function
// with the user ID generated by the PHP code.
var s = document.createElement( "SCRIPT" );
s.src = "http://yourserver/yourpath/yourscript.php?maybesome=params";
document.body.appendChild( s );
The code loaded from your server will call callbackFunc() with the user ID.

AJAX query fails due to missing DEFINE variable in PHP

I am new to AJAX/jQuery with PHP.
I am trying to call a PHP script via AJAX using XMLHttpRequest or jQuery. In both cases the call fails because the php file I am calling into contains on the very first row the following check
if (!defined("SOMETHING")) { die("Error. You cannot access this file directly");}
which causes that my call fails, because this variable is not defined in this case as I am calling from the outside. This condition just checks if the caller is the same web application or wheather the call comes from outside (then it will be denied).
Is there a workaround for it without removing this check? Can I somehow set this expected variable using AJAX/jQuery?
Is there a way how to call specific PHP method via AJAX without calling into the whole PHP file?
Thanks in advance
Tomas
Hmm... you can do it, but I am not sure if this is secure or the way you would like it to be.
Your jQuery should post a variable with GET or POST, which you should check on PHP side. If you have received that variable, then define SOMETHING.
Here is your jQuery, using the POST method:
$.post('ajax.php', {SOMETHING: true}, function(ret){
// do whatever you like with the return here
});
Here is your PHP, which will define SOMETHING if it receives a $_POST request with the variable SOMETHING in it.
<?php
if(isset($_POST['SOMETHING'])){
define('SOMETHING', true);
}
if (!defined("SOMETHING")) { die("Error. You cannot access this file directly");}
// do anything you like here
?>

[PHP/JavaScript]: Call PHP file through JavaScript code with argument

I want to call a PHP file but want to pass an argument to the PHP file. Not getting the correct approach, I am attempting to write a cookie and read that cookie when the PHP file loads. But this is also not working. I am using following code to write and read cookie. I just want to test the read cookie function of JavaScript here. I know how to read the cookie value in PHP.
<script>
function SetRowInCookie(NewCookieValue)
{
try
{
alert(NewCookieValue);
document.cookie = 'row_id=' + NewCookieValue;
loadCookies();
}
catch(err)
{
alert(err.description);
}
}
function loadCookies() {
var cr = []; if (document.cookie != '') {
var ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
var cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
alert(cr['row_id']);
}
</script>
I'm not sure what in your code (running on the client's PC) you expect to cause the php script (running on the server) to run. You'll need to invoke the php by making some kind of http request (like get http://yoururl/recheckcookie.php). With at HTTP request, the javascript code on the client to queries the webserver for the output of your recheckcookie.php script. This script can then recheck the cookie, and return some/no output.
Look up XMLHttpRequest or preferably the corresponding JQuery to see how to perform the HTTP request.
Cookies are not the way to transfer variables between client and server. you should append key/variables pairs to your request URL using either a get (querystring) or post method.
jQuery ajax example;
$.get('http://www.myphpserver.com/script.php?row_id=' + NewCookieValue);
I think, you dont need cookies. try it with $.post, where you can define which url will be called, something like:
$.post(url, params, callback_function);
Well I'm not sure what it is you are ultimately trying to achieve but it sounds like using AJAX could be your solution. There is a good tutorial here.
AJAX will basically allow you to call a php script, pass it variables and then use it's output on your webpage.

Categories