Post JSON data to external URL - php

How do you post JSON data as a url string to an external url (cross domains) and bypass Access Control?
Here is a jquery .ajax post request that won't work sending to an external url because of Access-Control-Allow-Origin:
var json = JSON.stringify(object);
$.ajax({
type: 'POST',
url: externalurl,
data: json,
dataType: 'json',
success: function(data){console.log(data);},
failure: function(errMsg) {
console.log(errMsg);
},
});
I have received a suggestion to POST the data to the same domain and 'pass on the request' to the external domain, though this solution doesn't make sense to me. I am looking for the most secure solution. Any help would be much appreciated.

I did this not too long ago in PHP. Here's an example of "passing the request". (You'll need to enable PHP cURL, which is pretty standard with most installations.)
<?php
//Get the JSON data POSTed to the page
$request = file_get_contents('php://input');
//Send the JSON data to the right server
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://location_of_server.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$data = curl_exec($ch);
curl_close($ch);
//Send the response back to the Javascript code
echo $data;
?>

One way to bypass the Same-Origin policy is to use cURL to do the actual transmitting.
I'll give an example using PHP, but you could easily do this on any server side language.
Set up a script on your server, for example send.php
First you point your ajax to send.php
var json = JSON.stringify(object);
$.ajax({
type: 'POST',
url: send.php,
data: json,
dataType: 'json',
success: function(data){console.log(data);},
failure: function(errMsg) {
console.log(errMsg);
},
});
Then your php script to forward it:
<?php
// Initialize curl
$curl = curl_init();
// Configure curl options
$opts = array(
CURLOPT_URL => $externalscriptaddress,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => 'field1=arg1&field2=arg2'
);
// Set curl options
curl_setopt_array($curl, $opts);
// Get the results
$result = curl_exec($curl);
// Close resource
curl_close($curl);
echo $result;
?>

Related

can not get cUrl response to .ajax() for redirect

I have a php cURL request which is run when .ajax() is run on form submit:
// A sample PHP Script to POST data using cURL
$headers = array(
'Access-Control-Allow-Headers: Authorization',
'x-api-key: xxxxx',
'Content-Type: application/json',
);
$post_data = '{
"user_email": "'.stripslashes($_POST['email']).'",
"user_firstname": "'.stripslashes($_POST['personName']).'",
}';
// Prepare new cURL resource
$crl = curl_init('https://api.examplesite.com/api/site');
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLINFO_HEADER_OUT, true);
curl_setopt($crl, CURLOPT_POST, true);
curl_setopt($crl, CURLOPT_POSTFIELDS, $post_data);
// Set HTTP Header for POST request
curl_setopt($crl, CURLOPT_HTTPHEADER, $headers);
// Submit the POST request
$result = curl_exec($crl);
if(curl_exec($crl) === false) {
echo 'Curl error: ' . curl_error($crl);
} else {
$output = json_decode($result, true);
echo json_encode($output);
}
// close the request
curl_close($crl);
And here's the .ajax() post:
$.ajax({
type: "POST",
url: location.href,
dataType: "json",
data: {
ajaxRequest: 1,
sendDemoEmail: sendDemoEmail,
email: email.val(),
personName: name.length != 0 ? name.val() : 'no_name',
},
success: function (data) { // CANT RETRIEVE SUCCESS
console.log('yes result', data);
$('#result').html(data);
},
error: function (data) { // RUNS ERROR
console.log('no result', data);
$('#result').html(data); // EMPTY
},
The result from cUrl is as follows:
{"errors":[],"messages":[],"site_url":"https:\/\/www.site.com\/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ2ZXJpZmljYXRpb25fY29kZSI6IiQyeSQxMCQzWXQwWlE1d0FGd0ZWaHNFdnZwdm0uQnl4WVNyS29EejlKVTZEQ0xzNnBtUFd1VFA2MFwvSE8iLCJuZXdfdHJpYWxfZ"}
User flow:
submit form with email with .ajax() POST
send data with cUrl to API
retrieve data from API response in cUrl json_decode
use the cUrl API response in my .ajax() POST to redirect to the site_url in the reponse.
I am unable to get a success from the .ajax() POST (it return error) and also unable to also access the site_url in the .ajax() for a redirect after a success. What am I doing wrong here?
Needed to add a exit(); to the PHP cUrl after the curl_close so my JSON response would not include site HTML
// close the request
curl_close($crl);
exit();

get specific data from REST API

I want to get specific data from rest api after user login using cookie auth but I end up with Field 'fieldname' does not exist or this field cannot be viewed by anonymous users.
Below you can see the code I wrote in ajax and php to get data. I know my script is probably awful as I used curl request for the first time so bear with me, I want someone to tell me where I am doing wrong or better explain to me how to get and post data to server with curl and get and specific data display would be appreciated.
$('#user-profile').click(function(){
$.ajax({
type: "POST",
url: "jiraticket.php",
data: $('#login-form').serialize(),
success: function(data){
alert(data);
}
});
});
and here is the script
<?php
session_start();
$url = 'http://base-url/rest/api/2/search?jql=issuetype%20=%20Epic%20AND%20status%20in%20(%22In%20Progress%22,%20Backlog,%20%22On%20hold%22,%20%22To%20Do%22)';
$curl_session = curl_init($url);
curl_setopt($curl_session, CURLOPT_HEADER, 0);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
if(isset($_COOKIE['JSESSIONID']))
$cookie_string='JSESSIONID='.$_COOKIE['JSESSIONID'];
else
$cookie_string="";
curl_setopt($curl_session, CURLOPT_HTTPHEADER, array('Content-Type: application/json' ,'Authorization: Cookie'), array('cookie:'.$cookie_string));
$response = curl_exec($curl_session);
curl_close($curl_session);
if ( !$response ) {
die('Nothing was returned.');
}
$result = json_decode($response, true);
print_r($result);
$response printing "errorMessages":["Field 'issuetype' does not exist
or this field cannot be viewed by anonymous users."]
Well, it means the API does not want to give you the value of issuetype.
Might be a typo or something, but that's not an error with your curl call, it's a problem with the API provider

Send JSON by cURL always returns "No access"

I have this JSON data:
$.ajax({
type: "GET",
url: "http://www.example.com/test.php",
data:"code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
contentType: "application/json; charset=utf-8",
});
To send this data to http://www.example.com/test.php, I have tried with this code:
<?php
//API URL
$url = 'http://www.example.com/test.php';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'data' => 'code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
?>
But, it always retuns No access.
What are wrong in my code? Can you help me to fix it?
Sorry about my English, it is not good. If my my question is not clear, please comment below this question.
First check http://www.example.com/test.php
Ajax system can't be used with full domain name.
so you should use /test.php
Then checking for an error that occurs in your site or target site.
Then the code becomes:
$.ajax({
type: "GET",
url: "/test.php",
data:"code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
contentType: "application/json; charset=utf-8",
success: function(data, textStatus) {
alert(data);
data = $.parseJSON(data);
},
error : function(data, textStatus, error){
alert(data + " : "+ textStatus);
}
});
Without the documentation to look out the only thing I can suggest is to remove the data from the array and just make it key code.
<?php
//API URL
$url = 'http://www.example.com/test.php';
$data = "?code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b"
//Initiate cURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Execute the request
$result = curl_exec($ch);
?>

Send data to a site to obtain a Json with php

I'm having an issue, the thing is that I was reading a json file with jquery, and it was working well, but now I have to make it read it in php, but the thing is that I was using some data to obtain the parts of the json with:
dataString = "id=" + id + "&todos=" + false;
$.ajax({
type: "POST",
url: "http://www.url.com/example",
data: dataString,
dataType: "json",
success: function( data, textStatus, jqXHR) {
And with this I had no problem, since I was sending the data to the site so it can give me the info that I wanted, but I have no clue of how to do it in php, i was trying with
$str = file_get_contents('http://www.url.com/example.json');
$json = json_decode($str, true);
var_dump($str);
But of course the site its returning me nothing since I'm not sending the data
I hope there's a way. Thanks!
You should use curl or fsockopen if the first is not present and cannot be enabled (pretty rare case).
Here how you do that with curl
<?php
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'id' => $id,
'todos' => false
));
$json = json_decode( curl_exec($ch) );
Jonathan Kuhn is right.
Here's an example with stream_context_create:
<?php
$str = file_get_contents('http://www.url.com/example', false, stream_context_create(
array('http' =>
array('method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => 'id=idVal&todos=false'))));
?>

AJAX rerouting from CURL with associative array parameters

I am trying to access another site using a POST request through ajax. So the access flow became :
AJAX request -> PHP CURL -> www.somedomain.com
This is the code for the AJAX request. I guarantee it passes the parameters correctly:
$("#new_access_token").submit(function(ev){
$.ajax({
url : "back_access/access_code.php",
type : "POST",
data: "access_token[app_id]=601&access_token[subscriber_num]="+$("#input-phone-number").val(),
success : function(res){
console.log(res);
}
});
return false;
});
The php curl script is here (access_code.php):
$ch = curl_init();
$url = "http://developer.globelabs.com.ph/oauth/request_authorization";
$data = array("access_token" => array(
'app_id' => $_POST['access_token']['app_id'],
'subscriber_number' => $_POST['access_token']['subscriber_number']
));
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
It returns an error of "500". With the correct parameters in terminal curl and Advanced Rest Client, it returns the page. However, this script does not. How do I control the parameters?
because you are posting multidomensional array so You'd have to build the POST string manually, rather than passing the entire array in .. you should add curl header with a form Type multipart and other relative things like accept , content-length etc
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
if you serialize or jsone_encode the whole field you can send the data but in this case you also need to capture the data and unserialize/json_decode it from server end.

Categories