axios post server does not receive data from browser - axios

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)

Related

Issue with fetch PHP not getting POST data

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?

Authentication in header with REST API

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));

Better solution on PDF generator for using as a mail attachment in yii2

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.

Mojolicious API not showing JSON data

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.

ZF3 redirect()->toUrl() not redirecting

I'm having a weird issue with ZF3.
I have a vanilla form in the view and a jquery ajax to send it to the controller, something like this:
<form>some form</form>
<script>
$("#form").submit(function (e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "stats",
data: {name: 'TEST'} // name selected in the form
});
});
</script>
The controller for action stats looks like this:
$stat = new Stat();
$route_name = $this->params()->fromRoute('name', 'none');
$post_name = $this->params()->fromPost('name', 'none');
if(!strcmp($route_name, 'none')) // if no redirection yet
{
if(!strcmp($post_name, 'none')) // if no form was sent
{
// display the form to choose the customer
return new ViewModel([
'customer_list' => $stat->get_customer_list(),
]);
}
else // if the form was sent, get name and direct to /stats/someName
{
return $this->redirect()->toRoute('stats', ['name' => 'someName']);
}
}
else // after redirection, get the name in the URL and show some data about this customer
{
return new ViewModel([
'avg_time' => $stat->get_avg_time(rawurldecode($route_name)),
]);
}
The problem is that the redirection does not occure on the screen but I still get the route parameter if I print $route_name after submitting the form.
Anyway, the goal is to have a form with a select to choose the customer name and load the customer data into /stats/[name]. Am I going in the wrong direction ? And is the redirection issue a bug or my code is wrong ?
So there I solved it thx to rkeet, this is the form & jquery:
<form id="customer_choice" method="POST" action=""> some form </form>
<script>
$("#customer_choice").submit(function () {
$("#customer_choice").attr('action', 'stats/' + $("#customer_select").val())
});
</script>
And this is the controller (hope no customer is named 'none'):
$stat = new Stat();
$name = $this->params()->fromRoute('name', 'none');
if(!strcmp($name, 'none'))
{
return new ViewModel([
'customer_list' => $stat->get_customer_list(),
]);
}
else
{
return new ViewModel([
'avg_time' => $stat->get_avg_time($name),
]);
}
The result is basepath/stats/[customer name] and changing the url manually works as well.
(if you don't want changing the url manually to change the result, use fromPost instead of fromRoute)