Having freshly recorded audio, post it to server - php

I'm writing an app in Laravel which will convert speech to text. Currently, the app records audio and if it has audio is already stored on the server side can convert it to text. My problem is getting the audio to the server so it can be converted. After recording audio the app has a blob encoded as an ogg. How do I go about getting the blob to the server?
Currently, I'm using an ajax request to post the data however, I'm having a hard time accessing the blob on the server side. This is what the ajax looks like:
var fd = new FormData();
fd.append('fname', 'audioBlob');
fd.append('data', e.data);
$.ajax({
type: 'POST',
url: '/getSTT',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
console.log('returned' + data);
});
In the controller I log the data and it looks like:
[2016-12-16 02:12:45] local.INFO: /tmp/php73iL3X
When I log the Request object $request->all() I get:
[2016-12-16 02:12:45] local.INFO: array (
'fname' => 'audioBlob',
'data' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => 'blob',
'mimeType' => 'audio/ogg',
'size' => 4751,
'error' => 0,
)
),
)
Is there a step that I'm missing?
Perhaps a better way to do all this?

Related

Converting an ajax call to a fetch api call and pulling the information into a php function

I'm trying to convert an .ajax call to a fetch call. The ajax works but the fetch pulls a 500 error when I try to pull the data in my wordPress php file.
I'm fairly new to the fetch api and that is why I'm trying to learn it. I have looked at MDN, wordPress site on custom hooks and rest api, searched the web and searched stack overflow. All they talk about is ajax. I don't know if I'm using the wrong search phrase but I have been trying to figure this out for hours and frustrated.
//working ajax in js file
createLike() {
$.ajax({
url: `${universityData.root_url}/wp-json/university/v1/manageLike`,
type: 'POST',
data: {'professorId' : 789},
success: response => {
console.log(response);
},
error: response => {
console.log(response);
}
});
//my conversion to fetch
createLike() {
const data = {
'professorId' : 789,
};
fetch(`${universityData.root_url}/wp-json/university/v1/manageLike`, {
headers: {
'X-WP-Nonce' : universityData.nonce,
'Content-Type' : 'application/json'
},
credentials: 'same-origin',
method: 'POST',
body: JSON.stringify(data),
}).then(function(response){
return response.json();
}).then(response => {
console.log(response);
}).catch(err => console.log(`error : ${err}`))
},
//php file
function createLike($data) {
$professor = sanatize_text_field($data['professorId']);
wp_insert_post(array(
'post_type' => 'like',
'post_status' => 'publish',
'post_title' => '3rd PHP Create Post Test',
'meta_input' => array(
'liked_professor_id' => $professor
)
));
}
function universityLikeRoutes() {
register_rest_route('university/v1', 'manageLike', array(
'methods' => 'POST',
'callback' => 'createLike',
));
}
add_action('rest_api_init', 'universityLikeRoutes');
my error
{code: "internal_server_error", message: "The site is experiencing technical difficulties.", data: {…}, additional_errors: Array(0)}
additional_errors: []
code: "internal_server_error"
data: {status: 500}
message: "The site is experiencing technical difficulties."
__proto__: Object
The key is understanding what $.ajax() does differently than fetch and thus how you have to handle the data differently in wordpress.
$.ajax takes whatever you pass to the data option and converts into the application/x-www-form-urlencoded MIME type by default. $_POST in PHP automatically decodes indexed form variable names, which the WP_REST_Request object makes available to you within your callback as the $data argument.
fetch is different in several ways, you can read about this in several articles online, such as this one. One thing you are doing differently is passing along a serialized JSON string and you are telling your endpoint that the data type is application/json. By design, the wp-json API doesn't by default parse this data for you. But you can access it nevertheless.
Instead of using $data as your callback argument, change it to a WP_REST_Request object. Then you can call the get_json_params method, and access whatever body you passed to the api that way.
For instance, change your PHP callback to the following:
function createLike( WP_REST_Request $request ) {
$data = $request->get_json_params();
$professor = sanitize_text_field( $data['professorId'] );
wp_insert_post( array(
'post_type' => 'like',
'post_status' => 'publish',
'post_title' => '3rd PHP Create Post Test',
'meta_input' => array(
'liked_professor_id' => $professor
)
) );
}

Select2 ajax option using YII Framework

I am using Yii framework on a project and i am using an extension which uses select2 jquery. I am unable to grasp how the implementation for ajax works with this extension or the select2.
My ajax call returns the following json.
[
{"id":"1", "text" : "Option one"},
{"id":"1", "text" : "Option one"},
{"id":"1", "text" : "Option one"}
]
The yii extension enfolds the select2 extension as below
$this->widget('ext.select2.ESelect2', array(
'name' => 'selectInput',
'ajax' => array(
'url'=>Yii::app()->createUrl('controller/ajaxAction'),
'dataType' => 'json',
'type' => 'GET',
'results' => 'js:function(data,page) {
var more = (page * 10) < data.total; return {results: data, more:more };
}',
'formatResult' => 'js:function(data){
return data.name;
}',
'formatSelection' => 'js: function(data) {
return data.name;
}',
),
));
I found a related question from this Question! The link to the extension am using is YII select2 Extention!
So a week later i merged with the answer to this question.
First let me highlight how the select2 ajax or in my case the Yii ESelect Extension.
The ajax options for jquery are the same as for the Eselect Extention i.e. url,type and datatype altho there is a slight difference on the format returned after successfully querying.
As for the result set for Eselect/select2 expects two parameters to be returned. that is
id : data.myOptionsValue;
text : data.myOptionText;
Reference :: https://select2.github.io/options.html#ajax
if we want to customize the format for the result set that is retured we can go a head and extend the plugin by using
'formatResult' => 'js:function(data){
return data.name;
}',
'formatSelection' => 'js: function(data) {
return data.name;
}',
I also had an issue getting my head around how the extention was quering. A look around and i realised that we have two datatype jsonp and json these two datatypes will handle data differently.
Jsonp (json padding) allows sending query parameters when querying. As for my case i am not passing any other parameters e.g an authkey e.t.c. In my case i changed the datatype to json and returning a json with id and text as results. See below my working snippet.
echo CHtml::textField('myElementName', '', array('class' => 'form-control col-lg-12'));
$this->widget('ext.select2.ESelect2', array(
'selector' => '#myElementName',
'options' => array(
'placeholder' => 'Search ..',
'ajax' => array(
'url' => Yii::app()->createUrl('controller/ajaxAction'),
'dataType' => 'json',
'delay' => 250,
'data' => 'js: function(term) {
return {
q: term,
};
}',
'results' => 'js: function(data){
return {results: data }
}',
),
),
));

Remove escape character from Jquery Post

To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
and here is the code on the server:
$remision = json_decode($_POST['rem']);
Now, when I see whats inside of $_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
How can I remove the escape characters ?? thanks in advance for any comment or help :)
I actually just recently had the same issue.
I fixed it by using stripslashes();
This should work ok unless you actually do have slashes in the data.
var_export(json_decode(stripslashes('{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}'), true));
outputs:
array (
'id' => '12',
'fecha' => '2014-06-25',
'ciudad' => 'Manizales',
'camion' => 'NAQ376',
'driver' => '16075519',
'cant' => '0',
'anticipos' =>
array (
0 =>
array (
'type' => '1',
'com' => 'Comment',
'costo' => '1234',
),
),
)
You're calling $.post incorrectly. The second argument is all the POST parameters, it's not an options structure. If you want to pass options, you have to use $.ajax:
$.ajax("updateremission.php", {
data: { rem: jsonRemission },
dataType: "json",
success: function(data, status) {
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
}
});
You shouldn't use processData: false, because that will prevent the parameter from being put into $_POST['rem'].

Send model attributes to Yii controller using ajax

I'm currently using the following code to send an Ajax get request to my controller:
echo CHtml::ajaxLink('clickMe', array('ajax'), array('update'=>'#results'));
This works fine, the controller receives the request and updates the view accordingly.
Now, I want to send in this request attributes of the model, i.e. from model->getAttributes();
How should I do this? Create a JSON object of the attributes and send that with the request?
Just pass 'data' attribute and 'type' if needed:
echo CHtml::ajaxLink('clickMe', array('ajax'), array(
'update' => '#results'
'data' => CJSON::encode($model->attributes),
'type' => 'post',
));
This code just replaces #results contents with json. If you need something different, use 'success' instead of 'update' like this:
echo CHtml::ajaxLink('clickMe', array('ajax'), array(
'success' => 'function (response) {
// do everything you need
}',
'data' => CJSON::encode($model->attributes),
'type' => 'post',
));
Take a look at jquery ajax options for more information.

Multiple jQuery Ajax Requests are getting confused

Running into a problem with some jQuery ajax. I've got three scenarios in which I'd send requests.
Load a user's publications
Move a user's publication categories up or down (i.e move books above articles)
Edit user's publications (i.e. change book to books for a category title)
After testing all the components individually and having them work as well as searching this site I'm pretty certain the issue is with the ajax requests.
The requests are called via button clicks. (i.e. <button onclick="edit_pubs('userid_modifies_action_id');">edit</button>)
The issue I'm getting is that on the page the data is getting sent to the arrays look like the following for each:
Array ( [action] => load [userid] => username ) This is correct
Array ( [action] => load [userid] => Array ( [userid] => username [modifies] => c [action] => dn [id] => Book ) ) This is incorrect
Array ( [userid] => username [modifies] => c [action] => ed [id] => Book ) This is correct.
I cannot figure out why it nests the first array inside the third one.
Just a note, these arrays are the output of print_r ( $_POST ); directly before the die;.
I have the following setup for $.ajaxSetup:
$.ajaxSetup({
url: "ajax_admin_load_pubs.php",
global: false,
type: "post"
});
Here are the ajax functions:
function modify_pubs(action) {
var action_list = action.split('_');
$.ajax({
data : {'kuoid' : action_list[0], 'modifies' : action_list[1],
'action' : action_list[2], 'id' : action_list[3]},
dataType : "text",
success : function(usr) {load_pubs(usr);}
});
}
function load_pubs(usr) {
$.ajax({
// Tested data in either order, the array always appends itself to kuoid.
data : {'action' : 'load', 'kuoid' : usr},
dataType : "text",
success : function(response) {
$('#pub-mod-list').html(response);
}
});
}
function edit_pubs(action) {
var action_list = action.split('_');
$.ajax({
data : {'kuoid' : action_list[0], 'modifies' : action_list[1],
'action' : action_list[2], 'id' : action_list[3]},
dataType : "text",
success : function(response) {
$('#pub-mod-list').html(response);
}
});
}
As always, thanks for any help.
Edit: Since asking, I've found out the answer to the question. It was due to having a print_r($_POST) statement outside of an if statement like it should of been.
It was due to having a print_r($_POST) statement outside of an if statement like it should of been. Thus when using jQuery.ajax the response was capturing that.

Categories