create jquery array from php ajax response JSON object - php

I have an en.php file with an array inside, like this:
$lang = array(
// MENÚ LATERAL
"bienvenido" => "Welcome",
"panel_administracion" => "Administration panel",
"administracion" => "Administration",
"gestion_usuarios" => "Users Management",
"roles_permisos" => "Roles and Permissions",
"perfiles" => "Profiles",
"apariencia" => "Appearance",
"configuracion" => "Settings",
"gestion_scripts" => "Script Management",
"gestion_escenarios" => "Scenario Management",
"planificador" => "Planner",
"monitorizacion" => "Monitoring",
"resultados_ejecuciones" => "Executions Results",
"dashboard" => "Dashboard",
// USUARIOS
"usuario" => "User",
"nombre_pagina" => "Users",
"nuevo_usuario" => "New User",
"nombre_usuario" => "User Name",
"perfil" => "Profile",
"rol" => "Role",
"idioma_sitio" => "Language",
"password" => "Password",
"repetir_password" => "Repeat Password",
"guardar" => "Save",
"administracion_usuarios" => "User administration",
"actualizar_usuario" => "Edit user",
"acciones" => "Actions"
);
And I would like store this array in a js array, inside an .js file to access to data always I need, and this code do it this. But I receive this alert: [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental...
var traducciones = function () {
var tmp = null;
var action = "getTraducciones";
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'html',
'url': '../egea/lib/egeaAjax/fAjaxUsuarios.php',
'data': { 'action': action },
'success': function (data) {
var datos = JSON.parse(data);
tmp = datos;
}
});
return tmp;
}();
PHP function:
function getTraducciones(){
session_start();
$traducciones = '';
$u = $_SESSION['usuario'];
if (isset($u) === true){
$lang = getLanguage($u);
if(isset($lang) === true){
require "../../lang/".$lang.".php";
}else{
require "../../lang/es.php";
}
}
echo json_encode($lang);
}
NOTE: async: false is deprecated.
How can I do it, without ajax async:false call?.
Thanks.

Return promise instead of the value itself:
var traducciones = function () {
return new Promise((resolve, reject) => {
var action = "getTraducciones";
$.ajax({
'async': true,
'type': "POST",
'global': false,
'dataType': 'html',
'url': '../egea/lib/egeaAjax/fAjaxUsuarios.php',
'data': { 'action': action },
'success': function (data) {
var datos = JSON.parse(data);
resolve(datos);
},
'error': reject
});
});
}();
Then use it like:
traducciones.then(function(datos) {
// the code that uses the data
}, function() {
// code called if data loading failed
});
By the way, if you really need to have the data loaded in a synchronous way, you may consider loading it as a JS code instead of JSON – i.e. replace:
echo json_encode($lang);
in your PHP code with:
Header('Content-type: text/javascript; charset=utf-8');
// or whatever other charset you are using ^^^^^
echo "var traducciones = " . json_encode($lang) . ";\n";
And then load it as a normal script:
<script src="../egea/lib/egeaAjax/fAjaxUsuarios.php"></script>

Related

AJAX get call always returning empty string

I am trying to make a simple AJAX GET call to my php backend, it hit and runs the method defined however no matter what the response data in the success function is always an empty string with a 200 response.
My ajax request is:
$("#coverage-table").on("click", "td", function() {
$(this).attr('id');
//Create Ajax call
//Get bill data/notes
//Present modal
$.ajax({
url: 'http://tms-v2.test/tms/getBillNotes',
type: 'GET',
data: {
bills: $(this).attr('id')
},
success: function(response) {
console.log(response);
debugger;
modal.style.display = "block";
}
});
});
My php method is:
public function getBillNotes() {
$bills = array_filter(explode("," ,$_GET['bills']));
$billingGateway = new BillingGateway;
$data = $billingGateway->getBillNotes($bills);
//Convert mysql object to array
while($row = mysqli_fetch_array($data)){
$items[] = $row;
}
foreach ($items as $key => $bill) {
$return[$bill['bill_id']] = [
'invoice_number' => $bill['invoice_number'],
'supplier' => $bill['supplier_name'],
'creation_date' => $bill['creation_date'],
'uploaded_by' => $bill['first_name'].' '.$bill['last_name'],
'is_credit_note' => !!$bill['type'],
'validation_status' => !!$bill['is_validating'],
'paid_date' => $bill['paid_date'],
'critical_notes' => $bill['note']
];
}
return 'TEST';
}
However this is always returning "", is this something to do with my request headers?

looking for a help(in wordpress) on how to parse JSON encoded object at server side (PHP code)?

Though I have searched a lot, I was not able to get a concrete answer
client side code
jQuery(document).ready(function() {
jQuery("#p_button").click ( function () {
console.log("button got clicked");
var donor_data= [ "12","13","14" ];
var damount = 1234;
var donor_obj = {
id : donor_data,
amnt : damount,
};
jQuery.ajax({
type:"POST",
dataType : "json",
url: myAjax.ajaxurl,
data: { action : "my_action",
'donors' : JSON.stringify(donor_obj),
},
success:function(response){
console.log("success " );
//console.log("success " + JSON.parse(response));
jQuery("#d_amount").val(donor_data[0]);
jQuery("#p_button").text("brrr");
},
error: function(response) {
console.log("error" + response);
},
});
});
});
server side code
function ajx_add_donations () {
global $wpdb;
$adv_don=json_decode($_REQUEST['donors']);
//$adv_don = json_decode($_POST['donors']);
//echo json_encode("phani");
//echo json_encode($result);
$dtype = 'OFFLINE';
$d_status = 'PENDING';
$ddate = current_time( 'mysql' );
$donation_e = array (
'UID' => $adv_don->id[0],
'STATUS' => $d_status,
'PMODE' => $dtype,
'AMNT' => $adv_don->amnt,
'DDATE' => $ddate
);
$d_id = update_donation_entry($donation_e);
echo json_encode("<h3> Thank you for Contribution <strong>$amount</strong></h3>");
wp_die();
}
Info needed
I'm not able to see my data base being updated, when I click the button,How to parse the Json data (array) at server side ?
Is there any way to know what I have received at server side, If I use "echo" to print a variable it is sent to ajax client ?
If answer to #2 is "NO" , how to parse the JSON data at client side ?
try this
jQuery(document).ready(function() {
jQuery("#p_button").click ( function () {
console.log("button got clicked");
var donor_data= [ "12","13","14" ];
var damount = 1234;
var donor_obj = {
id : donor_data,
amnt : damount,
};
jQuery.ajax({
type:"POST",
//dataType : "json",
url: myAjax.ajaxurl,
data: { action : "ajx_add_donations",
'donors' : JSON.stringify(donor_obj),
},
success:function(response){
console.log("success " ,response);
//console.log("success " + JSON.parse(response));
//jQuery("#d_amount").val(donor_data[0]);
//jQuery("#p_button").text("brrr");
},
error: function(response) {
console.log("error" + response);
},
});
});
});
function ajx_add_donations () {
global $wpdb;
$adv_don=json_decode(stripslashes($_REQUEST['donors']));
//$adv_don = json_decode($_POST['donors']);
//echo json_encode("phani");
//echo json_encode($result);
$dtype = 'OFFLINE';
$d_status = 'PENDING';
$ddate = current_time( 'mysql' );
$donation_e = array (
'UID' => $adv_don->id[0],
'STATUS' => $d_status,
'PMODE' => $dtype,
'AMNT' => $adv_don->amnt,
'DDATE' => $ddate
);
$d_id = update_donation_entry($donation_e);
echo json_encode("<h3> Thank you for Contribution <strong>$amount</strong></h3>");
wp_die();
}
add_action( 'wp_ajax_ajx_add_donations','ajx_add_donations' );
add_action( 'wp_ajax_nopriv_ajx_add_donations', 'ajx_add_donations');

Codeigniter always return error message

I tried to convert the codeigniter form handling using ajax then display validation error if validation is false but in my current state, it always throw an error. Check the code below for reference.
PHP:
public function add () {
$post_data = $this->input->post('formdata');
$data = array (
'identity' => $post_data ['email'],
'password' => $post_data ['password'],
'email' => $post_data ['email'],
'group' => array($post_data['group_id']),
'additional_data' => array (
'first_name' => $post_data['first_name'],
'last_name' => $post_data['last_name'],
'active' => $post_data['active'],
'date_registered' => date('Y/m/d h:i:sa')
)
);
// custom error message
$this->form_validation->set_message('alpha_dash_space', '%s appears to be invalid. Must contain only alphabets.');
$this->form_validation->set_message('matches', '%s does not match the Confirm Password field. ');
if ($this->form_validation->run() == TRUE) {
$result['data'] = $this->ion_auth->register($data['identity'], $data['password'], $data['email'], $data['additional_data'], $data['group']);
} else {
$result['message'] = validation_errors();
}
echo json_encode($result);
}
JS:
function submit_form (form_id) {
var url = $(form_id).attr("action");
var formData = {};
$(form_id).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('select[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('textarea[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$.ajax({
type: "POST",
data: {
'formdata': formData
},
url: url,
dataType: 'json',
success: function(result) {
if (result.data) {
console.log(success);
swal({
title: "Success!",
text: "You've done it great!",
type: "success"
},
function(){
location.reload();
});
} else {
$('#error-msg').html(result.message);
}
},
error: function(data) {
swal({
title: "Error!",
text: "Oops, something went wrong. Check and try again.",
type: "error"
});
}
});
}
Note: Form validation are set in config directory. So no issues in form rules. All are running good except I think the jquery that handles the condition.
Edit like below:
if ($this->form_validation->run() == FALSE) {
$result['message'] = validation_errors();
} else {
$result['data'] = $this->ion_auth->register($data['identity'],
$data['password'], $data['email'], $data['additional_data'],
$data['group']);
}
Also you have set_message but not set_rules. If you want to use form_validation library, you should set some rules.

Show data from 2 tables + zend framework

I want to show data from my database into my table in html. (when i click on a link)
Table "births" fields:
district
year1999
year2000
year2001
year2002
year2003
year2004
year2005
year2006
year2007
year2008
year2009
Table "deaths" fields:
district
year1999
year2000
year2001
year2002
year2003
year2004
year2005
year2006
year2007
year2008
year2009
I will get the data from my database true an ajax call in javascript. I link to an action in my indexcontroller.
Javascript code:
$("#wijken ul li a").click(function(e){
district = ($(this).text());
loadTable(district);
});
function loadTable(district){
var param1 = district;
$.ajax({
url: 'index/getdata',
type: "POST",
data: {param1: param1},
dataType: 'json',
success: function(result)
{
var htmlContent = "";
// HOW CAN I PARSE THE DATA?
htmlContent += '</tbody></table>';
$('#tabel').html(htmlContent);
},
error: function(request, status, error){
alert(request.responseText);
}
});
}
My IndexController:
public function getdataAction()
{
// DISABLE VIEW
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
// WIJK CLICKED
$district = $this->_request->getParam('param1');
// GET THE BIRTHS/YEAR
$birthMapper = new Frontoffice_Model_BirthMapper();
$array = $birthMapper->read($district);
$this->_response->setBody(json_encode($array));
}
My BirthMapper:
public function read($wijk = null)
{
$table = $this->_dbTable;
$columns = array('wijk' => 'wijk',
'year1999' => 'year1999',
'year2000' => 'year2000',
'year2001' => 'year2001',
'year2002' => 'year2002',
'year2003' => 'year2003',
'year2004' => 'year2004',
'year2005' => 'year2005',
'year2006' => 'year2006',
'year2007' => 'year2007',
'year2008' => 'year2008',
'year2009' => 'year2009',
);
$select = $table->select()
->from($table,
$columns
)
->where('wijk = :wijk')
->bind(array(':wijk' => $wijk))
;
if ($row = $table->fetchRow($select)) {
return $row->toArray();
}
throw new Exception('The requested Births cannot be found');
}
Now I can handle the year1999,year2000,year2001,year2002,year2003,year2004,year2005,year2006,year2007,year2008,year2009 fields in my javascript as result.year1999. But how can I do this for multiple tables? (In javascript and controller)

Options not getting added again when the form is submitted +zendFramework

i have to dependent combo box
$this->addElement('Select', 'Category',array(
'label' => 'Category:',
'AutoComplete'=> true,
'multiOptions' => array('0' => '-Category-',$a->GetCategories(),'2' => '-Add category-'),
'required' => true ));
$this->addElement('Select', 'SubCategory',array(
'label' => 'Sub Category:',
'AutoComplete'=> true,
//'multiOptions' => array('0' => '-Select Category-'),
'required' => true ));
the second one is filled using ajax
<script type="text/javascript">
//for send data i'll use jquery library
$(document).ready( function(){
$('#Category').change(function() {
var message=$('#Category option:selected').text();
if (message != '') {
$.ajax({
type: "GET",
dataType : 'json',
url: 'http://localhost/EverTags1/Authentification1/public/Product/add',
async: false,
data:{"message" : message},
success: function (respond) {
var json=JSON.stringify(respond);
var objet = eval('(' + json + ')');
e=objet.length;
var str = "";
for ( var count = 0 ; count < e; count++ ) {
str += "<option value='" + count + "'>" + objet[count].name+ "</option>"
}
$("#SubCategory").empty().append(""+str);
}
});
}
});
});
</script>
The elements were loaded correctly in the second combobox. But when I submitted the content of the second combobox disappears. how can i make them displayed
you need to update multioptions after each ajax request. i used session to do that
public function getsubcategoriesAction()
{
if($this->_request->isXmlHttpRequest())
{
$session = new Zend_Session_Namespace('mySession');
$this->getRequest()->param('id',1)
$model = new Application_Model_DbTable_Subcategory();
$result = $model->getSubcategories($category);
// save the result to session
$session->result = $result;
$this->_helper->json($result);
}
}
and in the action that render the form
public function createAction()
{
//some code here
if($this->getRequest()->isPost()){
$session = new Zend_Session_Namespace('mySession');
$subCategory = $form->getelement('subCategory');
$subCategory->addMultiOptions($session->result); // get the result back from session
//some code here
}
}
you need also to enable sessions in you application.ini
resources.session.save_path = APPLICATION_PATH "/../data/session"
resources.session.use_only_cookies = true
resources.session.remember_me_seconds = 864000
Does adding the selected='selected' attribute to the first option of #SubCategory fix it?

Categories