I have a problem in getting the content/array from web service to my php code. When I type in the url in browser like http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD, then the result in the browser is displayed like this: [ 1.20MYR , 0.39SGD ]. My PHP code looks like this:
$ch = curl_init('http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
echo $content;
Unfortunately, I get nothing use the code above. Looking for help.
Thanks.
UPDATED
$data=array(
'amount'=>1.2,
'fromCurrency'=>'MYR',
'toCurrency'=>'SGD'
);
$data_string = json_encode($data);
$ch = curl_init('http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-type: application/json'));
$content= curl_exec($ch);
curl_close($ch);
$obj = json_decode($content);
echo $obj;
This page contains dynamic content, loaded by JavaScript. You can see it in Google Chrome for example by access view-source:http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD.
If you look closer to the source code of the page (file http://server1-xeon.asuscomm.com/currency/JQuery/app_converter.js) you'll see, that it uses this code to get exchange data under the hood:
$.ajax({type: "POST",
url: "WebService.asmx/YaHOO_CurrencyEx", // important: it's a relative URL!
data: "{amount:" + amount + ",fromCurrency:'" + from + "',toCurrency:'" + to + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {},
success: function (data) {
$('#results').html(' [ ' + amount + from + ' , ' + data.d.toFixed(2) + to + ' ] ');
});
So, actually you can make such request in PHP to avoid access dynamic content on the http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD page.
UPD:
I've added a more complete explanation.
By the time the page on http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD is loaded, a JavaScript code on this page (it means that it's executed on the client side, in a browser, not on your server) parses URL parameters and makes AJAX POST request to the URL http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx. It passes a JSON payload {amount:1.20,fromCurrency:'MYR',toCurrency:'SGD'} and gets a response like this {"d":0.390360}. So, you can just make a direct POST request to the http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx via curl, passing an amount, fromCurrency and toCurrency in JSON body and then decode received JSON response using json_decode($content);.
How data should look? Add this to your code from "UPDATED" and run:
$array["MYR"] = 1.2;
$array["SGD"] = doubleval($obj->d)
// Print simple array (print source for example)
echo "<pre>";
print_r($array);
echo "</pre>";
// Print true JSON-array
print_r(json_encode($array));
In web browser you will see:
Array
(
[MYR] => 1.2
[SGD] => 0.39036
)
{"MYR":1.2,"SGD":0.39036}
Can't understand your problem at this moment.
If you want print only returned value (digits), do it: echo $obj->d;
Related
I'm trying to send a POST request via PHP from AJAX. I checked the API with Postman. It is working fine. But it is not getting executed in PHP. It is not showing up in Network Tab also.
I saw a lot of samples for making a POST Request in Stack Overflow & tried it. But I can't figure out where I'm going wrong ?
I have attached both the JS Code & PHP Code here
JavaScript CODE
function editUser(toid, name, mobile, mail, pin, addr, state, dis, subdis, role, user) {
$.ajax({
type: "POST",
url: "edituser.php",
dataType: 'html',
data: {
id: toid,
fullname: name,
phone: mobile,
email: mail,
address1: addr,
state: state,
district: dis,
subdistrict: subdis,
pincode: pin,
usertype: user,
role: role,
token: apptoken,
},
success: function (response) {
visibility(false);
console.log("Response > > " + response);
if (response.status == "SUCCESS") {
swal("Updated User", " Information Updated Successfully!", "success");
}
loadData();
}
});
}
PHP CODE
<?php
// where are we posting to?
$url = 'http://api.tech.com/api/UpdateUser';
// what post fields?
$fields = array(
'id' => $_POST['id'],
'fullname' => $_POST['fullname'],
'phone' => $_POST['phone'],
'email' => $_POST['email'],
'address1' => $_POST['address1'],
'state' => $_POST['state'],
'district' => $_POST['district'],
'subdistrict' => $_POST['subdistrict'],
'pincode' => $_POST['pincode'],
'usertype' => $_POST['usertype'],
'role' => $_POST['role'],
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
$token = $_POST['token'];
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("AppToken: $token",
"Content-Type: application/x-www-form-urlencoded"));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// execute post
$result = curl_exec($ch);
echo $result;
// close connection
curl_close($ch);
?>
UPDATE:
The request sent to the API ($url) is not showing in the Network Tab. But the request to edituser.php is shown.
I feel like a lot of context is missing here but I have done a lot of stuff like this so I will try to help out with what I do understand.
Here is what I have gathered so far from your question.
You are calling an ajax function in JavaScript that triggers the given PHP code.
The JavaScript is successful in calling this code "per the network screenshot."
The network tab indicates the PHP script returns nothing.
Here are my thoughts on how to move forward.
You appear to be sending all data from your client side JavaScript including a secure pin and token. This is a very bad idea as it mean your users can all see this secure pin and steal it for their own nefarious purposes. Instead store constants like the secure pin in the php code.
If you are expecting to see the curl request in the network tab you are mistaken. The curl request is going from server to server and will never be seen by the client.
If the response tab is empty you may have something as simple as a syntax error or some kind of curl error that you are not capturing.
Add some of this to your request for debugging:
$result = curl_exec($request);
$response_code = curl_getinfo($request, CURLINFO_HTTP_CODE);
echo 'Response code: ' . $response_code;
if(curl_error($request))
{
echo '<br />Curl error: ' . curl_error($request);
}
You should see the response code at least in the "response" tab of the ajax call.
If you still see nothing make sure your PHP configuration is set up to show all warnings and errors, etc and isn't suppressing the information you need.
This question is similar to another one answered, however the solution in that case was to use a country code, which is not feasible for this particular use, as the address is being provided by the user through an input field (so a country may not be provided).
Here is the content of my current request
Request coming from AngularJS:
function getCoordinatesFromApi(address) {
addressApiResponse = $http({
url: 'php/coordinates.php',
method: 'get',
params: {
address: address
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
return addressApiResponse;
}
Request handled in PHP:
$api_maps = 'https://maps.googleapis.com/maps/';
$address = urencode($_GET['address']);
$api_key = 'API_key_here';
$url = $api_maps . 'api/geocode/json?address=' . $address . '&key=' . $api_key;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
curl_close($curl);
echo ($curl_response);
When this is called, I consistently get back a valid response with status: 200, but data is an empty string.
I've checked the validity of the $url being build in PHP and it is ok, accessing that url directly in the browser displays a valid API response with data.
I've also tried using Angular's $http method and that too returns a valid response from the API:
function getCoordinatesFromApi(address) {
addressApiResponse = $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=API_key_here');
return addressApiResponse;
}
For some reason, it's ony the curl method that does not behave as expected. Has any one dealt with this problem?
If you are saying that echo ($curl_response); return nothing even if status is 200, it's because it's encoded JSON!
Please try this :
$decodedresponse = json_decode($curl_response);
//send me what var_dump return so I can hellp you accessing the array!
echo var_dump($decodedresponse);
//You would use as an array DEPENDING ON HOW THE ARRAY IS BUILD OF COURSE
echo $decodedresponse['response']['lat'];
echo $decodedresponse['response']['long'];
try again
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false
here i am supposed to call a web service in php and the return json of the web service is stored in a variable called $response,then i am passing that json to javascript ,here i am parsing the json and depending on the type of the employee and each type have differebt attributes i am alerting all ,when i have did the same function in another page for testing it was working where i have given value to var txt='' by hardcoding , when i have integrated the php web service with the one i havew tried nothing is having ,i am confused there is no error showing with javascript console.
<?php
session_start();
$regid=$_SESSION['product_registration_id'];
//echo $regid;
$details=array(
'product_registration_id'=> "$regid");
//coverting the vlaues collected from form into json
//calling the web service
$url='webservice url';
$data=$details;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($details));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response= curl_exec($ch);
echo ("The Server Response is:" .$response);
curl_close($ch);
json_decode($response);
$json_a=json_decode($response,true);
echo $json_a[expired];
echo $json_a[account_detail][0];
?>
</div>
<script>
var txt = '<?php echo $response ?>';
alert(txt);
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.type);
if(counter.type=="0")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="1")
{
alert(counter.user_name);
alert(counter.name);
alert(counter.password);
alert(counter.email_id);
}
if(counter.type=="2")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.opr_code);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="3")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.machine_type);
alert(counter.activate_status);
alert(counter.machine_name);
alert(counter.entrance_exit_name);
alert(counter.entrance_or_exit);
alert(counter.loc_name);
alert(counter.activation_code);
}
}
</script>
if you want the php array to be an array in javascript you must:
<?php echo json_encode($response) ?>
this does not need to be parsed in javascript, it will already be an array because the echo will return something in the likings of {'message': 'hellew world'} of ['value1','value2'] which in javascript is an array or an object definition.
So remove the parsing in javascript.
If response contains a quote you will get a js syntax error. Nothing from there on will be processed. So... no alerts. Check the response. Escape the quotes.
I have to simulate AJAX request in PHP, exactly as is in jQuery. My current code is here:
Original AJAX call (mustn't be modified)
$.ajax({
type: "POST",
url: "/someFile.php",
data: data,
success: function(response) {
some_code_here;
},
error: function() {
some_code_here;
}
});
Current PHP code - trying to simulate JS's code behaviour above
function _misc_test() {
$data = json_decode("xxx"); // The "xxx" is placeholder for the same string, as is in data var in JS above
$ajaxResponse = _make_post_request('/someFile.php', $data);
print_r($ajaxResponse);
}
function _make_post_request($url, $data) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
And unfortunatelly, the PHP code doesn't seems to generate exactly the same packets like JS code - that's what I need. Can anyone give me a hand please?
EDIT: maybe it's important, that data variable in JS holds complex JS object like this one:
{"options":{"userIP":"89.102.122.16","playerType":"flash","playlistItems":[{"Type":"Archive","Format":"MP4_Web","Identifier":"209 452 80139\/0042","Title":"Nezn\u00e1m\u00ed hrdinov\u00e9","Region":"","SubtitlesUrl":"http:\/\/img2.ceskatelevize.cz\/ivysilani\/subtitles\/209\/209452801390042\/subtitles-1.txt","Indexes":null,"Gemius":{"Param":[{"Name":"materialIdentifier","Value":"209 452 80139\/0042"},{"Name":"testParam","Value":"testValue"}]}}],"previewImageURL":null}}
in js : data: $('form').serialize();
in php :
How to post data in PHP using file_get_contents?
$jsonstr = '{"options":{"userIP":"89.102.122.16","playerType":"flash","playlistItems":[{"Type":"Archive","Format":"MP4_Web","Identifier":"209 452 80139\/0042","Title":"Nezn\u00e1m\u00ed hrdinov\u00e9","Region":"","SubtitlesUrl":"http:\/\/img2.ceskatelevize.cz\/ivysilani\/subtitles\/209\/209452801390042\/subtitles-1.txt","Indexes":null,"Gemius":{"Param":[{"Name":"materialIdentifier","Value":"209 452 80139\/0042"},{"Name":"testParam","Value":"testValue"}]}}],"previewImageURL":null}}';
print_r(
$data = json_decode($jsonstr ,true)
);
$data_url = http_build_query ($data);
$data_url = str_replace("amp;","",$data_url); //fix for & to &
$data_len = strlen ($data_url);
$url = 'http://domain.com/returnPost.php';
$result = file_get_contents ($url, false,
stream_context_create (
array ('http'=>
array ('method'=>'POST'
, 'header'=>"Connection: close\r\nContent-Length: $data_len\r\n"
, 'content'=>$data_url
))
)
);
print_r(
$result
);
in returnPost.php
print_r($_POST);
I have this bit of javascript:
var jsonString = "some string of json";
$.post('proxy.php', { data : jsonString }, function(response) {
var print = response;
alert(print);
and this bit of PHP (in proxy.php):
$json = $_POST['json'];
//set POST variables, THIS IS WHERE I WANT TO POST TO!
$url = 'http://my.site.com/post';
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, "data=" . urlencode($json));
//execute post (the result will be something like {"result":1,"error":"","pic":"43248234af832048","code":"234920348239048"})
$result = curl_exec($ch);
$response = json_decode($result);
$imageHref = 'http://my.site.com/render?picid=' . $response['picid'];
//close connection
curl_close($ch);
echo $imageHref;
I am trying to post data to an external site using a proxy. From there, I append the picid that the site responds with and append it to the URL to get the image URL.
Am I missing something here? I am not getting anything in response and it seems like my data is not even being posted (when I try echo $json after the first line in proxy.php, I get an empty string). Why am I not able to echo the JSON? Is my implementation correct?
Thanks!
In your Javascript code, you are using this :
{ data : jsonString }
So, from your PHP code, should you not be reading from $_POST['data'], instead of $_POST['json'] ?
If necessary, you can use var_dump() to see what's in $_POST :
var_dump($_POST);
Edit after the comment : if you are getting a JSON result such as this :
{"result":1,"error":"","pic":"43248234af832048","code":"234920348239048"}
This is a JSON object -- which means, after decoding it, you should access it as an object in PHP :
$response = json_decode($result);
echo $response->pic;
Note : I don't see a picid element in that object -- maybe you should instead use pic ?
Here too, though, you might want to use var_dump(), to see how your data looks like :
var_dump($response);
try this:
$json = $_POST['data'];
or even better do
var_dump($_POST);
to see what is actually in your post when you start