PHP
<?php
header('Content-type: application/json');
$return['ip'] = $_SERVER['REMOTE_ADDR'];
$results[] = array(
'ip' => $return['ip']
);
echo json_encode($results);
?>
jQuery
$.getJSON("http://domain.com/json/",
function(data){
console.log(data.ip);
});
});
But when I run the jQuery I've checked Fire bug and it says the following
GET http://domain.com/json/ 200 OK 81ms
And doesn't respond with the IP that I requested for. Have I missed something?
UPDATED CODE
PHP
<?php
header('Content-type: application/json');
$return['ip'] = $_SERVER['REMOTE_ADDR'];
$results = array(
'ip' => $return['ip']
);
echo json_encode($results);
?>
jQuery
$.getJSON("http://domain.com/json/", function(data){
console.log(data.ip);
});
Firebug Error
SyntaxError: invalid label {"ip":"XXX.XXX.XXX.X"}
An arrow points at the first quotation mark just before the word ip.
You are returning:
[{'ip': 'XXX.XXX.XXX.XXX'}]
But you are treating it as if you are returning:
{'ip': 'XXX.XXX.XXX.XXX'}
You either need to change your JavaScript to console.log(data[0].ip) or change your PHP to: $results = array( ... ); rather than $results[] = array( ... );
Either will fix your problem. :)
Related
I have a SPA (react) that is uses PHP calls to connect to a MongoDB.
Works great.
However, due to 'rules' I need to serve the javascript files from a different server -- a server that supports neither MongoDB nor MongoDB php client. Let's call this server, SERVER_A.
Let's call the server hosting the MongoDB PHP client and the MongoDB, SERVER_B. ('B' for 'backend'... :) )
The solution, I believe, was to build a php 'middleman' on SERVER_A that simply passes data on to SERVER_B. Research shows me that file_get_contents is the tool for this.
So I take my original known-working PHP file, I put it on SERVER_B and rename it to "mongoPatch_backend.php".
<?php
$user = "xxxx";
$pwd = 'xxx';
$filter = [];
if (isset($_REQUEST['needleKey'])) {
$needleKey = $_REQUEST['needleKey'];
$needle = $_REQUEST['needle'];
$filter = [$needleKey => $needle];
}
$newData = $_REQUEST['newData'];
$filter = ['x' => ['$gt' => 1]];
$options = [
'projection' => ['_id' => 0],
'sort' => ['x' => -1],
];
$bson = MongoDB\BSON\fromJSON($newData);
$value = MongoDB\BSON\toPHP($bson);
$manager = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#SERVER_B:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
[$needleKey => $needle],
['$set' => $value],
['multi' => false, 'upsert' => true]
);
$results = $manager->executeBulkWrite('sedwe.users', $bulk);
var_dump($results);
?>
On SERVER_A I then make a new file, dbPatch.php, like so:
<?php
$API = "https://SERVER_B/php/mongoPatch_backend.php?";
if (isset($_REQUEST['needleKey'])) {
$needleKey = $_REQUEST['needleKey'];
$needle = $_REQUEST['needle'];
$filter = [$needleKey => $needle];
}
$newData = $_REQUEST['newData'];
$postData = "needleKey=".urlencode($needleKey);
$postData .= "&needle=".urlencode($needle);
$postData .= "&newData=".urlencode($newData);
// echo $API.$postData;
$data = file_get_contents($API.$postData);
echo $data;
?>
But when I call it, I get nothing echo'd back out of $data.
Any idea why? Remember, the exact same call directly to mongoPatch_backend.php works just fine (but it's a CORS call, so it's not a valid option).
So here is what I've tried:
First, to ensure my AJAX call was still working, I spit out the response to the console. I get nothing.
So I changed the last line of the middleman (dbPatch.php) to echo "Hello World" instead of echo $data and received "Hello World" on the console as expected.
Next, I then changed the last line of my middleman (dbPatch.php) back to echo $data and tried reducing the 'backend' to a simple <?php echo "Hello Back World"; ?> and got nothing on the console.
Next, I go to https://SERVER_B/php/mongoPatch_backend.php in a browser ... and I'm greeted with "Hello Back World" as expected in the browser.
... which leads me to believe something is up with the transferring of info from server to server. Logical call, eh?
Unfortunately, when I try the same thing with just a 'fetch' command, it works perfectly fine:
Here is my 'middleman' (dbFetch.php) script on SERVER_A:
<?php
$API = "https://SERVER_B/php/mongoFetch_backend.php?";
$collection = $_REQUEST['collection'];
$postData = "collection=".urlencode($collection);
$needleID = $_REQUEST['needleID'];
$postData .= "&needleID=".urlencode($needleID);
$data = file_get_contents($API.$postData);
echo $data;
?>
And this is the file on the backend, SERVER_B:
<?php
$user = "xxxx";
$pwd = 'xxxx';
$filter = [];
if (isset($_REQUEST['needleID'])) {
$needleID = $_REQUEST['needleID'];
$filter = ['id'=> $needleID];
}
if (isset($_REQUEST['collection'])) {
$collection = $_REQUEST['collection'];
}
//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#SERVER_B:27017");
// Query Class
$query = new MongoDB\Driver\Query($filter);
$rows = $connection->executeQuery("db_name.$collection", $query);
// Convert rows to Array and send result back to client
$rowsArr = $rows->toArray();
echo json_encode($rowsArr);
?>
Huzzah, this works! ... and it's also proof there doesn't appear to be a problem with the server-to-server communication.
So back to ground zero.
I then go with a very simple newData value -- shorter, but same general layout - stringified json. It works! The data ends up in the database.
So I'm forced to think something is wrong with the data in newData (which is only a few hundred lines of stringified JSON made like this: encodeURIComponent(JSON.stringify(newData)). But, this bears repeating: this works if I skip the middleman.
... and that puts me at a loss. PHP isn't something I understand well... can you help?
EDIT to answer comment:
When I call mongoPatch_backend.php directly on SERVER_B it works (as stated above). I had it echo the $newData and it spits out a stringified JSON version of the variable (not URLencoded).
When I call dbPatch.php, it does not give me anything that was passed back from mongoPatch_backend.
As I said in the OP, if I modify mongoPatch_backend.php to do nothing other than echo "hellow world" I am still unable to log it to console when calling it via the above dbPatch.php file.
EDIT: I also tried putting the two PHP files on the same server and am getting the same results. (ie: both the dbPatch.php and mongoPatch.php files are in the same directory on the same server)
EDIT2: I have done a var_dump from the middleman and I get standard-looking human-readable stringified text back.
I do the same var_dump($_REQUEST['newData']); in the backend file and I get nothing back.
I have created a sample web services, This will return me a Json Data. looks like below.
http://127.0.0.1/Webservices/Oraconnect.php
<?php
header('Content-type: application/json');
$something = array();
array_push($something, array('say' => 'omg', 'dsay' => 'D omg'));
array_push($something, array('say' => 'bla', 'dsay' => 'D bla'));
$cont = array('result'=>$something);
$jsonresult = json_encode($cont);
print_r($jsonresult);
?>
Result:
{
result: [
{
say: "omg",
dsay: "D omg",
},{
say: "bla",
dsay: "D bla",
},
]
}
Now I want validated with UserName, which should take Value and change response accordingly.
something like this.
http://127.0.0.1/Webservices/Oraconnect.php?user=john
How can I add this validation and Change the response accordingly. Appreciate your help, thanks.
you could do something like that
<?php
header('Content-type: application/json');
if($_GET["user"])
{
$user = $_GET["user"];
// write your code that will use the user name
}
else
{
// return error or anything said the user is missing
}
?>
I am using PHP with XAMPP and Dialogflow to create a chat interface. In a simple intent(question) in Dialogflow, I have created a webhook to XAMPP regarding the question 'Who is X' (e.g. Paul, George). Therefore , I place a POST REQUEST in order to have access to the json form of this question in DIalogflow so that I can answer it as I want to. Specifically, the ultimate goal of this is to retrieve some data from a MySQL database in phpMyAdmin about this question and respond for example that 'X is a developer' or 'X is a financial analyst'. This is why wrote a php script which is the following:
<?php
$method = $_SERVER['REQUEST_METHOD'];
// Process when it is POST method
if ($method == 'POST') {
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->result->parameters;
switch($text) {
case 'given-name':
$name = $text->given-name;
$speech = $name . 'is a developer';
break;
default:
$speech = 'Sorry I did not get this. Can you repeat please?';
}
$response = new \stdClass();
$response->speech = "";
$response->displayText = "";
$respone->source = "webhook";
echo json_encode($response);
}
else
{
echo "Method not allowed";
}
?>
However, the output of this program is: Method not allowed.
Paradoxically enough $method has the value 'GET' so it identifies a GET REQUEST while Dialogflow explicitly states at the webhook page that
Your web service will receive a POST request from Dialogflow in the
form of the response to a user query matched by intents with webhook
enabled.
Hence I am wondering: why my php script cannot see and process the POST REQUEST from Dialogflow?
P.S. Questions close to mine are the following: Form sends GET instead of POST, Why is $_SERVER['REQUEST_METHOD'] always GET?.
It doesn't work because $_SERVER['REQUEST_METHOD'] == "GET" by default.
So you program execute the 'else' condition.
You need to submit a request with the POST method to change this value.
You can use
<form method="POST">
[...]
</form>
in your HTML, or
$.ajax({
url : "ajax_url.php",
type : 'POST',
data : 'data='+data,
[...]
});
in your AJAX JS code for example
Here i am doing same like you from below code your Query will be resolved,
index.php
<?php
require 'get_enews.php';
function processMessage($input) {
$action = $input["result"]["action"];
switch($action){
case 'getNews':
$param = $input["result"]["parameters"]["number"];
getNews($param);
break;
default :
sendMessage(array(
"source" => "RMC",
"speech" => "I am not able to understand. what do you want ?",
"displayText" => "I am not able to understand. what do you want ?",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
header('Content-Type: application/json');
$data = str_replace('\/','/',json_encode($parameters));
echo $data;
}
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input["result"]["action"])) {
processMessage($input);
}
?>
get_enews.php
<?php
function getNews($param){
require 'config.php';
$getNews="";
$Query="SELECT link FROM public.news WHERE year='$param'";
$Result=pg_query($con,$Query);
if(isset($Result) && !empty($Result) && pg_num_rows($Result) > 0){
$row=pg_fetch_assoc($Result);
$getNews= "Here is details that you require - Link: " . $row["link"];
$arr=array(
"source" => "RMC",
"speech" => $getNews,
"displayText" => $getNews,
);
sendMessage($arr);
}else{
$arr=array(
"source" => "RMC",
"speech" => "No year matched in database.",
"displayText" => "No year matched in database.",
);
sendMessage($arr);
}
}
?>
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input
When I call webservices and response convert into jsonp format, at that time response come correctly but it is download as a file. File format is not displayed. Just download file. I try below code.
$result = array(
'Result'=>'Error',
'ErrorMessage'=>'Please enter valid Data
);
header('Content-type: application/jsonp');
return json_encode($result);
I also try with echo and print replace of return keyword.
$result = array(
'Result'=>'Error',
'ErrorMessage'=>'Please enter valid Data
);
$this->output->set_content_type('application/json')->set_output(json_encode($result ));
I have a json response in this url, which I have to validate from this site.
I have stuck my head through many solutions,and I don't know what's wrong here.
I am very thankful for any help suggestions.
this is the code
header('Content-type: application/json');
$obj=array();
$UID=isset($_REQUEST['UID'])?$_REQUEST['UID']:'';
if($UID!='')
{
$sound_cloud=getLatestSound($UID);
if($sound_cloud==false)
{
$sound_cloud['status']="No Record Found";
$obj['status']="No Record Found";
}
else
{
$sound_cloud['status']="successfull";
}
}
else
{
$sound_cloud['errors']="required UID";
}
print stripslashes(json_encode($sound_cloud));
exit;
<?php
$json = '{"stream_url":"http://api.soundcloud.com/tracks/74950626/stream?client_id=b45b1aa10f1ac2941910a7f0d10f8e28","title":"Klaypex-Jump","status":"successfull"}';
$arrayval = json_decode($json);
print_r($arrayval);
// OR
$url = 'http://knowyourdj.staging.techliance.com/webservices?action=GetSoundCloud&UID=1';
$json = file_get_contents($url);
$arrayval = json_decode($json);
print_r($arrayval);
?>
Result:
stdClass Object ( [stream_url] => http://api.soundcloud.com/tracks/74950626/stream?client_id=b45b1aa10f1ac2941910a7f0d10f8e28 [title] => Klaypex-Jump [status] => successfull )
use
$json = file_get_contents('http://knowyourdj.staging.techliance.com/webservices?action=GetSoundCloud&UID=1');//fetch contents from server
$json = json_decode($json); // parse fetched contents
if(!empty($josn)){
print_r($json);
}else{
echo 'no result were found';
}
//lets find what we had parse
echo it, not print. just try~
print stripslashes(json_encode($sound_cloud));
=>
echo stripslashes(json_encode($sound_cloud));
------------------ edit
If this isn't a solution, I think this is a kind of same origin policy problem.
double check your url, it should have same domain with web page server.
refrence - same origin policy
use jquery jsonp,
You can make an ajax call with jquery to your php like this
$.ajax({
type:"POST",
url:'/example.php', //your url
data:{'seguros':a, 'esp':esp,'cont':cont}, //your variables
success: function(data){
//handle your answer here
}
});