I made a post request for an api using ajax. I wonder how I can do the same in php.
<script type="text/javascript">
var cbIntegrationId = "xxxxxx"; // I have it
var clientId = "xxxxxxx"; //I have it
var clientSecret = "xxxxx"; //I have it
var tableName = "Test_Database";
//Get access token
$.post(
"https://" + cbIntegrationId + ".caspio.com/oauth/token",
{
grant_type: "client_credentials",
client_id: clientId,
client_secret: clientSecret
},
function(cbAuth){
//Run POST call
$.ajax({
url: "https://" + cbIntegrationId + ".caspio.com/rest/v2/tables/" + tableName + "/records?response=rows",
type: 'POST',
'data': JSON.stringify({"UniqueID":"988"}), //Define record values
headers: {
"Authorization": "Bearer " + cbAuth.access_token, //Extracts the access token from the initial authorization call
"Content-Type": "application/json", //Required, otherwise 415 error is returned
"Accept": "application/json"
},
dataType: 'json',
success: function (data) {
console.log(data.Result); //Check the console to view the new added row
},
error: function(data) {
console.log(data.responseJSON); //Check the console to view error message if any
}
});
}
);
</script>
I did some research but couldn't find anything that would solve my problem. I really need your help.
You can use cURL to call an API using PHP.
So according to your case you are sending data using POST method. So, we can use cURL as follows with some headers,
$apiURL = "https://yourURL";
$uniqueID = "UniqueID:988";
$postData = json_encode($uniqueID); // Encode the data into a JSON string
$authorization = "Authorization: Bearer " . $token; // Prepare the authorization token
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array($authorization, 'Content-Type: application/json', 'Accept : application/json')); // Inject the token into the header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // To get actual result from the successful operation
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Specify HTTP protocol version to use;
curl_setopt($curl, CURLOPT_POST, 1); // Specify the request method as POST
curl_setopt($curl, CURLOPT_URL, $apiURL); // Pass the API URL
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); // Set the posted fields
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
$response = curl_exec($curl); // Here you will get the response after executing
$error = curl_error($curl); // Return a string containing the last error for the current session
curl_close($curl); // Close a cURL session
Hope this helps you!
Related
I'm trying to build a function for firebase to call a url on command via a POST method. I've currently implemented GET methods just fine but the POST method has me scratching my head.
I've got some sample code for calling via fetch but I'm not sure where the parameters in this following snippet need to go:
<?php
$url = 'https://profootballapi.com/schedule';
$api_key = '__YOUR__API__KEY__';
$query_string = 'api_key='.$api_key.'&year=2014&week=7&season_type=REG';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
Here's what my sample code for the POST request looks like:
const apiKey = "myAPIkey";
const url = "https://profootballapi.com/schedule";
const response = await fetch(url, {
method: 'POST',
body: 'api_key'= apiKey, '&year=2018&week=7&season_typeRG';
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}});
if (!response.ok) {/* Handle */}
// If you care about a response:
if (response.body !== null) {
functions.logger.log(response.body);
}
You're pretty close. You just have some syntax level issues in your TypeScript:
curl_setopt($ch, CURLOPT_URL, $url);
You passed in the url correctly.
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
This is just providing an HTTP body to the request You've already attempted this in the fetch, but you have some syntax issues. You should replace the body with this:
body: `api_key=${apiKey}&year=2018&week=7&season_type=REG`
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
This is free. fetch automatically returns the response in response.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
Assuming this code will run on the browser, you won't be able to disable this. It's telling the client to verify the server's SSL certificate. you should avoid disabling this if you can help it.
I tested this code and got somewhat reasonable results in Chrome's debugging tools:
const foo = async function () {
const apiKey = "myAPIkey";
const url = "https://profootballapi.com/schedule";
const response = await fetch(url, {
method: 'POST',
body: `api_key=${apiKey}&year=2018&week=7&season_type=REG`,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});
return response;
}
foo().then(response => console.log(response));
It produces a 500 error, but I suspect this has to do with not having a valid API key. I'll leave it to you to sort out how to submit a valid API request.
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();
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
I am trying to send a post request through PHP cURL to my node.js server to then emit a message to the client. The server is working and setup as follows:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
, qs = require('querystring')
app.listen(8000);
function handler(req, res) {
// set up some routes
switch(req.url) {
case '/push':
if (req.method == 'POST') {
console.log("[200] " + req.method + " to " + req.url);
var fullBody = '';
req.on('data', function(chunk) {
fullBody += chunk.toString();
if (fullBody.length > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy();
}
});
req.on('end', function() {
// Send the notification!
var json = qs.stringify(fullBody);
console.log(json.message);
io.sockets.emit('push', { message: json.message });
// empty 200 OK response for now
res.writeHead(200, "OK", {'Content-Type': 'text/html'});
res.end();
});
}
break;
default:
// Null
};
}
and my PHP is as follows:
$curl = curl_init();
$data = array('message' => 'simple message!');
curl_setopt($curl, CURLOPT_URL, "http://localhost:8000/push");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_exec($curl);
The console says that json.message is undefined. Why is it undefined?
You're using querystring.stringify() incorrectly. See the documentation on querystring's methods here:
http://nodejs.org/docs/v0.4.12/api/querystring.html
I believe what you want is something like JSON.stringify() or querystring.parse(), as opposed to querystring.stringify() which is supposed to serialize an existing object into a query string; which is the opposite of what you are trying to do.
What you want is something that will convert your fullBody string into a JSON object.
If your body simply contains a stringified version of the JSON blob, then replace
var json = qs.stringify(fullBody);
With
var json = JSON.parse(fullBody);
try this code
<?php
$data = array(
'username' => 'tecadmin',
'password' => '012345678'
);
$payload = json_encode($data);
// Prepare new cURL resource
$ch = curl_init('https://api.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($payload))
);
// Submit the POST request
$result = curl_exec($ch);
// Close cURL session handle
curl_close($ch);