PHP Class private variable misdirected value - php

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

Related

Ajax request in WP plugin return 0

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.

Select2 load data from database - CodeIgniter

I try to load database data in my Select2 input. (Im working on CI)
Here's my code from the controller : transforms array in echo json
class Ajax extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('client');
}
public function returnClientsAjax(){
echo json_encode($this->client->getClients());
}
}
Model : returning an array of results
function getClients(){
return $this->db->query("SELECT idclient AS id, CONCAT(societe,' [', nom,']') as text FROM du_client WHERE (societe != '' AND nom != '') AND evo2012 >=2 AND type_client != 'Particulier' AND statut_client = 'Demandeur' AND idclient = 6141;")->result_array();
}
My Select2 :
$("#sel_clients").select2({
placeholder: "Search for an Item",
ajax: {
dataType: "json",
url: "http://commexpert.dev.local/ajax/returnclientsajax",
results: function (data) {
return {results: data};
}
}
});
The input still empty so, don't know what to do.
Thnaks :D
I think something is missing on your data results method. Here is my code from working ajax select2 component:
results: function (data) {
var results = [];
var id1 = data.id;
var name = data.text;
$.each(data.data, function(index, item){
results.push({
id: item[id1],
text: item[name].trim()+' : '+ item[id1]
});
});
return {results: results};
}
also, I'm having somewhat diff data call also:
data: function (term) {
try {
mirko = $(this).closest('[rendered]').find( "input[fparamname$=" + $(this).attr('flookupfiltref') + "]" ).val();
if (mirko.indexOf(' : ') >=0 ) { // pocetna vrijednost
mirko = mirko.split(' : ')[1].trim();
}
} catch(e){
mirko = '';
}
return {
sp_name: $(this).attr('objectname'),
fl_name: $(this).attr('fparamname'),
node_id: $(this).attr('node_id'),
bound: mirko,
q: term,
};
},
I'm having somekind of manipulation before sending or returning q to server,, but I hope that can help you for your service :)
hth, k

AJAX request and PHP class functions

How to call a PHP class function from an ajax call
animal.php file
class animal
{
function getName()
{
return "lion";
}
}
Then in my ajax.php file I have an ajax request, need to get values from getName function
How to do that getName() function can I do like this?
<script type=text/javascript>
$.ajax({
type: "POST",
data: {
invoiceno:jobid
},
url: "animal/getName",
beforeSend: function() {
},
dataType: "html",
async: false,
success: function(data) {
result=data;
}
});
</script>
My answer is the same as Surreal Dreams answer, but with the code.
First. Class animal is OK. Leave it like that:
animal.php
<?php
class animal
{
function getName()
{
return "lion";
}
}
Next. Create a new animalHandler.php file.
<?php
require_once 'animal.php';
if(isset( $_POST['invoiceno'] )) {
$myAnimal = new animal();
$result = $myAnimal->getName();
echo $result;
}
Finally. Change your Javascript.
<script type=text/javascript>
$.ajax({
type: "POST",
data: {
invoiceno:jobid
},
url: "animalHandler.php",
dataType: "html",
async: false,
success: function(data) {
result=data;
}
});
</script>
That's is.
You need one additional script, because your animal class can't do anything on its own.
First, in another script file, include animal.php. Then make an object of the animal class - let's call it myAnimal. Then call myAnimal->getName() and echo the results. That will provide the response to your Ajax script.
Use this new script as the target of your Ajax request instead of targeting animal.php.
OOP Currently with php:
ajax.html program(client tier) -> program.php (middle tier) -> class.php (middle tier) -> SQL call or SP (db tier)
OOP Currently with DotNet:
ajax.html program(client tier) -> program.aspx.vb (middle tier) -> class.cls (middle tier) -> SQL call or SP (db tier)
My real-life solution:
Do OOA, do not OOP.
So, I have one file per table -as a class- with their proper ajax calls, and select the respective ajax call with a POST parameter (i.e. mode).
/* mytable.php */
<?
session_start();
header("Content-Type: text/html; charset=iso-8859-1");
$cn=mysql_connect ($_server, $_user, $_pass) or die (mysql_error());
mysql_select_db ($_bd);
mysql_set_charset('utf8');
//add
if($_POST["mode"]=="add") {
$cadena="insert into mytable values(NULL,'".$_POST['txtmytablename']."')";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
//modify
if($_POST["mode"]=="modify") {
$cadena="update mytable set name='".$_POST['txtmytablename']."' where code='".$_POST['txtmytablecode']."'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
//erase
if($_POST["mode"]=="erase") {
$cadena="delete from mytable where code='".$_POST['txtmytablecode']."'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
// comma delimited file
if($_POST["mode"]=="get") {
$rpta="";
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
while($row = mysql_fetch_array($rs)) {
$rowCount = mysql_num_fields($rs);
for ($columna = 0; $columna < $rowCount; $columna++) {
$rpta.=str_replace($row[$columna],",","").",";
}
$rpta.=$row[$columna]."\r\n";
}
echo $rpta;
};
//report
if($_POST["mode"]=="report_a") {
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
while ($row=mysql_fetch_array($rs)) {
echo $row['code']." ".$row['name']."<br/>"; // colud be a json, html
};
};
//json
if($_POST["mode"]=="json_a") {
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
$result = array();
while ($row=mysql_fetch_array($rs)) {
array_push($result, array("id"=>$row['code'],"value" => $row['name']));
};
echo json_encode($result);
};
?>
Can you please mention which are you using any Framework?
You method is correct but I want to mention two things over here. First try your URL from the browser and check if its working correctly. Secondly don't use return, in *success: function(data) * data will contain only the output. so use Echo rather then return
For what it is worth, I have used a PHP proxy file that accepts an object as a post -- I will post it here. It works by providing class name, method name, parameters (as an array) and the return type. This is limited as well to only execute classes specified and a limited set of content types to return.
<?php
// =======================================================================
$allowedClasses = array("lnk","objects"); // allowed classes here
// =======================================================================
$raw = file_get_contents("php://input"); // get the complete POST
if($raw) {
$data = json_decode($raw);
if(is_object($data)) {
$class = $data->class; // class: String - the name of the class (filename must = classname) and file must be in the include path
$method = $data->method; // method: String - the name of the function within the class (method)
#$params = $data->params; // params: Array - optional - an array of parameter values in the order the function expects them
#$type = $data->returntype; // returntype: String - optional - return data type, default: json || values can be: json, text, html
// set type to json if not specified
if(!$type) {
$type = "json";
}
// set params to empty array if not specified
if(!$params) {
$params = array();
}
// check that the specified class is in the allowed classes array
if(!in_array($class,$allowedClasses)) {
die("Class " . $class . " is unavailable.");
}
$classFile = $class . ".php";
// check that the classfile exists
if(stream_resolve_include_path($classFile)) {
include $class . ".php";
} else {
die("Class file " . $classFile . " not found.");
}
$v = new $class;
// check that the function exists within the class
if(!method_exists($v, $method)) {
die("Method " . $method . " not found on class " . $class . ".");
}
// execute the function with the provided parameters
$cl = call_user_func_array(array($v,$method), $params );
// return the results with the content type based on the $type parameter
if($type == "json") {
header("Content-Type:application/json");
echo json_encode($cl);
exit();
}
if($type == "html") {
header("Content-Type:text/html");
echo $cl;
exit();
}
if($type == "text") {
header("Content-Type:text/plain");
echo $cl;
exit();
}
}
else {
die("Invalid request.");
exit();
}
} else {
die("Nothing posted");
exit();
}
?>
To call this from jQuery you would then do:
var req = {};
var params = [];
params.push("param1");
params.push("param2");
req.class="MyClassName";
req.method = "MyMethodName";
req.params = params;
var request = $.ajax({
url: "proxy.php",
type: "POST",
data: JSON.stringify(req),
processData: false,
dataType: "json"
});
Try this:
Updated Ajax:
$("#submit").on('click', (function(e){
var postURL = "../Controller/Controller.php?action=create";
$.ajax({
type: "POST",
url: postURL,
data: $('form#data-form').serialize(),
success: function(data){
//
}
});
e.preventDefault();
});
Update Contoller:
<?php
require_once "../Model/Model.php";
require_once "../View/CRUD.php";
class Controller
{
function create(){
$nama = $_POST["nama"];
$msisdn = $_POST["msisdn"];
$sms = $_POST["sms"];
insertData($nama, $msisdn, $sms);
}
}
if(!empty($_POST) && isset($_GET['action']) && $_GET['action'] == ''create) {
$object = new Controller();
$object->create();
}
?>
For every ajax request add two data, one is class name and other is function name
create php page as follows
<?php
require_once 'siteController.php';
if(isset($_POST['class']))
{
$function = $_POST['function'];
$className = $_POST['class'];
// echo $function;
$class = new $className();
$result = $class->$function();
if(is_array($result))
{
print_r($result);
}
elseif(is_string($result ) && is_array(json_decode($result , true)))
{
print_r(json_decode($string, true));
}
else
{
echo $result;
}
}
?>
Ajax request is follows
$.ajax({
url: './controller/phpProcess.php',
type: 'POST',
data: {class: 'siteController',function:'clientLogin'},
success:function(data){
alert(data);
}
});
Class is follows
class siteController
{
function clientLogin()
{
return "lion";
}
}
I think that woud be a sleek workaround to call a static PHP method via AJAX which will also work in larger applications:
ajax_handler.php
<?php
// Include the class you want to call a method from
echo (new ReflectionMethod($_POST["className"], $_POST["methodName"]))->invoke(null, $_POST["parameters"] ? $_POST["parameters"] : null);
some.js
function callPhpMethod(className, methodName, successCallback, parameters = [ ]) {
$.ajax({
type: 'POST',
url: 'ajax_handler.php',
data: {
className: className,
methodName: methodName,
parameters: parameters
},
success: successCallback,
error: xhr => console.error(xhr.responseText)
});
}
Greetings ^^

jquery ajax not parsing json data from php

I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.

Calling php class function in javascript (ajax)

I was wondering if is there any good practices to call method from php class with Javascript, by the way of Ajax.
This is my current "style" to execute it.
(The method in the class are only here for example)
PHP side :
<?php
if(isset($_POST['action']) && $_POST['action'] != null)
{
extract($_POST);
if($action)
{
$ajaxCommand = new EleveUpdate();
if(method_exists($ajaxCommand, $action))
{
$reponse = call_user_func(array($ajaxCommand, $action),$_POST);
echo $reponse;
exit(0);
}
else
{
throw new Exception("Cette méthode n'existe pas");
}
}
}
else
{
echo 'Cette action n\'est pas autorisée';
return false;
}
class EleveUpdate
{
public function __construct()
{
}
public function testfunct($data)
{
echo $data['eleve'];
}
}
Javascript side:
$(document).ready(function() {
$.ajax({
url: 'eleveupdate.php',
type: 'POST',
data: {
action: "testfunct",
eleve: 1
},
beforeSend: function()
{
loading(true);
},
error: function()
{
console.log('error');
},
success: function(data)
{
loading(false);
console.log(data);
}
});
});
The problem is that the isset $_POST is always in my class, I'm pretty sure this is not the right way to do it so, I'm here to found help about it.
Thanks you in advance
Simon
The problem is it's not easy to call scope-namings based on a string-request.
You can use something called LAMBDA, or anonymous functions. This way you can store an array of strings with a LAMBDA attached to them. Like this:
<?php
class EleveUpdate {
private $funcs = array();
function __construct($which_function) {
$funcs['testfunct'] = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
$funcs[$which_function];
}
}
?>
See more info here: http://www.php.net/manual/en/function.create-function.php
You probably won't even need the Class anymore with this method, but just showing.

Categories