I am attempting to get my Access database written in VBA to communicate with a MySQL database on my clients website through a set of PHP web services I wrote. I have managed to get the Access db to retrieve data from the MySQL db but can't get it to post anything. I have narrowed the problem down to the fact that my HTTP request isn't sending the arguments I assign it.
Here are some questions and sites I have looked at already. These were not helpful, because the majority weren't dealing with PHP and were instead looking directly at websites, or were dealing with GET rather than POST.
Http Post not posting data
excel vba http request download data from yahoo finance
VBA HTTP GET request - cookies with colons
Pass Parameters in VBA HTTP Post Request
Perform hidden http-request from vba
How can I send an HTTP POST request to a server from Excel using VBA?
http://www.tushar-mehta.com/publish_train/xl_vba_cases/vba_web_pages_services/
https://stackoverflow.com/questions/29190759/vba-oauth2-authentication-http-get-request
VBA ServerXMLHTTP https request with self signed certificate
How can I send an HTTP POST request to a server from Excel using VBA?
Sending http requests with VBA from Word Sending http requests with VBA from Word
My code for VBA is:
Dim strJSONEncodedJob As String
strJSONEncodedJob = "[{""ExpenseID"":""" & astrExpenseIDs(intI) & "}]"
URL = "I removed the URL when posting"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-Type", "application/json"
objHTTP.send (strJSONEncodedJob)
strResponse = objHTTP.responseText
MsgBox strResponse
And my PHP code is:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$json = file_get_contents('php://input');
$data = json_decode($json, true);
$stmt = $conn->prepare("DELETE FROM tblExpenses WHERE ExpenseID=?");
$txtExpenseID = $data['ExpenseID'];
$stmt->bind_param("i", $txtExpenseID);
$stmt->execute();
echo '{"result" : "success"}';
$stmt->close();
$conn->close();
I get the success statement as a msgbox in VBA, as expected, however the record is not deleted from the MySQL db.
Does anyone have a solution?
Thanks in advance.
Update
When I echo $json I get the JSON encoded string, which means the arguments ARE being passed. However, when I echo $data['ExpenseID'] I get a blank msgbox.
Your json-encoded object is an array containing a single object, so if you want to get at that object's properties you'd first have to index it from the array. Something like
$txtExpenseID = $data[0]['ExpenseID'];
(again, I'm not a PHP person so just guessing the syntax)
Related
I have an apache2 server and php file to receive json via POST in my php code like this
$json = json_decode(file_get_contents('php://input'), true);
$mac_ = $json["code"];
$userId_ = $json["msg"];
and saving it to mysql. This work when I send post via python's requests but not when I'm recieving data from API android device. - When I look at the apache log file, there is a connection, so I'm assuming that some data are received, but because I can't touch that API android device I'm not sure if this part $json["code"] has a right parameter. I would like to know a way to save somewhere all recieved data from this part
$json = json_decode(file_get_contents('php://input'), true);
because I can't check it by echo or so
I've got this very odd problem...on my remote web server for this specific application, when I try to receive JSON input (in any way) I either get a NULL or empty ("") return. The odd part about this problem, is that it is working fine on my local machine. And when I say "working fine" what that means is that I can make a request via Postman to my local machine's API endpoint and it does what it's supposed to do. The other odd thing is that on this very web server (in different files, but still this web server), I can receive JSON input just fine.
I have tried different ways of sending the JSON data to this remote server as well. I have raw cURLed the data, I have sent it from Postman, I have sent it from the webhooks app in Zapier, and I have sent it from a different application's webhook functionality. All of these different applications have given me a NULL return on trying to retreive the JSON data. Here's how I'm trying to retrieve it:
// index.php, the API endpoint processing file
<?php
declare(strict_types=1);
require_once '../../vendor/autoload.php';
require_once '../../model/model.php';
use ShinePHP\{Crud, CrudException, EasyHttp, EasyHttpException, HandleData, HandleDataException};
try {
$data = EasyHttp::turnJsonInputIntoArray();
} catch (EasyHttpException $ehe) {
echo json_encode(['status' => 'failure', 'message' => $ehe->getMessage()]);
exit;
}
And this is the turnJsonInputIntoArray() method in the EasyHttp class:
public static function turnJsonInputIntoArray(string $urlToRetrieveFrom = 'php://input') : array {
// Check if JSON is null, if it is, throw EasyHttpException, if not, return the decoded assoc array.
if (json_decode(file_get_contents($urlToRetrieveFrom), true) === null) {
throw new EasyHttpException('No data retrieved from url: '.$urlToRetrieveFrom);
} else {
return json_decode(file_get_contents($urlToRetrieveFrom), true);
}
}
I've var_dumped $_POST (it returned an empty array), $HTTP_RAW_POST_DATA (returned NULL), and file_get_contents('php://input') (returned an empty string). Nothing exists in the nginx error log aside from the custom exception that exists because there is nothing in php://input. Nothing has worked and I really don't know how else to receive my JSON data.
How can I receive JSON data into my PHP script running on a remote server?
I have an android app and am trying to send data to the PHP on the server. The server gets the php data with
$this->get('uname');
$this->get('pass');
We do use codeigniter if that matters
The Java code, inside of an Async method, I currently have is
InputStream response = null;
URLConnection connection = new URL(urls[0]).openConnection();
connection.setRequestProperty("uname" , Username);
connection.setRequestProperty("pass", Password);
response = connection.getInputStream();
When I run this, the code always returns null but it is supposed to return a JSON array either way. I have checked the URL and it is correct. What am I doing wrong? Thanks!
You code should be like this
For your android side ,as mentioned by #Ichigo Kurosaki at Sending POST data in Android
For Codeigniter side , cosider you function name is user_login
function user_login(){
$uname = $this->input->get_post('uname'); //get_post will work for both type of GET/POST request
$pass = $this->input->get_post('pass');
$result=$this->authenticate->actLogin($uname,$pass ); //considering your authenticating user and returning 1,0 array as success/failure
$this->output
->set_content_type('application/json')
->set_output(json_encode($result));
exit;
}
Basic requirement is to know if we can iterate through $_POST when the request body payload has data sent in json format e.g.
{"City":{"countryCode": "IN","regionCode":"KR"}}
We are able to access this only if we send the data as
m={"City":{"countryCode": "IN","regionCode":"KR"}}
We are able to access this using $_POST['m']
The Content-Type is set to default application/x-www-form-urlencoded, when we set this as application/json $_POST is empty/null.
If we try to access this as $_POST instead of $_POST['m'] it returns null/empty.
NB: I am newbie to PHP. Is it possible to create webservices without any library. Without making use of any library can PHP accept the post request with json data.
To get raw POST data (as opposed to having to access individual POST variables such as $_POST['m']), you can use the following wrapper:
$json = file_get_contents('php://input');
You can read the manual on wrappers if you're interested in learning a bit more about them.
This is how i am getting data and saving it to my database.
$return = array();
$data = json_decode(stripslashes($_REQUEST['Data']));
$email = $data->{"paramA"};
$password = $data->{"paramB"};
i think it might help you.
What I'm doing:
I'm writing a custom program in PHP which pulls data via API from an online LMS service. Right now, I'm trying to implement the available single-sign-on functionality.
This part of the program needs to execute a GET request to the API when a button is clicked (via js or php POST or ?) and ultimately redirect the users browser to a URL which is supplied in the response from the API.
The API allows the choice of an XML or JSON response and I would prefer to use JSON but will make do with XML if needed.
From the API documentation on making requests:
All requests listed in this document should contain a content-type
(XML or JSON) in the request header and be prefixed with the following
base Uri: https://api.example.com/v1.svc
E.g. The Uri to GET a list of Users in XML format would be:
Content-Type: text/xml
GET https://api.example.com/v1.svc/users?apikey=MY-KEY&source=MY-APP
Below is what I'm trying to implement:
How to get the a user's LoginKey
Once you have the user id that you want to sign on you need to make a
GET request to /users/{user-id} which will return information about
the user. Included in this is a LoginKey which you can use to redirect
the user's browser to.
eg.
GET
https://api.example.com/v1.svc/users/USER-ID?apikey=YOUR_API_KEY&source=sampleapp
Response from API:
<User>
<Id>abc12345678</Id>
<UserName>rich_demo#example.com</UserName>
<FirstName>Rich</FirstName>
<LastName>Chetwynd</LastName>
.....
<LoginKey>https://demo.example.com/login.aspx?loginkey=xxxzzzyyy777222</LoginKey>
</User>
The <LoginKey> object data is the URL which I need to ultimately redirect the user's browser to.
I am new to working with APIs and have tried a ton of methods which I could not get to work before posting. If you know how to accomplish this I would be very grateful if you shared your knowledge.
Thanks.
From a HTML <form>, use a traditional post (not AJAX) to a PHP script that does this:
if(isset($_POST['userid']))
{
$userId = (int)$_POST['userid'];
$obj = simplexml_load_file('https://api.xxx.com/v1.svc/users/' . $userId . '?apikey=YOUR_API_KEY&source=sampleapp');
if($obj && isset($obj->LoginKey))
{
$loginKey = $obj->LoginKey;
header('Location: ' . $loginKey);
}
else
{
// failed to load the xml
}
}
If you want to do it with JSON you can use file_get_contents() to get the raw JSON from a URL, then use json_decode() to turn it into an object.
Also, if you want to do it via AJAX, you will have to echo the URL with PHP instead of trying to redirect, then have Javascript do the redirect with window.location.href = '...'