I am trying to send some data from Dart to PHP...
This is the code i am using to send the data from Dart:
button.onClick.listen((e) {
var req = new HttpRequest();
req.onReadyStateChange.listen((HttpRequestProgressEvent e) {
if (req.readyState == HttpRequest.DONE) {
print('Data submitted!');
}
});
req.open('POST', form.action);
req.send('hello from dart');
});
In my PHP file I am trying to use the string i have send from dart, but count($_POST) returns 0. $_POST seems to be empty...
Dart code DOES trigger the php script and 'Data submitted' is printed...
This is actually related to your PHP configuration. You can access the POST'd data with PHP's reserved variable: $HTTP_RAW_POST_DATA However the preferred method is to use php://input
I am very new to Dart, but you can use FormData in the send. So a quick and dirty way could be.
var data_form = new FormData(query('#My_form'));
button.onClick.listen((e){
var request = new HttpRequest():
request.open('POST', 'http://Localhost/form_data.php');
request.send(data_form);
Related
ColdFusion being as obscure as it is, Twilio doesn't have any SDKs for it. I'm trying to give Synch a go; I'm not getting the JSON request for the access token correct. Trying to mimic what is done by their node.js example here, I thought I could just output the JSON to the page on token.cfm:
{
"identity":"#Username#",
"token":["#AccountSID#","#APPSID#","#SECRET#"]
}
This is called from index.cfm:
<script src="js/jquery.js" ></script>
<script src="https://media.twiliocdn.com/sdk/js/sync/releases/0.5.7/twilio-sync.min.js"></script>
<script>
function fetchAccessToken(handler) {
// We use jQuery to make an Ajax request to our server to retrieve our
// Access Token
$.getJSON('token.cfm', function(data) {
// The data sent back from the server should contain a long string, which
// is the token you'll need to initialize the SDK. This string is in a format
// called JWT (JSON Web Token) - more at http://jwt.io
console.log(data.token);
// Since the starter app doesn't implement authentication, the server sends
// back a randomly generated username for the current client, which is how
// they will be identified while sending messages. If your app has a login
// system, you should use the e-mail address or username that uniquely identifies
// a user instead.
console.log(data.identity);
handler(data);
});
}
$(document).ready(function()
{
fetchAccessToken(initializeSync);
function initializeSync(tokenResponse) {
var syncClient = new Twilio.Sync.Client(tokenResponse.token);
// Use syncClient here
}
});
</script>
The response I receive is
{code: 400, message: "Unable to process JSON"}
code:
400
message:
"Unable to process JSON"
Can I accomplish this? Or, alternately, can the token be built by JavaScript alone?
Your JS is a very roundabout way of writing this:
$(function() {
$.get('token.cfm').done(function (response) {
var syncClient = new Twilio.Sync.Client(response.token);
// ... use syncClient here
});
});
but this still requires that the response is actually parseable as JSON.
If your CFM page just contains this:
<cfoutput>
{
"identity":"#Username#",
"token":["#AccountSID#","#APPSID#","#SECRET#"]
}
</cfoutput>
then this almost certainly produces syntactically wrong JSON. Don't do that.
JSON is to be produced from a data structure and a serialization function, that's no different in ColdFusion than in any other language.
<cfset AccountSID = "...">
<cfset APPSID = "...">
<cfset SECRET = "...">
<cfset tokenData = {
"identity" = Username,
"token" = [AccountSID, APPSID, SECRET]
}>
<cfcontent type="application/json"><cfoutput>#SerializeJSON(tokenData)#</cfoutput>
There are other, nicer ways of creating JSON responses, most prominently CF components with functions annotated with the "json" returnformat, but doing it manually like above is enough for a one-off.
I have a Silverlight application that uses Web API to upload a document that is stored in a Database as a Filestream. Currently it's done by a POST with a Content-Type: application/json. The object containing a byte array of the File along with some metadata about the file is serialized to JSON and posted to the Web API. Web API then saves the byte array as a Filestream to the Database.
Following is a sample of the current request:
{"FileContent":"JVBERi0xLjUNJeLjz9MNCjEwIDAgb2JqDTw8L0xpbmVhcml6ZWQgMS9MIDI3MTg2L08gMTIvRSAyMjYyNi9OIDEvVCAyNjg4NC9IIFsgNDg5IDE2OF0+Pg1lbmRvYmoNICAgICAgICAgICAgICAgICAgDQoyNyAwIG9iag08PC9EZWNvZGVQYXJtczw8L0NvbHVtbnMgNC9QcmVkaWN0b3IgMTIg0K","ProductId":"85c98324-092a-4d10-bab0-03912e437234","OrderId":"7b826322-7526-4a69-b67c-5c88a04f4c60","FileName":"test.pdf","FileType":1,"FileDescription":"test"}
I would like to change this logic to Post as a Content-Type of Multipart. What would be the best way to form my request? Also, what's the best way to structure my Web API Controller to process the Multipart request?
This is a sample for a Multipart upload.
[HttpPost]
[Route("upload")]
public async Task<IHttpActionResult> Upload()
{
MultipartFileData file = null;
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
return UnsupportedMediaType();
}
// initialize path and provider
string root = HttpContext.Current.Server.MapPath("~/App_Data");
if (Directory.Exists(root) == false) Directory.CreateDirectory(root);
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
try
{
// we take the first file here
file = provider.FileData[0];
// and the associated datas
int myInteger;
if (int.TryParse(provider.FormData["MyIntergerData"], out myInteger) == false)
throw new ArgumentException("myInteger is missing or not valid.");
var fileContent = File.ReadAllBytes(file.LocalFileName);
// do something with your file!
}
finally
{
// get rid of temporary file
if (file != null)
File.Delete(file.LocalFileName);
}
// successfull!
return NoContent();
}
This is a sample I got from an API of mine. You can have multiple files for each upload (check the provider.FileData array), and different datas inside the provider.FormData array.
For the client side aspect of this I suggest you to check this answer for a sample of a JS call to this API.
Hope it helps!
i have installed rtMedia on my web-site(which i have already installed buddypress) and now i’m trying to write an android application using the api of rtMedia but when i try to do a request like http://example.com/rtmedia_api/wp_login/?username=USER&password=PASS it display me “NOT FOUND”.
I have also tryed using the endpoint, like this http://example.com/wp-admin/admin-ajax.php/rtmedia_api/wp_login/?username=USER&password=PASS in this case it display me “0″.
I don’t understand how to use this api with json code to do json request.
I use also other plugin which have api and to perform a request i just need to type something like this http://example.com/api/?json=get_recent_posts/?cookie=COOKIE
Why it dosen’t work whith rtMedia api??
(sorry for my bad english :D )
This isn't the way rtMedia API will work.
Please check this doc about rtMedia JSON API.
For any queries regarding rtMedia, you can create a support request here
The rtmedia api plugin requires you to submit it via POST request (even though the confusing 'documentation' tells you otherwise with some functions). The easiest way to go about this is to create a form using the method="POST" and action="yourhost.domain/wordpress/wp-admin/admin-ajax.php". Another way to go about this is by using javascript (which I presume you will be using) and creating a formdata object like so: var formData_rtmedia = new FormData(); and appending (for example wp_login) the strings of your input field like this:
// _(id) is a function that returns document.getElementById(id)
var data1 = _('wp_login_input1').value;
var data2 = _('wp_login_input2').value;
if(data1 != undefined && data1 != '') {formData_rtmedia.append('username', data1);}
if(data1 != undefined && data1 != '') {formData_rtmedia.append('password', data2);}
Using the if dataX not equals undefined and not equals empty string check ensures the fields that are optional can be empty and won't populate the postdata object with empty or null values. The object can be sent using ajax (aka an XMLHttpRequest object) like this:
var xhr;
function ajax(method, url, async, formData) {
if(window.XMLHttpRequest) {xhr = new XMLHttpRequest();}
else {xhr = new ActiveXObject('Microsoft.XMLHTTP');}
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status != 200) {/* handle error */}
else {/* handle response */}
} else {
// display ajax loader or do something fancy
}
}
xhr.open(method, url, async);
xhr.send(formData);
}
and calling it in your rtmedia javascript file like so: ajax('POST', url, true, formData_rtmedia);
I am implementing socket.io server in node js (socketio.js) for my windows azure project. My worker role is in c#. And am sending a brokered message from worker role to socketio.js through service bus queue. But The object which am sending through the brokered message is not getting serialized into a json object. I dont know how to access the body of this brokered message in node js.
I can show how am sending the brokered message in the worker role and how am receiving it in the node js script.
The response body of brokered message(i.e message.body)
#rrayOfTestModelHhttp://schemas.datacontract.org/2004/07/Project.Model ☺i)http://www.w3.org/2001/XMLSchema-instance☺
TestModel is the name of the object model which am sending through the brokered message body.
Worker Role:
BrokeredMessage socketioMessage = new BrokeredMessage(messageObject);
WorkerRoleClient.Send(socketioMessage );
Node Js script:
serviceBusService.receiveQueueMessage(queue, function (error, receivedMessage) {
if (!error) {
console.log(receivedMessage);
if (receivedMessage != null) {
var messageBody = receivedMessage.body;
console.log(messageBody);
io.sockets.emit('news', messageBody);
}}
the message body i receive here is some plain unreadable string. And i am sending proper objects from the worker role. Please let me know if any of you have an idea about whats going wrong
Thanks
I finally found a way to de serialize it and getting the json objects.
Worker Role in C#
var recordsMessage = Newtonsoft.Json.JsonConvert.SerializeObject(data);
BrokeredMessage socketMessage = new BrokeredMessage(recordsMessage);
Receiving in Node js:
if (receivedMessage != null) {
var messageBody = receivedMessage.body;
var jsonString = messageBody.substring(messageBody.indexOf('['), messageBody.indexOf("]")+1);
var recordsQueue = JSON.parse(jsonString);
}
Hope this helps someone
I know it's an old ticket but i guess it might help people in the future as it helped me today :).
Instead of using substring from your nodejs app, you have the possibility to directly send the message in string without the automatic serialization.
To do so, use the following code :
using (Stream stream = new MemoryStream())
using (TextWriter writer = new StreamWriter(stream))
{
writer.Write("Start");
writer.Flush();
stream.Position = 0;
queueClient.Send(new BrokeredMessage(stream) { ContentType = "text/plain" });
}
Hope it will help,
Clément
I am also trying to find a reference to help doing this, please check the following link: http://www.rackspace.com/blog/node-swiz-node-js-library-for-serializing-deserializing-and-validating-objects-in-rest-apis/
it shows the serialization and the deserialization using Node JS in any of the requested format (JSON or XML)
let me know if this work with you :)
I am trying to receive and parse a JSON object sent in a POST request using Codeigniter but I cannot "find" it.
This is my controller code:
public function parse () {
$json = $this->input->post();
$json = stripslashes($json);
$json = json_decode($json);
print_r($json);
}
This is my JSON object:
{"data":"value"}
This is the correct way to do it.
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$post = json_decode($this->security->xss_clean($this->input->raw_input_stream));
When you use $this->input->raw_input_stream you can read it multiple times and its basically the same as file_get_contents('php://input'). This works on CI3. I don't know if it works on CI2.
Try this code, it will output an array with all your parameters.
$this->input->raw_input_stream;
$input_data = json_decode($this->input->raw_input_stream, true);
$input_data will return array
Try this instead
$json = $this->input->post('data');
$json = stripslashes($json);
$json = json_decode($json);
print_r($json);
You need to pass in the key of the data variable you want from the post array as an argument to post()
Firze's answer is correct but here is a more elaborated answer. I am not allowed to comment so I am posting it as an answer.
It has to do with CodeIgniter not being able to fetch JSON. jQuery does some under the hood tricks and transforms your data into form-data-x, that's why it works when you don't specify the content type, don't encode your object, or other situations.
If you want a pure JSON the solution is to use $this->input->raw_input_stream to fetch your JSON and decode it using php's json_decode. Check the full answer and code below:
Retrieve JSON POST data in CodeIgniter
controller:
puplic function exam(){
$obj = file_get_contents('php://input');
$edata = json_decode($obj);
echo $edata->name;
}
Go to post man->type->post
url:http://www.exam.com/exam
formate:json
{
"name":"atm fahim"
}
==>send
make sure you have POST data, using $this->input->post() it will always return empty, you should put on the input type name $this->input->post('name_of_input_text')
Are you sure you're POSTing the data and not doing a GET instead? I ran into this issue earlier today (which is how I found this question) and I was doing a POST but using JSONP which seems to be done with a GET.
CodeIgniter has a function called get_post that will get the data from wherever it happens to be.
$this->input->get_post_string('data');
I hope this helps you out.
You can do it manually like so if you'd like.
function get_post($index = '', $xss_clean = FALSE){
if ( ! isset($_POST[$index]) )
{
return $this->get($index, $xss_clean);
}
else
{
return $this->post($index, $xss_clean);
}
}
I know this is an old post, but for others looking, this might be helpful:
On the browser side, I create my data packet using code similar to this pattern:
var form_data = { };
$.each($('#mvt_dialog_form').serializeArray(), function() {
form_data[this.name] = this.value;
});
// add the address data to the payload
var result = {
form_data: form_data,
locations: addressData,
selected_location: selectedLocation
};
// now wrap it all up with a pretty bow
// Seriously, the key:value format is required for codeigniter INPUT class to be able to "see"
var movement = {
movement_dlg: JSON.stringify(result)
};
I then "post" movement to the server.
In the controller, I then use the following logic:
// Perform XSS filtering
$postData = $this->input->post(NULL, TRUE);
$result = json_decode($postData['movement_dlg']);
Just add correct content type to your request header
Content-Type: application/json
In order to use the standard CI methods.
In index.php, insert a couple of lines:
$json = json_decode(trim(file_get_contents('php://input')), true);
if(!empty($json)) {
$_POST = $json;
}
Either implement in the bootstrap.
RIP Codigniter...(
try
json_decode(array($this->input->post()))
OR
$tmp[] = (array)json_decode($this->input->post());
print_r($tmp);