I'm trying to pass the following JSON object using AJAX, but can't see the data in the log file. How should I look for the 'data' part of my Ajax call in the API?
var jsObject = {
myIds : [1234,5678],
myType : 1
};
$.ajax({
type : "POST",
url : "/myAddress",
dataType: "json",
data : JSON.stringify(jsObject),
contentType : 'application/json',
success: function(data)
{
console.log('Success', data);
},
error: function(data)
{
console.log('Failed', data);
}
});
Here is my API to show the data in the log file:
sub my_sub {
my $c = shift;
my %params = %{$c->req->params};
$c->app->log->debug(Dumper(\%params));
}
And this is what I see in the log file:
$VAR1 = {
'charset' => 'UTF-8',
'pairs' => []
};
Try this: $c->req->json;
Read more in Mojolicious::Controller documentation.
Related
I'm using the following code :-
Javascript :-
var t_sql="SELECT * FROM `compliance_report`;";
const options = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify( {sql: t_sql} )
};
fetch( 'test3.php', options )
.then( response => response.json() )
.then( response => {
console.log(response);
} );
The PHP code is just to echo back the Post data
:-
<?php
$sql=$_POST['sql'];
$au=json_encode($sql);
echo $au;
?>
But all I am getting back is NULL? can anyone tell me what is wrong. I ultimately want to run the query and echo back the result but the server is reporting the $_POST as empty?
I am new to coding and trying to work with my first API in Javascript. I am having some trouble figuring out where to populate an API key and header. It is a POST for sending a small message to an IOT device. The reference is here and the header reference is here.
Here is what I have, but I have replaced my API key with the generic one.
request.open('POST', 'https://dashboard.hologram.io/api/1/devices/messages');
request.setRequestHeader('Content-Type', 'application/json');
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
var body = {
'deviceid': [storedDeviceID],
'protocol': 'TCP',
'port': 80,
'data': 'Hello world!',
'base64data': 'SGVsbG8gd29ybGQhCg=='
};
request.send(JSON.stringify(body));
I really appreciate any help. Thank you.
Hologram provides an API Key which you need to encode in base64 format first then you can use it in your program.
So you can go to base64encode or any other conversion website ( you can encode it programmatically as well ) and there you have to enter -
apikey:YOUR_API_KEY
Then encode it into base64 format which will be something like
ABCDEFGHIJKLMNOpQrstUVW==
Copy it, and use it in your program. Below is an example using Javascript Fetch API -
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic ABCDEFGHIJKLMNOpQrstUVW==");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://dashboard.hologram.io/api/1/links/cellular", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
i used jspdf plugin to generate pdf file and passed to the controller using ajax. In controller i mailed the pdf as body now i want to mail the pdf as attachment.
Is there any better way to generate pdf than jspdf?
I generated pdf using the following code and sent using ajax
<script>
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'a4', true);
source = $('#content')[0];
specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
pdf.fromHTML(
source,
margins.left,
margins.top, {
// y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
},
function (dispose) {
// pdf.save('ticket');
var pdfBase64 = pdf.output();
var email= 'check#email.com';
$.ajax({
'url': baseUrl + '/site/email',
'method': 'post',
'data': {
'pdfBase64': pdfBase64,
'email':email
},
'success': function (result) {
if (!result == 'true') {
notify('Sorry Email NOt sent', 'danger');
} else {
notify('Ticket sent', 'success');
}
},
'error': function (error) {
notify('Server Error. Sorry Email Not Sent', 'danger');
}
});
}, margins
);
// $('#email').val(pdfBase64);
}
</script>
Using following code i sent mail in controller
if (Yii::$app->request->isAjax) {
$post = Yii::$app->request->get();
$email = $post['data']['email'];
$name = 'Smart Bus';
$subject = 'Booked Ticket';
$base64 = $post['data']['pdfbase64'];
$decoded = base64_decode($base64);
Email::sendTo($email, $name, $subject, file_put_contents('invoice.pdf', $decoded));
}
If you asked for another package than jspdf, It would be great if you use TCPDF as it is more stared and used(more famous). Also it is PHP PDF Library (server side) however the jspdf is client side one.
I am using axios.post but the server does not seem to receive the post-data.
This is what I have:
var baseURL = "http://localhost:8888/dbRouting.php";
var body = {
function: 'foo',
id: 'bar',
}
axios.post(baseURL, body)
.then((response) => { console.log( "Data Loaded AXIOS: " + response.data ); })
.catch(function (error) {console.log(error);});
// Data Loaded AXIOS: array(0) {
// }
This jQuery post to the same file, on the other hand, works:
$.post( baseURL, body )
.done(function( data ) {
console.log( "Data Loaded JQUERY: " + data );
});
//Data Loaded JQUERY: array(2) {
//["function"]=>
//string(3) "foo"
//["id"]=>
//string(3) "bar"
//}
The server file (dbRouting.php) is just:
<?php
var_dump($_POST);
?>
Any ideas what might be going on?
This is my way of allowing the back-end which is php to process it via $_POST. This is part of my code in vue inside method section.
Assuming you are post it to a post_url and you have an object, var myObject:
var myObject = {
property: value,
property1: value1,
property2: value2
}
Inside my vue, method section:
updateForm: function( myObject ){
var post_url = (your post url);
axios.post(post_url, makePostReady( myObject ) )
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
Then above(before axios post call) or make it a global function. I created below function to turn any object I want to send as post using axios so that it will form
property=value&poperty1=value1&property2=value2......
Below is the function:
function makePostReady( object )
{
var sentence = "";
for (var key in object) {
sentenceAdd = key + '=' + object[key] + '&';
sentence = sentence + sentenceAdd;
}
//console.log( 'sentence: ' + sentence );
return sentence;
}
After that you can var_dump( $_POST ) at your post_url to check if everything is fine. Then you can process the data as usual.
Hopefully it helps
Below is some picture to help understanding better
It seems a networking issue.
Double check the URL and the port localhost:8888/dbRouting.php on JQuery & Axios demo
Are they exactly the same?
Is your .catch fired on axios? What's the error?
is your server responding on localhost:8888?
Alternatively, you can check your server implementation using a different client (e.g. Postman https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en)
I nearly find the way, how to implenment the REST Style in Zend Framework 2.
But my doubt is, the methods like get(), getList() is working fine, but the update() method id not calling and showing the following error in the html page.
HTML PAGE:
$.ajax({
url: 'http://128.199.233.137/api/v1/tes/74',
data: {"gender":"1","country":"1"},
type: 'PUT',
success: function(result) {
console.log(result);
// Do something with the result
}
});
OPTIONS http://233.102.233.137/api/v1/tes/74 jquery-2.1.3.js:8625 jQuery.ajaxTransport.sendjquery-2.1.3.js:8161 jQuery.extend.ajaxput.html:16 (anonymous function)jquery-2.1.3.js:4430 jQuery.event.dispatchjquery-2.1.3.js:4116 jQuery.event.add.elemData.handle
put.html:1 XMLHttpRequest cannot load http://233.102.233.137/api/v1/tes/74. Invalid HTTP status code 405
MY controller is:
<?php
namespace Tes\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;
use Zend\Http\Response;
class TesController extends AbstractRestfulController
{
//getAction
public function get($id) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT');
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");
$resp = array("method" => "Get", "id" => $id);
return new JsonModel($resp);
}
//updateAction
public function update($id, $data) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT');
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");
$resp = array("method" => "Update", "id" => $id, "data" => $data);
return new JsonModel($resp);
}
}