WP ajax always returns 0 even when using die - ajax

I am trying to use ajax the WP way and I cannot get a response back. If I use ajax manually and include the url to a php file it works fine. But I want to use ajax in wp the "proper" way.
Here is what I have.
add_action('wp_ajax_get_data', 'get_data');
function get_data(){
$group = $_GET['option_group'];
$data_table = 'tablename';
// Array to hold data
$bigArray = array();
// Variable to determine the select clause
$query = "SELECT * FROM $data_table WHERE `group` = $group ";
$datas = $wpdb->get_results($query);
foreach($datas as $data) {
array_push($bigArray, $data);
}
echo json_encode($bigArray);
//Don't forget to always exit in the ajax function.
die();
}
Then the request
jQuery('#new_service #service_option_group').on('change', function() {
// Ajax query to fetch the results
jQuery.ajax({
type: 'GET',
url: ajaxurl,
data: {
action: 'get_data',
data: jQuery('#service_option_group').serialize()
},
success: function(result) {
jQuery('#new_service #service_option_region').empty();
// need to add the default option back in
var option = document.createElement('option');
var select = document.getElementById('service_option_region');
option.text = 'Select an Option'
option.value = -1;
select.appendChild(option);
// Append on the events
for (var i = 0; i < result.length; i++) {
// create and append each element
var option = document.createElement('option');
option.text = result[i].title;
option.value = result[i].id;
var select = document.getElementById('service_option_region');
select.appendChild(option);
}
},
error: function(request, status, error) {
alert(request.responseText);
}
})
});

Related

How to set url ajax query datatable

I want to display the data while returning it from the server.
I canĀ“t set url to ajax query for return the data from the service..
Ajax view:
data: {
'fecha_desde': $("#fecha_desde").val(),
'fecha_hasta': $("#fecha_hasta").val(),
'aplicacion': JSON.stringify(ArrayAplicaciones),
'equipos': JSON.stringify(ArrayEquipos)
},
ajax: function (data, callback, settings) {
var out = [];
for (var i=data.start, ien=data.start + data.length; i < ien ; i++) {
out.push([ i+'-1', i+'-2', i+'-3', i+'-4', i+'-5']);
}
setTimeout(function () {
callback({draw: data.draw, data: out, recordsTotal: 5000000, recordsFiltered: 5000000});
}, 50);
},
Controller
$usuarios_data = collect(DB::select("SELECT distinct usuarios.usuario_id, empresas.nombre_empresa as empresa, usuarios.apellido as apellido, usuarios.autorizado, usuarios.dni, usuarios.dni, usuarios.email, usuarios.fecha_creacion, usuarios.habilitado, usuarios.nombre AS nombre, usuarios.origen, usuarios.reportado, usuarios.telefono, team.equipo AS teams, aplicaciones.nombre AS nombre_app
FROM usuarios, usuario_aplicacion, aplicaciones, team_usuario, team, empresas, usuarios_empresa
WHERE aplicaciones.aplicacion_id IN ( $aplicaciones )
AND usuario_aplicacion.aplicacion_id IN ($aplicaciones)
AND usuarios.email = usuarios_empresa.email
AND usuarios.email = usuario_aplicacion.email
AND usuarios.email = team_usuario.email_usuario
AND team_usuario.id_team = team.id_team
AND usuarios_empresa.id_empresa = empresas.id_empresa
AND team.id_team
IN ( $equipos )"));
return response()->json($usuarios_data);
View
I have to draw data of mysql in datatable. How to set url service in this ajax ?
Sorry for my english..

JQuery Datatable memory leak under both IE and Chrome

My application is using Datatable which binds the data and event dynamically. When monitored from Developer tool in internet explorer one can see an increase in the total memory usage after each server successful response (increases approx. 29-35 MB). I tried solutions to free the DOM using jquery remove(), empty(), detach(), and destroy() methods but none stops the memory increase. Even destroying the datatable before request doesn't help. I also tried to delete the variables in the script, set the variables to null, and set the event bind to the datatable off().
The code snippet from the js file is as follows
function LoadData(isReset) {
var viewId = $jq('#ddlCategory').val();
if (viewId == 'undefined' || viewId == null || viewId == '') {
return false;
}
try {
//Clear the variables and remove the datatable
ClearFunction();
dtAjaxCall = $jq.ajax({
type: "POST",
url: "Ajax/WorkListAjax.aspx/GetData",
deferRender: true,
contentType: "application/json; charset=utf-8",
async: true,
dataType: "json",
timeout: 0,
headers: { Connection: 'keep-alive' },
data: JSON.stringify({
"viewId": viewId
}),
success: function (response) {
//Clear the variables and remove the datatable
ClearFunction();
result = response.d;
if (result.IsError) {
CustomConfirm("dialog-confirm", result.Message, "");
}
else if (result.Data != null) {
data01 = result.Data;
result.Data = null; //set the result.Data as null
tableHeaders = ''; //var to store Datatable headers
columns = []; //var to store Datatable columns
excludeFilters = [];//var to exclude the filters.
bulkOperation = data01.BulkOperation; //var to store if bulk operation is required
//Create the table header columns dynamically as configured in database
$jq.each(data01.Columns, function (i, val) {
if (val.HiddenColumn != "Y") {
tableHeaders += "<th>" + val.DisplayName + "</th>";
var col = { 'title': val.DisplayName, 'data': val.DataColumnName.toLowerCase() };
columns.push(col);
}
if (val.FilterColumn >= 0) {
excludeFilters.push(val.FilterColumn);
}
});
data = $jq.parseJSON(data01.Results); //result returned in ajax call
json = $jq.parseJSON(data01.WorkListJQStructure); //datatable configuration returned in ajax call
delete json["bAutoWidth"];
json.data = data;
json.columns = columns;
DisplayExportOptions(json.buttons, 'resultsTable', 'ulExportTo');
//Add checkbox for each row in the data table
dtColumnDefinition = function (data, type, full, meta) {
return '<input type="checkbox" data-id="' + data + '">';
}
json.aoColumnDefs[0].render = dtColumnDefinition;
//Ajax call to save the datatable state state
dtSaveState = function (settings, data) {
$jq.ajax({
type: "POST",
url: "Ajax/WorkListAjax.aspx/SaveState",
contentType: "application/json; charset=utf-8",
async: true,
dataType: "json",
data: JSON.stringify({ "viewId": viewId, json: data }),
"success": function () {
},
error: function (request, status, error) {
CustomConfirm("dialog-confirm", "An error occurred while processing your current request. Please try again", "");
}
});
}
//Try destroying the existing instance
if ($jq.fn.DataTable.isDataTable('#resultsTable')) {
$jq('#resultsTable').DataTable().destroy();
}
//Make the body empty
$jq('#resultsTable tbody').empty();
//Remove the datatable
$jq("#resultsTable").dataTable().remove();
//Datatable save state function call
json.stateSaveCallback = dtSaveState;
//Empty from the parent table of the datatable
$jq("#resultsTable_display").empty();
//Create the datatable header dynamically and add to the parent table
$jq("#resultsTable_display").append('<table id="resultsTable" class="display" style="width:100%;white-space: nowrap;"><thead><tr>' + tableHeaders + '</tr></thead></table>');
//bind the json and data to the datatable
SearchTable = $jq("#resultsTable").DataTable(json).rows().invalidate().draw();
//Set the event off before
$jq("#resultsTable").off();
//Set the event
$jq('#resultsTable').on('length.dt', function (e, settings, len) {
//code to set the height dynamically...
});
$jq("#resultsTable_display .dataTables_scrollHeadInner").css("width", "100%");
$jq("#resultsTable_display .dataTables_scrollHeadInner .dataTable").css("width", "100%");
BulkOpr(bulkOperation, SearchTable);
//reset the columns after binding the data
SearchTable.columns.adjust();
DataTableName = '#resultsTable';
$jq('#resultsTable').on('page.dt', function () {
info = SearchTable.page.info();
customHeight = 0;
customHeight = UserDefinedFields.CustomPageHeight(info, 40);
$jq('#Parent').attr('style', 'min-height:' + customHeight + 'px;');
});
$jq("a").removeClass("dt-button");
}
//set the variables null
json = null;
data01 = null;
data = null;
},
error: function (request, status, error) {
//do nothing...
}
});
return false;
}
finally {
//Clear the variables...
}
}
//----------------------------------------------
//method to clear the variables and datatables
function ClearFunction()
{
//make all variables null
dtAjaxCall = null;
resultSearchTable = null;
DataTableName = null;
info = null;
customHeight = null;
cells = null;
selected = null;
cBox = null;
clist = null;
dtSaveState = null;
result = null;
data01 = null;
tableHeaders = null;
columns = null;
excludeFilters = null;
bulkOperation = null;
data = null;
json = null;
dtColumnDefinition = null;
//clear dom objects
$jq("#resultsTable").dataTable().remove();
$jq("#resultsTable_display").dataTable().empty();
}
Thanks!
We are refreshing a datatable in a polling method, and it seems to lock up the browser. I don't have an answer either.

How to pass all loop value and pass to ajax?

Why it returns only the last number of my database? I wanted to return all value inside the div. Help me.
Ajax
$.ajax({
url : 'Test.php',
method : 'post',
data : {id: id},
success : function(response)
{
var x = $.parseJSON(response);
for (var a in b)
{
$('#allValue').html(b[a]);
}
}
});
PHP
if(isset($_POST['id']))
{
$query = mysqli_query($conn, "SELECT * FROM tbl_reservation");
while ($row = mysqli_fetch_array ($query))
{
$result[] = array($row['ID_reservation']);
}
echo json_encode($result);
}
By doing
$("#element").html("TEST");
The HTML method removes any existing content and replaces it with "TEST". If you want to append text you could first get the HTML value, but better yet:
var x = $.parseJSON(response);
var text = "";
for (var a in b)
{
text += b[a];
}
$('#allValue').html(text);

How to get data uniquely in view from controller on a ajax call

This is my ajax request code
function ajaxRequest() {
var currentIndexDay = $('#fieldValue').text();
var currentIndexMonth = $('#monthFieldValue').text();
var companyG = $("#companyGname").val();
var timeline = $("#timeL").val();
var month = $("#monthSelect").val();
var year = $("#yearSelect").val();
var dateRange = $("#dateR").val();
$.ajax({
method: "POST",
url: "<?php echo base_url(); ?>index.php/admin/home/pie_chart",
data: { day: currentIndexDay, week: currentIndexMonth, companyGroup: companyG, timeline: timeline, month: month, year: year, daterange: dateRange}
}).done(function( msg ) {
$("#test").html(msg);
});
}
on Done function the recieved data will showed on the div which id is test which is returned from a controller
Here is my controller
public function pie_chart() {
$data = $this->Statisticsmodel->pie_data_all_day($day);
$ap = array();
if(!empty($data)) {
foreach($data as $d=>$value){
if($value->moodstatus == 1 ){
$ap['Ok'] = $value->total;
}elseif($value->moodstatus == 2) {
$ap['Bad'] =$value->total;
}elseif($value->moodstatus == 0) {
$ap['Good'] =$value->total;
}
}
}
echo json_encode($ap);
}
So how can i catch the output to use in somewhere else not only in a div
You need to change your controller function to this :
public function pie_chart() {
$day= $this->input->post('day') // fetch the post data
$data = $this->Statisticsmodel->pie_data_all_day($day);
$ap = array();
if(!empty($data)) {
foreach($data as $d=>$value){
if($value->moodstatus == 1 ){
$ap['Ok'] = $value->total;
}elseif($value->moodstatus == 2) {
$ap['Bad'] =$value->total;
}elseif($value->moodstatus == 0) {
$ap['Good'] =$value->total;
}
}
}
echo json_encode($ap);
}
Since the day was not fetched,so the $data was empty and you are getting the empty response.
Hope this helps.
Change your ajax function like
function ajaxRequest(getData) {
var currentIndexDay = $('#fieldValue').text();
var currentIndexMonth = $('#monthFieldValue').text();
var companyG = $("#companyGname").val();
var timeline = $("#timeL").val();
var month = $("#monthSelect").val();
var year = $("#yearSelect").val();
var dateRange = $("#dateR").val();
$.ajax({
method: "POST",
url: "<?php echo base_url(); ?>index.php/admin/home/pie_chart",
data: { day: currentIndexDay, week: currentIndexMonth, companyGroup: companyG, timeline: timeline, month: month, year: year, daterange: dateRange},
success:function(data) {
getData(data);
}
});
}
Use it in div as like
ajaxRequest(function(output){
$("#test").html(output);
});
Use it in your chart as
ajaxRequest(function(output){
$('#piechart').piechart({
data : output
});
});

Return array from php to ajax success

I want to return an array from a php function to my ajax call. After that I want to use the array values from the page the ajax call is made.
So this is my ajax call:
$(function() {
$("#find").click(function() {
var url = $("#form_url").val();
var dataString = 'url=' + url;
$.ajax({
type: "POST",
url: "/ajax/add_url.php",
data: dataString,
}).done(function( result ) {
myresult(result);
});
return false;
});
});
function myresult(result) {
var result_lines = result.split("<splitter>");
if (result_lines[0] == '1') {
$('#content_error').html(result_lines[1]).fadeIn(250);
$('#content_error').delay(1500).fadeOut(500);
} else if (result_lines[0] == '2') {
$('#content_success').html('Succesfully get images').fadeIn(250);
$('#url_result').delay(500).fadeIn(500);
$('#content_success').delay(1500).fadeOut(500);
alert(eval(data));
}
return true;
}
and this is my php script:
if($_POST['url']) {
$url = $Db->escape($_POST['url']);
$html = file_get_html($url);
$count = 0;
$goodfiles = array();
foreach($html->find('img') as $element) {
$pic = url_to_absolute($url, $element->src);
if(!empty($pic)){
$pics = parse_url($pic);
list($width, $height, $type, $attr) = getimagesize($pic);
if($pics["scheme"]=="http" && $width >= 300 && $height >= 250) {
array_push($goodfiles,$pic);
$_SESSION['pictures'] = $goodfiles;
$count++;
}
}
}
if($count == 0){
$_SESSION['count'] = 'empty';
echo "1<splitter>";
echo "No items found with the correct size";
}else{
$_SESSION['count'] = $count;
echo "2<splitter>";
echo json_encode($_SESSION['pictures']);
}
$_SESSION['url'] = $url;
$html->clear();
$empty = 1;
}
}
when the ajax call is successful I use json_encode on the array to use it on my php page. But I don't know how I get this array to a javascript on the page the ajax call was made of.
right now I'm receiving the following content:
["image.jpeg","image.jpg"]
And I want to put this in a javascript array...
The error is this with this line:
var result_lines = result.split("<splitter>");
result (the AJAX response) is an object or array (depending on the nature of your JSON) but you are trying to call a string method (split()) on it.
This would cause an error in your JS console - always check the console.
Finally, eval() is evil and almost never required except in exceptional circumstances. Try to avoid it.
I don't know how to work with $.ajax but here is an alternative.
Replace this
$.ajax({
type: "POST",
url: "/ajax/add_url.php",
data: dataString,
}).done(function( result ) {
myresult(result);
});
with
$.post("/ajax/add_url.php",{dataString:dataString},function(data){
alert(data['you array index']);
},'json')
I repeat ,this is my alternative so don't take it hard!

Resources