Multiple jQuery Ajax Requests are getting confused - php

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.

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?

Laravel 5.2 - adding to existing session array overwrites existing session

I am attempting to store basket data in a session in Laravel 5 via AJAX but each time I try and push an item to the array stored as the value to 'basket', the existing 'basket' array is overwritten.
Below is my controller method:
public function add(Request $request)
{
$success = false;
if ($request->ajax()) {
$ticket = Ticket::find((int) $request->get('ticket_id'));
if ($ticket) {
if (!$request->session()->has('basket')) {
$request->session()->put('basket', []);
}
$item = [
'attraction.name' => $ticket->attraction->name,
'ticket.quantity' => $request->get('quantity'),
'ticket.price' => $ticket->price,
];
$request->session()->push('basket', [$ticket->id => $item]);
$success = true;
}
}
return response()->json(['success' => $success]);
}
An item is set in the basket session array on the first instance, but I am expecting it to add to this array rather than overwrite when I post more item data over to this method.
The end result I'm looking to achieve is this:
Array
(
[basket] => Array
(
[123] => Array
(
[attraction.name] => Attraction 1
[ticket.quantity] => 2
[ticket.price] => 14.5
)
[456] => Array
(
[attraction.name] => Attraction 2
[ticket.quantity] => 3
[ticket.price] => 12
)
)
)
I've tried using the Session facade equivalent methods, but to no avail :(
Any help would be greatly appreciated. Thanks :)
I had tried array_merge() but again my session was being overwritten. So, after putting my debug hat on yet again, I've found the reason why it was happening.
Session data was not persisting after each request. As my session wasn't being remembered, !$request->session()->has('basket') was always evaluating to true therefore my basket session was being set back to an empty array each time.
I needed to return my request as JSON using the below line in order for my session data to persist. Maybe this is because I have dataType: 'json' as a property in my AJAX call?
return response()->json($request);
I also took your advice and grabbed the basket session array, pushed new data to it and put back into session.
Sorted! Thank you both for your help :)
I experienced a similar issue and discovered that after adding values to the session you need to call
session()->save();

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

Get values from form in an iphone app to a php web appication in get method?

i m trying to to get the request values of form in zend framework
earlier i was using the post method
but the the iphone app is sending me data in get method .
how do i can use it has i was using the post values like
$post = array(
'id'=>'2',
'email'=>'4',
)
i want to get values also in this form value when a form is submitted .
i was using this to get post values
$post = $this->getRequest ()->getPost ();
and i tried this to get get method values
$post = $this->getRequest();
but
i get this error
Cannot use object of type Zend_Controller_Request_Http as array in
this is the full error message
"Zend_Controller_Request_Http Object ( [_paramSources:protected] =>
Array ( [0] => _GET [1] => _POST ) [_requestUri:protected] =>
/platinum-picks/p-picks/index/registration [_baseUrl:protected] =>
/platinum-picks/p-picks [_basePath:protected] => [_pathInfo:protected]
=> /index/registration [_params:protected] => Array ( [controller] => index [action] => registration [module] => default )
[_rawBody:protected] => [_aliases:protected] => Array ( )
[_dispatched:protected] => 1 [_module:protected] => default
[_moduleKey:protected] => module [_controller:protected] => index
[_controllerKey:protected] => controller [_action:protected] =>
registration [_actionKey:protected] => action ) Fatal error: Cannot
use object of type Zend_Controller_Request_Http as array in D:\Program
Files\Zend\Apache2\htdocs\platinum-picks\application\models\User.php
on line 267"
If I understand correctly, you want to get the values passed using GET method and you have done the same successfully with POST values. The only change you need to make in such a scenario is this:
$post = $this->getRequest()->getPost ();
becomes
$get = $this->getRequest()->getParams();
This will also return parameters from other sources:
Retrieves a merged array of parameters, with precedence of userland params (see setParam()), $_GET, $_POST (i.e., values in the userland params will take precedence over all others).
So refer to the manual if this may be a problem for you.
You can find the GET variables using for example:
$this->getRequest()->getParams();
Or, for a specific variable:
$this->getRequest()->getParam('myVar');
This will also search for POST values. To search the GET vars only, use:
$this->getRequest()->getQuery('myVar');

Categories