Hi i've got a problem evaluating json. My goal is to insert json member value to a function variable, take a look at this
function func_load_session(svar){
var id = '';
$.getJSON('data/session.php?load='+svar, function(json){
eval('id = json.'+svar);
});
return id;
}
this code i load session from php file that i've store beforehand. i store that session variable using dynamic var.
<?php
/*
* format ?var=[nama_var]&val=[nilai_nama_var]
*/
$var = $_GET['var'];
$val = $_GET['val'];
$load = $_GET['load'];
session_start();
if($var){
$_SESSION["$var"] = $val;
echo "Store SESSION[\"$var\"] = '".$_SESSION["$var"]."'";
}else if($load){
echo $_SESSION["$load"];
}
?>
using firebug, i get expected response but i also received error
> uncaught exception: Syntax error, unrecognized expression: )
pointing at this
> eval('id = json.'+svar);
I wonder how to solve this
The correct code to use is:
id = json[svar];
You may also want to add alert(svar); to check that svar contains the correct value beforehand.
However, your code still won't work: the func_load_session function will return immediately, before the ajax call finishes and before the id variable is assigned.
what you need to do instead is to perform whatever you want to do with id from the ajax callback function:
function func_load_session(svar){
$.getJSON('data/session.php?load='+svar, function(json){
var id = json[svar];
doSomethingWith(id);
});
}
Also If I understand and have full part of your code Your json comes out like Store["var"]="var" ??
Does not appear valid json
I suggest using php function json_encode()
So php would be
$var = $_GET['var'];
$val = $_GET['val'];
$load = $_GET['load'];
session_start();
if($var){
$_SESSION["$var"] = $val;
echo json_encode(array($var=>$_SESSION[$var])); // or something like that
}else if($load){
echo json_encode(array('load'=>$_SESSION["$load"]);
}
?>
Related
I have created a JSON file which I will use as a datasource for global configurations of the app.
Excerpt from json file
//Have not put the complete json file. No error in the file
{
"loginType":[
{
"name":"Facebook",
"url":"#",
"method":"",
"label":"Continue with Facebook",
"type":"social",
"class":"",
"icon":"",
"callBack_url" : "fbLoginUrl",
"providerButton":"<div class='fb-login-button' data-max-rows='1'
data-size='large' data-button-type='continue_with' data-use-
continue-as='true'></div>"
},
{
"name":"Twitter",
"url":"#",
"method":"logInWithTwitter()",
"label":"Continue with Twitter",
"type":"social",
"class":"",
"icon":"",
"callBack_url" : "twitterLoginUrl",
"providerButton" :""
}
]
}
The callBack_url key in the json file has a variable with a similar name which has a url as its value e.g $twitterLoginUrl = "https://some.site.com/twitter_login?param1"
$jsonData_signIn =json_decode
(file_get_contents(/path/to/oauth2_provider.json));
$oauth2Provider = jsonData_signIn->loginType;
foreach($oauth2Provider as $type){
if($type->type == 'local' ){
echo "{$type->label}";
}
}
For the above, as output for the link I get eg Continue with facebook
echo "{$type->label}";
The reason I am not storing the complete URI is I will generate some parameters dynamically.
Take a look at the manual for variable variables: http://php.net/manual/en/language.variables.variable.php
You basically just wrap the string variable name in ${ } to make it behave like an actual variable.
$fbLoginUrl = 'https://www.facebook.com/v2.10/dialog/oauth?client_id=xxxxxxx&state=xxxxxxx&response_type=code&sdk=php-sdk-5.6.2&redirect_uri=some.site.com/fbLogin.php&scope=public_profile';
$json = '{"callBack_url" : "fbLoginUrl"}';
$decoded = json_decode($json);
echo ${$decoded->callBack_url};
I want to validate a form with php.
Therefor I created a class "benutzer" and a public function "benutzerEintragen" of this class to validate the form:
class benutzer
{
private $username = "";
private $mail = "";
private $mail_check = "";
private $passwort = "";
private $passwort_check = "";
public $error_blank = array();
public $error_notSelected = array();
public $error_notEqual = array();
public function benutzerEintragen () {
$textfields[0] = $this->username;
$textfields[1] = $this->mail;
$textfields[2] = $this->mail_check;
$textfields[3] = $this->passwort;
$textfields[4] = $this->passwort_check;
foreach ($textfields as $string) {
$result = checkFormular::emptyVariable($string);
$error_blank[] = $result;
}
In the function "benutzerEintragen" i filled the variables "username,mail" and so on with the appropriate $_POST entries (not shown in the code above). The call
checkFormular::emptyVariable($string)
just returns "TRUE" if the field is not set or empty otherwise FALSE.
Now when i try to create a new instance of this class, execute the function and get access to $error_blank[0] the array is empty!
if (($_SERVER['REQUEST_METHOD'] == 'POST')){
$BENUTZER = new benutzer();
$BENUTZER->benutzerEintragen();
echo $BENUTZER->error_blank[0];}
So the last line is leading to a "Notice: Undefined offset: 0". It seems to be related to the array structure, because if i do
echo $BENUTZER->mail;
I get any input I wrote in the form, which is correct. Also the foreach loop seems to do the right thing when i run the debugger in phpEd, but it seems like the array "error_blank" is erased after the function is executed.
Any help would be greatly appreciated. Thanks in advance.
There is a scope problem here. You do have a class attribute with the name. Unlike in Java where using a local variable with the same name as a class variable automatically selects the class attribute this is not the case in PHP.
Basically you are saving your output in a local variable which gets discarded once you leave the function. Change $error_blank[] = $result; to $this->error_blank[] = $result; and you should be fine.
First of all this seems overly complicated way to do a simple task, but that wasn't actually the question.
You are creating a new $error_blank variable that is only in function scope. If you wish to use the class variable you should use $this->error_blank[]
I have a code similar to this:
$name = '_DBR'; // This comes from a function call
$this->_Inits['_DBR'] = function () { return get_library('Database')->getConnection('users', 'read'); };
$inits = $this->_Inits[$name];
$result = $inits(); // ERROR: Function name must be a string
return $result;
The error I get is:
Function name must be a string in xxxx
Is there any ways I could use an array to store multiple closures and is there a working way to access them?
I use PHP 5.4.3
This works fine for me in php 5.3.10.
$m = array();
$m['fish'] = function() { print "Hello\n"; };
$f = $m['fish'];
$f();
Yeah, use call_user_func instead.
I am pulling in weather data from a Yahoo weather RSS feed for both London and New York. I'm trying to reduce code duplication by reusing a PHP file which contains functions for pulling in the weather data.
Below is the function I am calling - get_current_weather_data(). This function goes off to various other functions such at the get_city() and get_temperature() functions.
<?php
function get_current_weather_data() {
// Get XML data from source
include_once 'index.php';
$feed = file_get_contents(if (isset($sourceFeed)) { echo $sourceFeed; });
// Check to ensure the feed exists
if (!$feed) {
die('Weather not found! Check feed URL');
}
$xml = new SimpleXmlElement($feed);
$weather = get_city($xml);
$weather = get_temperature($xml);
$weather = get_conditions($xml);
$weather = get_icon($xml);
return $weather;
}
In my index.php I set the URL for the RSS feed as the variable called $sourceFeed.
<?php
$tabTitle = ' | Home';
$pageIntroductionHeading = 'Welcome to our site';
$pageIntroductionContent = 'Twinz is a website which has been created to bring towns together!
Our goal is to bring communities around the world together, by providing
information about your home town and its twin town around the world. Our
site provides weather, news and background information for London and
one of its twin cities New York.';
$column1Heading = 'Current Weather for New York';
$column2Heading = 'Current Weather for London';
$column3Heading = 'Current Weather for Paris';
$sourceFeed = "http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f";
include_once 'header.php';
include_once 'navigationMenu.php';
include_once 'threeColumnContainer.php';
include_once 'footer.php';
?>
I attempt to call the feed in my get_current_weather_data() function using:
(if (isset($sourceFeed)) { echo $sourceFeed; }).
However, I receive the following error
"Warning: file_get_contents() [function.file-get-contents]: Filename cannot be empty in C:\xampp\htdocs\Twinz2\nyWeather.php on line 10
Weather not found! Check feed URL".
If I replace
(if (isset($sourceFeed)) { echo $sourceFeed; })
with the URL for the feed it works but this will stop me from reusing the code. Am I trying to do the impossible or is my syntax just incorrect?
This isset method works fine where used elsewhere like for example the $tabTitle and
$pageIntroductionHeading variables just need for the RSS feed.
Thanks in advance.
The problem is in the following line:
$feed = file_get_contents(if (isset($sourceFeed)) { echo $sourceFeed; });
it has to be:
if(isset($sourceFeed)){ $feed = file_get_contents($sourceFeed); }
And when you call the function, you also have to pass $sourceFeed as function parameter, like that:
get_current_weather_data($sourceFeed);
You're attempting to access a global variable $sourceFeed inside your function. Pass it as a parameter to the function instead:
// Pass $sourceFeed as a function parameter:
function get_current_weather_data($sourceFeed) {
// Get XML data from source
include_once 'index.php';
$feed = file_get_contents($sourceFeed));
// Check to ensure the feed exists
if (!$feed) {
die('Weather not found! Check feed URL');
}
$xml = new SimpleXmlElement($feed);
$weather = get_city($xml);
$weather = get_temperature($xml);
$weather = get_conditions($xml);
$weather = get_icon($xml);
return $weather;
}
And call the function as:
$sourceFeed = "http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f";
$weather = get_current_weather_data($sourceFeed);
Try to make $sourceFeed global like this:
function get_current_weather_data() {
global $sourceFeed
OR
get_current_weather_data($sourceFeed)
Your issue is a variable scope issue. The variable that goes inside of the function is a new variable that is used only for the function. It will inaccessible once the function is returned/completed. So, you need to let the function know what the value is:
function get_current_weather_data( $sourceFeed ) { // this tells the function to
// read that variable when it starts. You also need to pass it when you call the function.
get_current_weather_data( $sourceFeed );
// OR
get_current_weather_data( 'http://myurl.com' );
isset($sourceFeed) will always return false. you are using it in a local scope whereas you define it in the global scope. please read more on variable scopes at http://tr2.php.net/manual/en/language.variables.scope.php.
I am fairly sure that what you have done there will not even parse. It certainly won't parse in PHP 5.2.
$feed = file_get_contents(if (isset($sourceFeed)) { echo $sourceFeed; });
This is not valid. You cannot place an if statement inside a call to a function, and even if that did work, it would not affect the way the function is called.
You can use a ternary expression:
$feed = file_get_contents((isset($sourceFeed)) ? $sourceFeed : '');
...but even this will not help you here, since you have to pass a filename to file_get_contents() or you will get the error you see.
Your approach to this is all wrong, rather than including index.php to define your variable, you should pass the variable to the function as an argument. For example:
function get_current_weather_data($sourceFeed) {
// Get XML data from source
$feed = file_get_contents($sourceFeed);
// Check to ensure the feed exists
if (!$feed) {
die('Weather not found! Check feed URL');
}
$xml = new SimpleXmlElement($feed);
$weather = get_city($xml);
$weather = get_temperature($xml);
$weather = get_conditions($xml);
$weather = get_icon($xml);
return $weather;
}
$Var = new StdClass;
if($_POST['somvar']){
$Var->somvar = $_POST['somvar']
}
else
{
$somevar=''
}
Why is it creating hidden varaible for this statement
"$Var->somvar = $_POST['somvar']"
when i see the view source
How do i persist the state of this variable when moving to next pages
The answer to your second question is probably sessions.
session_start();
$Var = new StdClass;
if($_POST['somvar']){
$Var->somvar = $_POST['somvar']
}
// Objects need to be serialized to be stored in $_SESSION
$_SESSION["Var"] = serialize ($Var);
to access $Var on another page:
session_start();
if (array_key_exists("Var", $_SESSION))
$Var = unserialize($_SESSION["Var"]);
if (!empty($Var->somvar))
echo "Somvar is: ".$Var->somvar;