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'))));
?>
Related
I have an Axios HTTP GET request I'd to convert to PHP cURL.
Axios Request
axios({
method: 'get',
url: 'https://api.sample.com/123456789/',
data: {
apikey: '987654321',
id: '123123',
}
}).then(function ( response ) {
console.log( response );
});
How do I make this request in PHP cURL, sending the apikey and id data, then echoing the response?
cURL I Was Trying
<?php
$url = 'https://api.sample.com/123456789/';
$body_arr = [
'apikey' => '987654321',
'id' => '123123',
];
$data = http_build_query($body_arr);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result_arr = json_decode($result, true);
echo '<pre>';
var_dump( $result_arr );
echo '</pre>';
?>
Result
NULL
when you set data together with method: 'GET', axios will set Content-Type: application/json and.. completely ignore the post data. so the correct translation is:
<?php
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://api.sample.com/123456789/',
CURLOPT_HTTPGET => 1,
CURLOPT_HTTPHEADER => array(
// this is not correct, there is no content-type,
// but to mimic Axios's behavior with setting `data` on GET requests, we send this
// incorrect header:
'Content-Type: application/json'
)
));
curl_exec($ch);
fwiw this feels like an axios bug, it wouldn't surprise me if this changes in a future version of axios.
I am trying to pass the variable from view file to include_player_id in controller file using ajax and execute the function. Here is what I have in hand.
Please help me on this. I spent days to make it but I am not successful in ajax.
View.php
<p><?php echo $ticket->last_name ?></p>
<input type="submit" class="btn-primary" value="<?php echo lang("ctn_474") ?>">
Controller.php
function sendMessage(){
$content = array(
"en" => 'Message'
);
$fields = array(
'app_id' => "XXXXX-XXXXX-XXXXX-XXXXX",
'include_player_ids' => array("XXXXXXXX-XXXXXXXX-XXXXXXXXXX"),
'data' => array("foo" => "bar"),
'large_icon' =>"ic_launcher_round.png",
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
I believe I need something like that
<script>
$(document).ready(function($){
$(".btn-primary").click(function(){
$.ajax({
type: "POST",
datatype:"json",
url: BASE_URL+"/application/controllers/Ticket.php",
data: {
'data':<?php echo $ticket->last_name ?>
},
contentType:'Text',
processData: false,
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
return false;
});
});
</script>
Thanks for edition your post and providing the needed information. Let's assume you have a working HTTP Endpoint (GET) under BASE_URL+"/application/controllers/Ticket.php" (you can verify that it's working if you call the given URL in your browser).
Let's also assume that your sendMessage() function works like expected and does not contains bugs. I'd suggest you alter your Controller.php to something like this for testing purpose:
// static values, so we can be sure we get a predictable result for testing
$response = array['test1', 'test2'];
// rename the variable, return is a keyword and could cause problems
$result["allresponses"] = $response;
$json_result = json_encode( $result);
// comment this line, it will break the JSON.parse
// print("\n\nJSON received:\n");
// echo is just fine
echo $json_result;
// comment this line, it's not necessary
// print("\n");
Now try to call your controller under the given URI in your browser. If everything works fine you should see something like this:
{"allresponses": ["test1", "test2"]}
as result in your browser.
Let's come to the HTML, JS part.
Your button should look like this :
// make this a button not submit - submit is for sending forms
// give the button an ID
<input type="button" class="btn-primary" id="myCoolButton" value="Click me"></input>
And your script could look like:
<script>
$(document).ready(function($){
// bind the function to the ID, otherwise all primary buttons would perform this function
$("#myCoolButton").click(function(){
$.ajax({
// it's a GET endpoint as far as I understand your code, POST if creating new ressources
type: "GET",
datatype:"json",
// enter your working endpoint URL here (the one you tested in your browser)
url: BASE_URL+"/application/controllers/Ticket.php",
error: function(response) {console.log('ERROR '+Object.keys(response)); },
success: function(response) {
console.log(response)
}});
return false;
});
});
</script>
HTH
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);
?>
So I have an AJAX call that I'm using to POST 1 variable to a PHP script I have on a separate server. The PHP takes this variable and returns data based off of what the variable is. This works on all browsers except IE9 and below. IE9 returns data but it's an error saying the variable is missing which to me shows that it isn't sending the data. Below I have the AJAX call I'm making:
(function (jQ) {
var inviteID = '00000000000';
jQ.ajax({
url: 'www.example.com/test.php',
type: 'POST',
dataType: 'json',
cache: false,
data: { classID: inviteID },
error: function (data, status, error) {
jQ('.statusField').append('Failure: ' + data + status + error);
},
success: function (data, status, error) {
jQ('.statusField').append('Success: ' + data);
}
});
})(jQuery);
And below I have the PHP script that's being used:
<?php
//first POST to grab token
function runPost($classID) {
$postdata = array(
'username' => 'username',
'password' => 'password'
);
//open connection
$ch = curl_init();
//set the url, POST data
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/login");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
curl_setopt($ch, CURLOPT_USERAGENT, 'example');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
list($message, $time, $token, $userID) = split(',', $result);
list($one, $two, $three, $four, $five) = split('\"', $token);
$four = json_encode($four);
$four = str_replace('"','',$four);
$secondaryPostData = array(
'token' => $four,
'data' => array( 'invitationID' => $classID
));
//open connection
$chu = curl_init();
//set the url, POST data
curl_setopt($chu, CURLOPT_URL, "https://www.example.com/classID");
curl_setopt($chu, CURLOPT_POST, 1);
curl_setopt($chu, CURLOPT_POSTFIELDS, json_encode($secondaryPostData));
curl_setopt($chu, CURLOPT_USERAGENT, 'example');
curl_setopt($chu, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($chu, CURLOPT_RETURNTRANSFER, 1);
//execute post
$secondResult = curl_exec($chu);
//close connection
curl_close($chu);
return json_encode($secondResult);
}
//Grab classID from javascript
echo runPost(trim($_POST['classID']));
?>
Again, this works fine in everything except IE. I've tried several different methods but everything gives me the same error. The network console in IE shows that the Request body does have the classID in it, but I'm guessing it's just not sending the data to the PHP script. I don't know if I'm missing something that IE needs to send this to the PHP script but any help with this would be GREATLY appreciated.
Have you tried using this ?
$("button").click(function(){
$.post("demo_test.php",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
works for me in chrome and IE.
$.post() is a short hand method for $.ajax();
It does every thing you could do in $.ajax(); when I started having this problem I never used $.ajax(); unless I had to send FormData an entire object off all the field inputs in a form
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;
?>