I'm using Factory in AngularJS, The Script is
app.factory('GetCountryService', function ($http, $q) {
return {
getCountry: function(str) {
// the $http API is based on the deferred/promise APIs exposed by the $q service
// so it returns a promise for us by default
var url = "https://www.bbminfo.com/sample.php?token="+str;
return $http.get(url)
.then(function(response) {
if (typeof response.data.records === 'object') {
return response.data.records;
} else {
// invalid response
return $q.reject(response.data.records);
}
}, function(response) {
// something went wrong
return $q.reject(response.data.records);
});
}
};
});
My Output Response Screen Shot:
My PHP Script:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$dbname = "xyzData";
$link = mysql_connect("localhost", "Super", "Super") or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $link) or die("Couldn't select database");
$uid = "";
$txt = 0;
$outp = "";
$data = file_get_contents("php://input");
$objData = json_decode($data);
if (isset($objData->token))
$uid = mysql_real_escape_string($objData[0]->token, $link);
else if(isset($_GET['uid']))
$uid = mysql_real_escape_string($_GET['uid']);
else
$txt += 1;
$outp ='{"records":[{"ID":"' . $objData->token . '"}]}';
echo($outp);
?>
I got error_log message is
[18-Mar-2016 21:40:40 America/Denver] PHP Notice: Trying to get
property of non-object in /home/sample.php
I tried both $objData->token and $objData->token[0]. But I got the same error notice. Kindly assist me...
I tried the Solution provided in the Post Notice: Trying to get property of non-object error, But it fails so, I raised 50 Bounty Points for this post. I tried to update my requirement in that post Question https://stackoverflow.com/review/suggested-edits/11690848, But the Edit was Rejected so I posted my requirement as a new Question. Kindly assist me...
The AngularJS is not sending any Object instead it passes the GET element.
Just access the Value by simply using $_GET['uid']
$objData doesn't seem to be an object.
try $objData['token'].
Or echo the object $objData and try to figure out what is its structure.
Related
I understand that similar general questions exist, but none of them follow my specific set of circumstances, and none of them really provide a solution.
Inside the same folder on the server, I have two files: "quiz_maker.php"
and "master_data.php."
I send a JSON object to "master_data.php" from "quiz_maker.php" with the following Ajax code:
if(localStorage.getItem("JSON Question Data Object") != null){
//The JSON object was stringified before saving to localStorage.
var dataString = localStorage.getItem("JSON Question Data Object");
$.ajax({
method: "POST",
url: "master_data.php",
data: { jsonDataObject: dataString },
success: function(msg){
console.log(msg + "\n");
}
});
}
Then, in "master_data.php", I receive it as follows:
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
$masterQuestionData = json_decode($masterQuestionData, TRUE);
//Perform MySQL Queries here.
}
else{
echo "not set";
}
When I run the code on "quiz_maker.php", the Ajax success handler fires, and I receive the string "set" in the console as I would expect. However, if I look at the "master_data.php" file, the string "not set" gets echoed out, and the following notice is displayed:
Notice: Undefined index: `jsonDataObject` in
/home/sites/5a/0/03891393e8/public_html/master_data.php on line 35
Furthermore, all the MySQL queries execute perfectly using the allegedly "undefined index" "jsonDataObject".
What would be the reason why Ajax's success handler fires, gives me the string "set" and all of the queries work, but I get an undefined index notice on master_data.php?
Thank you.
As requested, here is the whole master_data.php file:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
$booleanSuccessfulOne = false;
$booleanSuccessfulTwo = false;
$servername = "[REDACTED]";
$username = "[REDACTED]";
$password = "[REDACTED]";
// Create connection
$link = mysqli_connect($servername, $username, $password, $username);
// Check connection
if (mysqli_connect_error()) {
$alert = "Oops! We're having trouble publishing your questions and
answers right now. Please try again later.";
die($alert);
}
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
// Unescape the string values in the JSON array
$masterQuestionData = $_POST['jsonDataObject'];
// Decode the JSON array
$masterQuestionData = json_decode($masterQuestionData, TRUE);
$maxQuestions = $masterQuestionData["statistics"][0]["totalQuestions"];
for($i = 1; $i <= $maxQuestions; $i++){
$question = $masterQuestionData["block"][$i-1]["question"];
$answer = $masterQuestionData["block"][$i-1]["answer"];
$query = "INSERT INTO `master` (`id`, `question`, `solution`)
VALUES('".$i."', '".$question."', '".$answer."') ON DUPLICATE KEY
UPDATE `id` = '".$i."', `question` = '".$question."', `solution` =
'".$answer."'";
mysqli_query($link, $query);
}
$query = "DELETE FROM `master` WHERE `id` > '".$maxQuestions."'";
mysqli_query($link, $query);
}
else{
echo "not set";
}
There shouldn't be spaces in the item key for localstorage. The rest of my suggestions are in the chat comments.
localStorage.getItem("JSON Question Data Object");
Can you try the following below and let us know what happens? Change all of your getItem() and setItem() to have no spaces.
localStorage.getItem("JSON");
I believe it should fix up this issue because the rest of your ajax & php looks fine.
That said, you can use bracket notation if you want
localStorage['JSON Question Data Object']
how to recognise i am able to log in to rets ?
This is my code and output.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
//date_default_timezone_set('America/New_York');
require_once("vendor/autoload.php");
//$log = new \Monolog\Logger('PHRETS');
//$log->pushHandler(new \Monolog\Handler\StreamHandler('php://stdout', \Monolog\Logger::DEBUG));
$config = new \PHRETS\Configuration;
$config->setLoginUrl('*****************');
$config->setUsername('****');
$config->setPassword('****');
$config->setUserAgent('****');
$config->setRetsVersion('1.7.2');
$config->setOption('disable_follow_location',false);
$config->setOption('use_post_method',true);
$rets = new \PHRETS\Session($config);
$rets->setLogger($log);
$connect = $rets->Login();
var_dump($connect->getBody());
output
Notice:
Trying to get property of non-object in
/var/www/html/glvar/rets/vendor/troydavisson/phrets/src/Parsers/GetMetadata/System.php
on line 26
Fatal error:
Call to a member function attributes() on a non-object in
/var/www/html/glvar/rets/vendor/troydavisson/phrets/src/Parsers/GetMetadata/System.php
on line 26
how can i know from this response that i am login in to rets and
i can get any data.
$config = new \PHRETS\Configuration;
$config ->setLoginUrl(***)
->setUsername(***)
->setPassword(***)
->setRetsVersion(***)
->setOption('use_post_method', false)
->setOption('disable_follow_location', false);
empty($user_agent') ? '' : $config->setUserAgent($user_agent);
empty($user_agent_password) ? '' : $config->setUserAgentPassword($user_agent_password);
$rets = new \PHRETS\Session($config);
$connect = $rets->Login();
if ($connect) {
echo " + Connected\n\n";
return $connect;
} else {
echo" + NotConnected\n\n";
}
Here is an ever better way to make sure.. add the code below you $connect and you should get something like the below.. and any response not an error should indicate a connection and show you what was returned..
$connect = $rets->Login();
print "<pre>";
print_r($connect);
print "</pre>";
This will be returned or some thing similar if you are connected..
PHRETS\Models\Bulletin Object
array {
[body:protected] =>
}
Watch out on the above answer.. I ran it on a live RETS feed and it stopped my program in its tracks.. and printed + Connected... I removed the return $connect and changed the \n to and it ran fine and printed Connected.. but my point is it may appear to work fine but the program will not go past the connection test... so it killed my program dead in its tracks... not sure why?
I would like to find out how a PHP page calls another PHP page, which will return JSON data.
I am working with PHP (UsersView.php) files to display my contents of a website. However, I have separated the MySQL Queries in another PHP (Get_Users.php) file.
In the Get_Users.php, I will have a MySQL statement to query the database for data. It will then encode in JSON and be echo-ed out.
In the UsersView.php, I will call the Get_Users.php in order to retrieve the Users JSON data. The data will then be used to populate a "Users Table".
The thing is, I do not know how to call the "Get_Users.php" from the "UsersView.php" in order to get the data.
Part of UserView.php
$url = "get_user.php?id=" . $id;
$json = file_get_contents($url);
$result = json_decode($json, true);
I am trying to call the file which is in the same directory, but this does not seem to work.
Whole of Get_Users.php
<?php
$connection = mysqli_connect("localhost", "root", "", "bluesky");
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}
$valid = true;
if (!isset($_GET['id'])) {
$valid = false;
$arr=array('success'=>0,'message'=>"No User ID!");
echo json_encode($arr);
}
$id = $_GET['id'];
if($valid == true){
$query = "SELECT * FROM user WHERE id = '$id'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Invalid User ID!");
echo json_encode($arr);
}
}
mysqli_close($connection);
?>
You have a couple of different ways to accomplish this:
You should be able to first set the actual id and then include the Get_Users.php file like this. Notice that you should not echo out the output from Get_Users.php, instead only return the encoded json data using return json_encode($arr);:
// set the id in $_GET super global
$_GET['id'] = 1;
// include the file and catch the response
$result = include_once('Get_Users.php');
You can also create a function that can be called from UserView.php:
// Get_Users.php
<?php
function get_user($id) {
// connect to and query database here
// then return the result as json
return json_encode($arr);
}
?>
// In UserView.php you first include the above file and call the function
include_once('Get_Users.php');
$result = get_user(1);
You could also use file_get_contents(). Notice that you need to make sure so that allow_url_fopen is enabled in your php.ini file for this to work:
$result = file_get_contents('http://example.com/Get_Users.php?id=1');
To enable allow_url_fopen you need to open up your loaded configuration file and set allow_url_fopen=1 and finally restart your webserver.
You could also use curl to achieve the same result:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/Get_Users.php?id=1');
$result = curl_exec($ch);
curl_close($ch);
An ajax request could also be made to get the result. This example uses jQuery:
$(document).ready(function() {
$.get({
url: 'Get_Users.php',
data: 'id=1',
success: function(response) {
// response contains your json encoded data
// in this case you **must** use echo to transfer the data from `Get_Users.php`
}
});
});
Change UsersView.php to like this
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['CONTEXT_PREFIX'];
$url = "get_users.php?id=" . $id;
$url = $actual_link.$url;
$json = file_get_contents($url);
$result = json_decode($json, true);
This will work fine.
I am configuring FullCalendar with a MySQL DB, using PHP to process and return a JSON.
db-connect.php - fetches results from my Db and encodes to JSON.
get-events.php - reads JSON, converts to FullCalendar
json.html - is my front-end calendar view
File contents below, but before reading: db-connect.php successfully outputs JSON that I have verified on JSONLint.
[{"title":"Test new calendar","start":"2015-07-21","end":"2015-07-22"}]
get-events.php is successfully 'reading' db-connect.php as the "php/get-events.php must be running." error message on my front-end view has disappeared (shows if for example it can't establish that db-connect.php is in the directory, or spelling error in file name, etc).
However when I either pass the query via params or check in Firebug console, the JSON array is empty.
/cal/demos/php/get-events.php?start=2015-07-01&end=2015-07-31
returns [] whereas my test calendar entry does fall within these parameters.
I'm convinced it's my db-connect.php that is the error, but I'm scratching my head about it. Relative newbie so I'm sure it's obvious!
db-connect.php
<?php
$db = mysql_connect("localhost:3306","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
mysql_select_db("test",$db);
$result = mysql_query("select * from cal", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['title'] = $row['title'];
$row_array['start'] = $row['start'];
$row_array['end'] = $row['end'];
array_push($json_response,$row_array);
}
echo json_encode($json_response);
mysql_close($db);
?>
get-events.php
<?php
// Require our Event class and datetime utilities
require dirname(__FILE__) . '/utils.php';
if (!isset($_GET['start']) || !isset($_GET['end'])) {
die("Please provide a date range.");
}
$range_start = parseDateTime($_GET['start']);
$range_end = parseDateTime($_GET['end']);
$timezone = null;
if (isset($_GET['timezone'])) {
$timezone = new DateTimeZone($_GET['timezone']);
}
$json = file_get_contents(dirname(__FILE__) . '/db-connect.php');
$input_arrays = json_decode($json, true);
$output_arrays = array();
if (is_array($input_arrays) || is_object($input_arrays))
{
foreach ($input_arrays as $array) {
$event = new Event($array, $timezone);
if ($event->isWithinDayRange($range_start, $range_end)) {
$output_arrays[] = $event->toArray();
}
}
}
echo json_encode($output_arrays);
file_get_contentsdoesn't parse the php file. It will output the programmcode in this case. Add this function to your get-events.php
function loadPhpFile($file) {
ob_start();
include $file;
$content = ob_get_contents();
ob_end_clean();
return $content;
}
And then replace
$json = file_get_contents(dirname(__FILE__) . '/db-connect.php');
with
$json = loadPhpFile(dirname(__FILE__) . '/db-connect.php');
And as a hint: Please use objects (OOP) and mysqli. PHP Mysqli
I'm trying to get data from:
http://natomilcorp.com/api/get-users
But when I try it nothing is working.
$url = "http://natomilcorp.com/api/get-users";
$jsonString = file_get_contents($url);
$obj = json_decode($jsonString);
echo $obj->"username";
I try JQuery but I was not able to make it work.
I will like to get the username, lastseen and datejoined.
If someone could help me with this.
The things that could have gone wrong are:
The website is not responding
The JSON is invalid
There is some error in your code
This code should tell your what is happening:
error_reporting(-1); // Turn on error reporting
$url = "http://natomilcorp.com/api/get-users";
$jsonString = file_get_contents($url);
if ( ! $jsonString) {
die('Could not get data from: '.$url);
}
$obj = json_decode($jsonString);
if ( ! $obj) {
// See the following URL to figure out what the error is
// Be sure to look at the comments, as there is a compatibility
// function there
// http://php.net/manual/en/function.json-last-error-msg.php
die('Something is wrong with the JSON');
}
echo $obj->"username";