Ajax request in WP plugin return 0 - php

I know it's a commun question and I red nearly all the subject about it, but i can't find an answer who fit my case.
I wrote a plugin to add country and languages related (USA->English|Sapnish for example) I am using Class and constructor for the plugin's functions. It is fully working expect the following function :
I get a select in front with all the country, and on change of this select action another function with ajax, the data passed are ok but the response is always returning 0, connected as admin or not.
Here is my ajax :
$('#sel-country-back').change(function(){
var post_id = $(this).val();
change_status(post_id);
})
function change_status(id) {
$.ajax({
url: window.location.origin + '/wp-admin/admin-ajax.php',
data: {
action: 'wmu-display-lang-select',
post_id: id,
},
type: 'post',
success:function(data){
$('#lang-back').html(data);
},
error: function(errorThrown){
$('#lang-back').html('<select name="langBack" id="sel-lang-back"><option value="default" class="no-lang-option">Aucune langue associée</option></select>');
}
});
}
and my function
public function wmu_display_lang_select()
{
if ($_POST['post_id']) {
$id = sanitize_text_field($_POST['post_id']);
$lang = self::getLang($id);
if ($lang !== false) {
$response = array(
'status' => 200,
'content' => $lang
);
}
else {
$response = array(
'status' => 201,
'message' => __('Le fichier demandé n\'existe pas', 'cadwork')
);
}
die(json_encode($response));
}
}
with the action added to the constructor
public function __construct()
{
add_action('admin_menu', array($this, 'wmu_add_menu'));
add_action('wp_ajax_wmu_display_lang_select', 'wmu_display_lang_select');
add_action('wp_ajax_nopriv_wmu_display_lang_select', 'wmu_display_lang_select');
}
I tried to place the add_action outside the class after the class instantiation
$wmu = new WB_MultiLang_URL();
add_action('wp_ajax_wmu_display_lang_select', 'wmu_display_lang_select');
add_action('wp_ajax_nopriv_wmu_display_lang_select', 'wmu_display_lang_select');
but it doesn't seem to work,
Do you have any ideas why ? I think it's a dumb error or mistake somewhere but I can't find it...

Change action: 'wmu-display-lang-select', in your JS request to action: 'wmu_display_lang_select', and it should work.

Related

Front-end AJAX request not working in WordPress

I'm writing a WordPress plugin (using the boilerplate recommended in the official documentation) and I need to incorporate an AJAX request to fill a DataList. I’m following the WP convention of sending my AJAX requests to “admin-ajax.php”.
My problem is that after doing everything “by the book” I can’t get it to work: the response from the server is always 0 (The default one). The server-side method to handle the request is not being triggered. I think it’s not being “hooked” at all. And I know the request enters the “admin-ajax” file.
The weird thing is that when I hook this method to “init” and process all AJAX requests in this function, it works perfectly. So, I’m pretty sure the problem is in the dynamic “wp_ajax_{$action}” and “wp_ajax_nopriv_{$action}” hooks. Any ideas?
Thanks in advance.
Here’s an extract of my code:
PHP
<?php
private function define_public_hooks() {
$plugin_public = new SR_Public($this->get_plugin_name(), $this->get_version());
$this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_scripts');
$this->loader->add_action('wp_ajax_sr_get_titles', $plugin_public, 'process_get_titles');
$this->loader->add_action('wp_ajax_nopriv_sr_get_titles', $plugin_public, 'process_get_titles');
}
public function enqueue_scripts() {
wp_enqueue_script(
$this->plugin_name,
PLUGIN_DIR_URL . 'public/js/sr-public.js',
array('jquery'),
$this->version
);
wp_localize_script(
$this->plugin_name,
'localizedData',
array(
'ajaxUrl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('sr_get_titles'),
)
);
}
public function process_get_titles() {
if ((!empty($_POST['action'])) && ($_POST['action'] === 'sr_get_titles')) {
check_ajax_referer('sr_get_titles');
// Load some data in $some_array...
wp_send_json($some_array);
}
}
JS
jQuery(document).ready(function($) {
"use strict";
var titleInput = $("#sr-title");
var titleDataList = $("#sr-requested-titles");
function ajaxRequest() {
var userInput = titleInput.val();
if (userInput.trim() !== "") {
$.ajax({
type: "POST",
dataType: "json",
url: localizedData.ajaxUrl,
data: {_ajax_nonce: localizedData.nonce, action: "sr_get_titles", user_input: userInput},
success: processSuccessResponse
});
}
}
function processSuccessResponse(data) {
if (data) {
titleDataList.empty();
data.forEach(function(item) {
titleDataList.append($("<option>").val(item));
});
}
}
titleInput.keyup(ajaxRequest);
});

AJAX on success return HTML files instead the data value?

I have this simple AJAX code to get the User Timezone whenever he is successfully login to the dashboard.
JS
<script type="text/javascript">
$(document).ready(function(){
'use strict';
/**
* Getting user current timezone offset
*/
var timezone_offset = new Date().getTimezoneOffset();
timezone_offset = timezone_offset == 0 ? 0 : -timezone_offset;
$.ajax({
type: "POST",
url: "<?php echo base_url('dashboard'); ?>",
data: {"timezone": timezone_offset},
cache: false,
success: function(data){
alert(data);
},
error: function(){
console.log('error');
}
});
});
</script>
Controller
public function index()
{
$data = $this->global_data->logged_user();
$data['page_title'] = 'Dashboard';
$data['page_directory'] = 'pages/dashboard';
$data['greeting'] = $this->global_helpers->greeting() . ' !';
$chart_data = array();
$order_history = $this->trade_history->chart_data();
foreach($order_history AS $d)
{
$chart_data[] = array(
'y' => $this->global_helpers->month_name($d->month) ."' ". $d->year,
'a' => $d->profit,
'b' => $d->loss
);
}
echo $_POST['timezone'];
$data['chart_data'] = json_encode($chart_data);
$this->load->view('template', $data);
}
But the problem is, when it's success why it's return the HTML header? not the data I wish to get?
What do I do wrong here? And I put this AJAX code in footer.php file. Sorry for this silly question but I just got stuck here.
I appreciated any kind of helps, Thanks!
Edited
Sorry for this silly post, I can't use that way, i just need to create another controller for handling any kind of AJAX value, so the problem will be fixed.
Well, you can't render HTML inside an alert anyway.
I see that you ended up solving this issue, but, FYI, if you ever need a controller to return HTML as data, use the third parameter on view method:
echo $this->load->view('template', $data, TRUE);
See more at Codeigniter docs :)

500 Error in Laravel with Ajax post

I've got 6 different routes that can be chosen from an input select. Each selected route then posts to its own database.
The problem is I get a 500 error back for all of them, but on half of them, it actually posts to the database. I've gone through line-by-line, and other than the variable names, the code is identical. Here's an example of one that doesn't work at all.
submit.js
$('#submit-event').on('click', function() {
event.preventDefault()
let title = $('#title').val()
let type = $('#type').val() // for selecting which DB
let start = $('#start').data('DateTimePicker').date()
let end = $('#end').data('DateTimePicker').date()
let data = {
'_token': token,
'title': title,
'start': start,
'end': end
}
console.log(type); // logs the correct POST route
$.ajax({
method: 'POST',
url: type,
data: data,
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err)
}
});
})
routes.php
Route::post('/createmeeting', [
'uses' => 'MeetingController#postCreateMeeting',
'as' => 'createmeeting'
]);
MeetingController.php
class MeetingController extends Controller
{
// Get Meeting from DB - works
public function getMeetings()
{
$meetings = Meeting::orderBy('created_at', 'desc')->get();
return $meetings;
}
// Add new Meeting to DB - doesn't work (500 error)
public function postCreateMeeting(Request $request)
{
if (!request['_token']) {
return redirect()->route('calendar')->with(['message' => "You must be logged in"]);
}
// Save Meeting
$meeting = new Meeting();
$meeting->title = $request['title'];
$meeting->start = $request['start'];
$meeting->end = $request['end'];
if ($request->user()->meetings()->save($meeting)) {
$message = 'Event successfully added to calendar';
return redirect()->route('calendar')->with(['message' => $message]);
}
return redirect()->route('calendar')->with(['message' => $message]);
}
}
Responses to similar problems suggest a problem with the token, but I test for that here. Any idea where the mistake could be happening?

PHP Class private variable misdirected value

first of all, my problem is from my php class called by a php file who is accessed by an AJAX call.
The problem is that the return value is totally wrong and is not the same as the sybase_result value. So what am i missing?
Here are the steps of my program.
First we make the AJAX call:
$.ajax(
{
type: "POST",
url: "ajax/load_fiche_resume.php",
timeout:5000,
dataType: 'json',
data: ({matricule:matricule, id_mun:id_mun}),
beforeSend: function()
{
// Handle the beforeSend event
$('#loading-bar').show("slow");
},
complete: function()
{
// Handle the complete event
$('#loading-bar').hide("slow");
},
success: function(data)
{
console.dir(data);
$('#tab-role').html(formatData(data));
},
error: function ()
{
alert("Oops! Une erreur c'est produite.\nVeuiller rafraichir la page. \nSi cela se reproduit, veuiller contacter le propriétaire du site.");
}
});
Then, we go into the php file load_fiche_resume.php
include('../class/class_role.php');
$oRole = new Role("42025", "2036-94-5034");
$ar_step2 = array(
array("Propriétaire(s)"),
array("Nom(s) : ", $oRole->getProprioNoms() ),
array("Adresse postale : ", $oRole->getProprioAdresse() ),
array("Condition particulière d'inscription : ", $oRole->getProprioCondition() ),
array("Date d'inscription au rôle : ", $oRole->getProprioDateInscription() )
);
If we look closer at the code above, the return value of the function $oRole->getProprioDateInscription() is supposed to be a date. But instead of a date, this function return a string from another get function(i.e.: it will show the valu of $oRole->getProprioNoms) and it is totally wrong.
If we go inside the class $oRole we have this:
class Role
{
private $prop_inscription;
public function getInfoProprio()
{
$qry = "SELECT
p.nom_form AS nom_form,
p.t_typos AS t_typos,
substr(p.d_date_inscr,1,10) AS d_date_inscr,
pga.adr_form AS adr_form,
p.id_adr AS id_adr,
p.id AS id
FROM
ev_dossiers d,
ro_b75 p,
pg_adresses pga
WHERE
d.id_dossiers = ".$this->getIdDossier()." AND
d.typ_donnees = 11 AND
d.id_donnees = p.id AND
p.id_adr = pga.id_adr order by p.id, p.id_adr, p.ordre;";
$this->prop_qry = $qry;
$result = sybase_query($qry, $this->getLinkDB());
$nbr = sybase_num_rows($result);
$typos = sybase_result($result, 0, "t_typos");
if($nbr>0)
{
for($cpt=0; $cpt<$nbr; $cpt++)
{
if($cpt===0)
{
$this->setProprioNoms(utf8_encode(strtr(trim(sybase_result($result, $cpt, "nom_form")),"’","'")));
$this->setProprioAdresse(utf8_encode(strtr(trim(sybase_result($result, $cpt, "adr_form")),"’","'")));
$this->setProprioCondition($this->getConditionInscription(sybase_result($result, $cpt, "t_typos")));
// THIS IS PROBLEMATIC
$this->setProprioDateInscription(sybase_result($result, 0, "d_date_inscr"));
}
else
{
$this->setProprioNoms(", ".utf8_encode(strtr(trim(sybase_result($result, $cpt, "nom_form")),"’","'")));
}
}
}
}
...
public function getProprioDateInscription()
{
return $this->prop_inscription;
}
private function setProprioDateInscription($date)
{
$this->prop_inscription = $date;
}
}
If we have look at the line where we have this : $this->setProprioDateInscription(sybase_result($result, 0, "d_date_inscr"));
The sybase_result return a date (it's all OK from the database and the value is good). But the problem is between the Setter and the Getter of the private var prop_inscription.
Can you help me? Do you know where is the problem from?
Thank you very much.
To resolve this,
juste change this line
// THIS IS PROBLEMATIC
$this->setProprioDateInscription(sybase_result($result, 0, "d_date_inscr"));
to
$this->setProprioDateInscription(utf8_encode(strtr(trim(sybase_result($result, $cpt,"d_date_inscr")),"’","'")));

How do I use the PUT feature in REST

Using this git-hub library:
http://github.com/philsturgeon/codeigniter-restserver
How do I use the PUT feature to save its data?
example: example.com/put/some-data/some-data/...
you can use it like this: but take in count that PUT is less commonly used and not supported by most browsers
function somename_put()
{
$data = array('somedata: '. $this->put('some-data'));
$this->response($data);
}
You can do it with an ajax request e.g.
(assumes use of jQuery)
$.ajax({
url: '/index.php/my_controller/somedata',
type: 'PUT',
success: function(result) {
console.log(result);
}
});
According this (link: https://github.com/philsturgeon/codeigniter-restserver/blob/master/application/libraries/REST_Controller.php#L915), $this->put only return if passed a param to it (so that works: $username = $this->put('username')). But in REST_Controller, $this->_put_args is protected so, you will extend this class and can access it like: $params = $this->_put_args.
In short (this is just an example, you may improve it as you need);
<?php
// route: /api/users/123
class Users extends REST_Controller
{
...
// update a user's data
public function user_put() {
$params = $this->_put_args;
// you need sanitize input here, "db" is a pseudo
$username = $db->escape($params['username']);
$userpass = $db->escape($params['userpass']);
$db->update(array(
'username' => $username,
'userpass' => $userpass
), (int) $params['id']);
if (!$db->error) {
// suppose right code should be 201 for PUT
$this->response('Created', 201);
} else {
$this->response('Internal Server Error', 500);
}
}
}
?>
<script>
// Some ajax library
Ajax("/api/users/123", {
method: "PUT",
data: {username:"John", userpass:"new pass"},
onSuccess: function(){ console.log("Success!"); }
...
});
</script>

Categories