Remove escape character from Jquery Post - php

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'].

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

Having freshly recorded audio, post it to server

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?

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 }
}',
),
),
));

Converting jQuery using CakePHP's Javascript Helper

I'm having issues converting the following jQuery/AJAX call to CakePHP's JS Helper.
Here is what currently works:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
$("#DatabaseServerId").bind("change", function (event) {
var server_id = $("#DatabaseServerId").val();
$.ajax({
async:true,
dataType:"html",
evalScripts:true,
success:function (data, textStatus) {
$("#DatabaseEnvironmentId").html(data);
},
url:"\/apsportal\/servers\/get_environments/"+server_id
}
);
return false;
});
});
//]]>
</script>
Here is what I have thus far:
$data = $this->Js->get('#DatabaseServerId')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#DatabaseServerId')->event('change',
$this->Js->request(
array('controller' => 'servers', 'action' => 'get_environments'),
array(
'update' => '#DatabaseEnvironmentId',
'async' => true,
'type' => 'html',
'dataExpression' => true,
'evalScripts' => true,
'data' => $data,
)
)
);
The issue is that the parameter passed has an array key specified and narrows the usage of this action.
http://my.domain.com/servers/get_environments?data%5BDatabase%5D%5Bserver_id%5D=36
Since server_id is being used in other models, I would rather have this as generic as possible.
Note: I figure if I standardize to the JS Helper, if something changes in the future, I'll only have to change things once.
Per the comments, I used raw jQuery instead of CakePHP's methods.

jQuery and array of objects

$(document).ready(function () {
output = "";
$.ajax({
url: 'getevents.php',
data: { ufirstname: 'ufirstname' },
type: 'post',
success: function (output) {
alert(output);
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: output
});
}
});
});
I have code like this and if I copy the text verbatim out of my alert box and replace
events: output
with
events: [{ id: 1, title: 'Birthday', start: new Date(1355011200*1000), end: new Date(1355011200*1000), allDay: true, url: 'http://www.yahoo.com/'},{ id: 2, title: 'Birthday Hangover', start: new Date(1355097600*1000), end: new Date(1355097600*1000), allDay: false, url: 'http://www.yahoo.com'},{ id: 3, title: 'Sepotomus Maximus Christmas', start: new Date(1356393600*1000), end: new Date(1356393600*1000), allDay: false, url: 'http://www.yahoo.com/'},]
Everything works just fine. What can I do to fix this problem? I though that using events: output would place the text in that location but it does not seem to be working.
Thank you all kindly in advance for any comments or answers!
Since you haven't given us much information, i'm going to take a shot in the dark and say that the browser is interpreting the json as text. So add a dataType property to the ajax call so that jQuery can parse the return as json.
$.ajax({
url: 'getevents.php',
data: { ufirstname: 'ufirstname' },
type: 'post',
dataType: 'json'
......
If you are getting that string in your alertbox.. You need to use JSON.parse() to parse the string into a javascript Object
change
events: output
to
events: JSON.parse(output)
According to the documentation
An "event source" is anything that provides FullCalendar with data about events. It can be a simple array, an event-generating function that you define, a URL to a json feed, or a Google Calendar feed.
Since version 1.5, Event Objects can have "options" associated with them. However, before you can start specifying options, you must write an Event Object in its extended form. It must be a traditional JavaScript object with properties.
Also your json string has an extra comma at the end
$year = date('Y');
$month = date('m');
echo json_encode(array(
array(
'id' => 111,
'title' => "Event1",
'start' => "$year-$month-10",
'url' => "http://yahoo.com/"
),
array(
'id' => 222,
'title' => "Event2",
'start' => "$year-$month-20",
'end' => "$year-$month-22",
'url' => "http://yahoo.com/"
)
));
The program actually wants this very specific format of json_encode or it does not work. I only figured this out by reading through all of these replies.

Categories