Bootstrap treeview nodes do not expand - javascript

I have a problem with a specific bootstrap treeview, I have tried everything but the node does not expand, I use ajax request through a load file where I retrieve the information coming from the database, the data appears normally, the only one I have already tried all the methods that the treeview bootstrap provides, but it returns that it does not know the method used, below I will send the specific code that I use.
Function that calls a tree:
var levelTree = 2;
function getTree() {
var data = '';
$.ajax({
url: 'atividades/atividades_load.php',
data: {idObraAtiva: <?php echo $idObra; ?>},
async: false,
dataType: 'json',
type: 'post',
beforeSend: function () {
},
success: function (retorno) {
data = retorno;
console.log(retorno);
},
error: function () {
bootbox.alert('Erro, contate o suporte!');
}
});
return data;
}
$('#atividadeTree').treeview({
data: getTree(),
levels: levelTree,
backColor: "#C4E3F3",
onNodeSelected: function (event, data) {
if (data.qtdfilhos == 0) {
$('#table_Andamento').bootstrapTable('refresh', {url: 'atividades/atividade_andamento_load.php?q=' + data.id});
}
$('#table_AtividadeFilha').bootstrapTable('refresh', {url: 'atividades/atividade_filha_load.php?p=' + data.id});
$('#fmAndamento_idatividade').val(data.id);
$('#fmAtividadeSub_idAtividade').val(data.id);
},
onNodeExpanded: function (event, data) {
$.ajax({
url: 'atividades/atividades_load.php',
data: {idObraAtiva: <?php echo $idObra; ?>,idNo:data.id},
async: false,
dataType: 'JSON',
type: 'POST',
beforeSend: function (){
},
success: function (filho){
$('#atividadeTree').treeview('addNode',[filho, data.id,
{silent: false} ]);
console.log(filho);
},
error: function () {
bootbox.alert('Erro, contate o suporte!');
}
});
}
});
Function that calls the data, and reorganizes the treeview
<?php
include('../../sessao.php');
require_once('../../J3_FrameWork/Conexao.php');
function getItemPai($_arrLista, $_id)
{
foreach ($_arrLista as $item) {
if ($item->id == $_id) {
if (!property_exists($item, 'nodes')) $item->nodes = array();
return $item;
}else
if (property_exists($item, 'nodes')) {
if (is_array($item->nodes)) {
$aux = getItemPai($item->nodes, $_id);
if ($aux != null)
return $aux;
}
}
}
return null;
}
$idObra = $_REQUEST['idObraAtiva'];
if (isset($_REQUEST['idNo'])) {
$idNo = $_REQUEST['idNo'];
}else{
$idNo = -1;
}
$conexao = Proxy::mrObra();
$param = array("_parameters" => array($idObra, $idNo));
$resultado = $conexao->comando('GetAtividadesArvore', json_encode($param));
$resultado = json_decode($resultado);
$lista = $resultado->result[0];
$listanova = array();
foreach ($lista as $item) {
$novoitem = new stdClass();
$novoitem->id = $item->ID;
$novoitem->text = $item->DESCRICAO. ' - ' .$item->QTDFILHOS;
$novoitem->qtdfilhos = $item->QTDFILHOS;
$novoitem->valor = $item->VALOR;
$novoitem->qtdativsub = $item->QTDATIVSUB;
if($item->QTDFILHOS > 0)
{
$novoitem->nodes = array();
}
if ($item->IDPAI == -1) {
array_push($listanova, $novoitem);
} else {
array_push($listanova, $novoitem);
}
}
echo json_encode($listanova);
?>
Função que chama os dados, e reorganiza a treeview
<?php
include('../../sessao.php');
require_once('../../J3_FrameWork/Conexao.php');
function getItemPai($_arrLista, $_id)
{
foreach ($_arrLista as $item) {
if ($item->id == $_id) {
if (!property_exists($item, 'nodes')) $item->nodes = array();
return $item;
}else
if (property_exists($item, 'nodes')) {
if (is_array($item->nodes)) {
$aux = getItemPai($item->nodes, $_id);
if ($aux != null)
return $aux;
}
}
}
return null;
}
$idObra = $_REQUEST['idObraAtiva'];
if (isset($_REQUEST['idNo'])) {
$idNo = $_REQUEST['idNo'];
}else{
$idNo = -1;
}
$conexao = Proxy::mrObra();
$param = array("_parameters" => array($idObra, $idNo));
$resultado = $conexao->comando('GetAtividadesArvore', json_encode($param));
$resultado = json_decode($resultado);
$lista = $resultado->result[0];
$listanova = array();
foreach ($lista as $item) {
$novoitem = new stdClass();
$novoitem->id = $item->ID;
$novoitem->text = $item->DESCRICAO. ' - ' .$item->QTDFILHOS;
$novoitem->qtdfilhos = $item->QTDFILHOS;
$novoitem->valor = $item->VALOR;
$novoitem->qtdativsub = $item->QTDATIVSUB;
if($item->QTDFILHOS > 0)
{
**$novoitem->nodes = array();**
}
if ($item->IDPAI == -1) {
array_push($listanova, $novoitem);
} else {
array_push($listanova, $novoitem);
}
}
echo json_encode($listanova);
?>

Related

Error : SyntaxError: Unexpected token { in JSON at position 4

I am using ajax to do some mathematical calculations. The controller sends the correct response back but the data is not being displayed (when I try to do console.log(data) after success) and instead alerts an error message - "Error : SyntaxError: Unexpected token { in JSON at position 4". I have been debugging since yesterday to no success.
Here is the JSON being returned
{
mydata: {
items: [
20.68
],
sub_total: 20,
tax_total: 0.68,
grand_total: 20.68
}
}
This is the Ajax function
function totalItem() {
$.ajax({
url: '{{ url("finance/items/totalItem") }}',
type: 'POST',
dataType: 'JSON',
data: $('#items input[type=\'text\'],#items input[type=\'hidden\'], #items textarea, #items select'),
headers: { 'X-CSRF-TOKEN': csrf },
success: function(data) {
if (data) {
$.each( data.items, function( key, value ) {
console.log(data);
//$('#item-total-' + key).html(value);
$('#item-total-' + key).val(value);
});
$('#sub-total').html(data.sub_total);
$('#tax-total').html(data.tax_total);
$('#grand-total').html(data.grand_total);
}
},
error:function (xhr, ajaxOptions, thrownError) {
alert("Error : "+thrownError);
}
});
}
My Controller
public function totalItem(Request $request)
{
//
//$input_items = request('item');
$input_items = $request->item;
$mydata = new \stdClass;
$sub_total = 0;
$tax_total = 0;
//$tax = 0;
$items = array();
if ($input_items) {
foreach ($input_items as $key => $item) {
//return response()->json($item['tax_id']);
$item_tax_total = 0;
$price = isset($item['price']) ? $item['price'] : 0;
$qty = isset($item['quantity']) ? $item['quantity'] : 0;
$item_sub_total = ($price * $qty);
//$item_sub_total = (2 * 2);
if (isset($item['tax_id'])) {
$tax = Tax::find($item['tax_id']);
$rate = isset($tax->rate) ? $tax->rate : 0;
$item_tax_total = (($price * $qty) / 100) * $rate;
}
$sub_total += $item_sub_total;
$tax_total += $item_tax_total;
$total = $item_sub_total + $item_tax_total;
//$items[$key] = money($total, $currency_code, true)->format();
$items[$key] = $total;
//return response()->json($tax);
//return response()->json($sub_total);
}
}
$mydata->items = $items;
$mydata->sub_total = $sub_total; //money($sub_total, $currency_code, true)->format();
$mydata->tax_total = $tax_total; //money($tax_total, $currency_code, true)->format();
$grand_total = $sub_total + $tax_total;
$mydata->grand_total = $grand_total; //money($grand_total, $currency_code, true)->format();
return response()->json(['mydata' => $mydata]);
}
}
Missing double quotes. The JSON should be
{
"mydata": {
"items": [
20.68
],
"sub_total": 20,
"tax_total": 0.68,
"grand_total": 20.68
}
}

jQuery ajax call not triggering success function on Safari 9.1

In a project I have a particular ajax call that works fine on PC Chrome/Firefox, but on Safari 9.1 it fails to trigger the success function.
The ajax call:
$('#new_file_form').submit(function(e) {
e.preventDefault();
var form_data = new FormData($(this)[0]);
$.ajax({
url: '/includes/ajax/file-manager.php',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
success: function(result) {
JSON.parse(result);
alert(result);
if (result == true) {
$('#new_file_form').reset;
$('#new_file_modal').modal('hide');
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-info-sign blue"></i>File successfully saved.',
callback: function() {
location.reload();
}
});
} else if (result == false) {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>File not saved.',
callback: function() {
location.reload();
}
});
} else {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>Whoa! That escalated quickly..',
callback: function() {
location.reload();
}
});
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
This doesn't throw any errors. The file is uploaded and the data inserted into the database, it's just the success function that sits there and seems to be laughing at me.
Based on the returned error in Safari it seems useful to post the file-manager.php code:
if(!empty($_POST['file_name']) && !empty($_POST['file_type']) && !empty($_POST['file_user'])) { // && !empty($_FILES['file'])
$ownerid = $mysqli->real_escape_string($_POST['file_user']);
$ownertype = 1;
$name = $mysqli->real_escape_string($_POST['file_name']);
$visible = $mysqli->real_escape_string($_POST['visible']);
$filetype = $mysqli->real_escape_string($_POST['file_type']);
$ownerid = filter_var($ownerid, FILTER_SANITIZE_NUMBER_INT);
$visible = filter_var($visible, FILTER_SANITIZE_NUMBER_INT);
$filetype = filter_var($filetype, FILTER_SANITIZE_NUMBER_INT);
$cdate = date('Y-m-d H:i:s');
$edate = $cdate;
$u_file_name = $_FILES['file']['name'];
$u_tmp_file = $_FILES['file']['tmp_name'];
$u_file_type = $_FILES['file']['type'];
$u_file_error = $_FILES['file']['error'];
$u_file_content = file_get_contents($_FILES['file']['tmp_name']);
$upload_result = '';
if($u_file_error == 'UPLOAD_ERROR_OK') {
if($u_file_name == '') {
$upload_result = false;
} else {
$sql = "SELECT path FROM filetypes WHERE id = '$filetype'";
$result = $mysqli->query($sql);
$record = $result->fetch_object();
$file_type_path = $record->path;
$extension = end(explode(".", $u_file_name));
if($ownertype == 1) {
$s_file_name = preg_replace("![^a-z0-9]+!i", "-", $name).'-'.date('Y-m-d_H-i').'.'.$extension;
$s_file_dest = LOCAL_BASE_PATH.'/uploads/'.$ownerid.'/'.$file_type_path;
$s_file_location = $s_file_dest.'/'.$s_file_name;
$s_file_path = '/uploads/'.$ownerid.'/'.$file_type_path.$s_file_name;
}
if(!file_exists($s_file_dest)) {
mkdir($s_file_dest, 0755, true);
}
move_uploaded_file($u_tmp_file, $s_file_location);
$sql = "INSERT INTO files (ownertype, owner, type, visible, extension, name, path, cdate, edate) VALUES ('$ownertype', '$ownerid', '$filetype', '$visible', '$extension', '$s_file_name', '$s_file_path', '$cdate', '$edate')";
$result = $mysqli->query($sql);
$upload_result = true;
}
}
echo json_encode($upload_result);
exit();
}
When I alert the ajax result before parsing it, I get a PHP error:
Strict Standards: Only variables should be passed by reference...

UI Unresponsive when we jquery ajax abort called

I am doing a four API calls(for twitter,facebook,instagram,youtube) on selecting brand name and get data and set the response to different div.
When if i select first brand say "ford" and request made by using ajax asynchronous call, on between request if i select other brand,then previous made request is aborted and second one get processed.
First Ajax calls is aborted and second request was run but between abort process,my dropdown box get unresponsive until all request get aborted.
Sample code :
$(document).ready(function ()
{
var cblcurrentRequest = null;
var currentRequest = null;
var twcurrentRequest = null;
var fbcurrentRequest = null;
var igcurrentRequest = null;
var ytcurrentRequest = null;
var firsttwcurrentRequest = null;
var firstfbcurrentRequest = null;
var firstigcurrentRequest = null;
var firstytcurrentRequest = null;
load_session();//load access key on session
$('#brands').prop('disabled', 'disabled');
$('#selcategory').change(function () {
$('.loader_cmn').show();
$("#brands").select2("val", null);
$('#brands').append('<option value=" ">Select Brand Name</option>');
$('#brands').prop('disabled', true);
var categoryID = this.value;
if (categoryID != "") {
currentRequest = $.ajax({url: baseurl + 'admin/Adminhome/getCategoryListByIdWithLogin/' + categoryID, type: 'post', data: '',
beforeSend: function () {
var msg = "<center><b>Please select brand</b></center>";
$('#tw').html(msg);
$('#fb').html(msg);
$('#inst').html(msg);
$('#yt').html(msg);
hide_loader();
if (currentRequest != null) {
currentRequest.abort();
}
if (twcurrentRequest != null) {
twcurrentRequest.abort();
}
if (fbcurrentRequest != null) {
fbcurrentRequest.abort();
}
if (igcurrentRequest != null) {
igcurrentRequest.abort();
}
if (ytcurrentRequest != null) {
ytcurrentRequest.abort();
}
if (firsttwcurrentRequest != null) {
firsttwcurrentRequest.abort();
}
if (firstfbcurrentRequest != null) {
firstfbcurrentRequest.abort();
}
if (firstigcurrentRequest != null) {
firstigcurrentRequest.abort();
}
if (firstytcurrentRequest != null) {
firstytcurrentRequest.abort();
}
}
}).done(function (res)
{
$("#brands").empty();
$('#brands').append('<option value="" selected="">Select Brand Name</option>');
var obj = JSON.parse(res);
$.each(obj, function (i, item) {
$('#brands').append('<option value="' + obj[i].BrandID + '">' + obj[i].BrandName + '</option>');
});
$('.loader_cmn').hide();
$('#brands').prop('disabled', false);
}).fail(function (res) {
});
}
});
$('#display_alert').show();
function load_session() {
$.ajax({url: baseurl + 'Login/set_accesskeys', type: 'post', async: false, cache: true, data: ''}).done(function (res)
{
setTimeout(2000);
}).fail(function (res) {
});
}
var msg = "<center><b>Please select brand</b></center>";
if ($("#brands").val() === "") {
$('#tw').html(msg);
$('#fb').html(msg);
$('#inst').html(msg);
$('#yt').html(msg);
$('#yelp').html(msg);
} else {
var brand_id = $.trim($("#brands").val());
load_social_feeds(brand_id);
}
$("#brands").change(function () {
$(window).scrollTop(0);
var brand_id = $.trim(this.value);
load_social_feeds(brand_id);
});
function hide_loader()
{
$('#loader_tw').hide();
$('#loader_fb').hide();
$('#loader_inst').hide();
$('#loader_yt').hide();
}
function getChannelBrandlistJson(brand_id)
{
var channelBrandList;
var facebookBrandName;
var twitterBrandName;
var youtubeBrandName;
var instagramBrandName;
var yelpBrandName;
cblcurrentRequest = $.ajax({url: baseurl + 'Login/getChannelBrand/' + brand_id, type: 'post', async: false, cache: true, data: '',
beforeSend: function () {
if (cblcurrentRequest != null) {
cblcurrentRequest.abort();
}
if (firsttwcurrentRequest != null) {
firsttwcurrentRequest.abort();
}
if (firstfbcurrentRequest != null) {
firstfbcurrentRequest.abort();
}
if (firstigcurrentRequest != null) {
firstigcurrentRequest.abort();
}
if (firstytcurrentRequest != null) {
firstytcurrentRequest.abort();
}
if (twcurrentRequest != null) {
twcurrentRequest.abort();
}
if (fbcurrentRequest != null) {
fbcurrentRequest.abort();
}
if (igcurrentRequest != null) {
igcurrentRequest.abort();
}
if (ytcurrentRequest != null) {
ytcurrentRequest.abort();
}
}
}).done(function (res)
{
channelBrandList = JSON.parse(res);
facebookBrandName = channelBrandList['FacebookChannel'];
twitterBrandName = channelBrandList['TwitterChannel'];
youtubeBrandName = channelBrandList['YoutubeChannel'];
instagramBrandName = channelBrandList['InstagramChannel'];
YelpBrandName = channelBrandList['YelpChannel'];
$('#facebookchannel').val(facebookBrandName);
console.log(facebookBrandName);
$('#twitterchannel').val(twitterBrandName);
console.log(twitterBrandName);
$('#youtubechannel').val(youtubeBrandName);
console.log(youtubeBrandName);
$('#instagramchannel').val(instagramBrandName);
console.log(instagramBrandName);
$('#yelpchannel').val(YelpBrandName);
console.log(yelpBrandName);
}).fail(function (res) {
});
}
function Twfeed(brand_name)
{
var indexCount = 2;//used to calls the all three month post
$('#twContainer').scrollTop(0);
$('#twContainer').perfectScrollbar('update');
loader_show();
// setTimeout(function wait() {
twcurrentRequest = $.ajax({url: baseurl + 'Twfeed/get_Twfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
beforeSend: function () {
if (twcurrentRequest != null) {
twcurrentRequest.abort();
}
}
}).done(function (res)
{
if (res != null && res.trim() != '')
{
setcontent(res);
}
}).fail(function (res) {
});
//}, 1000);
}
function FirstTwfeed(brand_name)
{
var indexCount = 1; //used to calls the first three post
$('#twContainer').scrollTop(0);
$('#twContainer').perfectScrollbar('update');
loader_show();
// setTimeout(function wait() {
firsttwcurrentRequest = $.ajax({url: baseurl + 'Twfeed/get_Twfeed/' + brand_name + '/' + indexCount, type: 'post', data: ''}).done(function (res)
{
if (res != null && res.trim() != '')
{
setcontent(res);
Twfeed(brand_name);
}
}).fail(function (res) {
});
// }, 1000);
}
function Fbfeed(brand_name)
{
// load_session();
var indexCount = 2;
$('#fbContainer').scrollTop(0);
$('#fbContainer').perfectScrollbar('update');
$('#loader_fb').show();
//setTimeout(function wait() {
fbcurrentRequest = $.ajax({url: baseurl + 'Fbfeed/get_Fbfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
beforeSend: function () {
if (fbcurrentRequest != null) {
fbcurrentRequest.abort();
}
}
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#fb').html(res);
$('#loader_fb').hide();
}
}).fail(function (res) {
});
//}, 1000);
}
function FirstFbfeed(brand_name)
{
// load_session();
var indexCount = 1;
$('#fbContainer').scrollTop(0);
$('#fbContainer').perfectScrollbar('update');
$('#loader_fb').show();
//setTimeout(function wait() {
firstfbcurrentRequest = $.ajax({url: baseurl + 'Fbfeed/get_Fbfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#fb').html(res);
$('#loader_fb').hide();
Fbfeed(brand_name);
}
}).fail(function (res) {
});
//}, 1000);
}
function Instfeed(brand_name)
{
//load_session();
var indexCount = 2;
$('#instaContainer').scrollTop(0);
$('#instaContainer').perfectScrollbar('update');
$('#loader_inst').show();
// setTimeout(function wait() {
igcurrentRequest = $.ajax({url: baseurl + 'Igfeed/get_Igfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
beforeSend: function () {
if (igcurrentRequest != null) {
igcurrentRequest.abort();
}
}
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#inst').html(res);
$('#loader_inst').hide();
}
}).fail(function (res) {
});
//}, 1000);
}
function FirstInstfeed(brand_name)
{
//load_session();
var indexCount = 1;
$('#instaContainer').scrollTop(0);
$('#instaContainer').perfectScrollbar('update');
$('#loader_inst').show();
// setTimeout(function wait() {
firstigcurrentRequest = $.ajax({url: baseurl + 'Igfeed/get_Igfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#inst').html(res);
$('#loader_inst').hide();
Instfeed(brand_name);
}
}).fail(function (res) {
});
//}, 1000);
}
function Ytfeed(brand_name)
{
//load_session();
var indexCount = 2;
$('#ytContainer').scrollTop(0);
$('#ytContainer').perfectScrollbar('update');
$('#loader_yt').show();
//setTimeout(function wait() {
ytcurrentRequest = $.ajax({url: baseurl + 'Ytfeed/get_Ytfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
beforeSend: function () {
if (ytcurrentRequest != null) {
ytcurrentRequest.abort();
}
}
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#yt').html(res);
$('#loader_yt').hide();
}
}).fail(function (res) {
});
// }, 1000);
}
function FirstYtfeed(brand_name)
{
//load_session();
var indexCount = 1;
$('#ytContainer').scrollTop(0);
$('#ytContainer').perfectScrollbar('update');
$('#loader_yt').show();
//setTimeout(function wait() {
firstytcurrentRequest = $.ajax({url: baseurl + 'Ytfeed/get_Ytfeed/' + brand_name + '/' + indexCount, type: 'post', data: '',
}).done(function (res)
{
if (res != null && res.trim() != '')
{
$('#yt').html(res);
$('#loader_yt').hide();
Ytfeed(brand_name);
}
}).fail(function (res) {
});
// }, 1000);
}
function setcontent(res) {
$('#tw').html(res);
loader_hide();
}
function loader_show() {
$('#loader_tw').show();
}
function loader_hide() {
$('#loader_tw').hide();
}
function load_social_feeds(brand_id) {
//load_session();
getChannelBrandlistJson(brand_id);
//load_session();
//setTimeout(function wait() {
$('#tw').html("");
$('#fb').html("");
$('#inst').html("");
$('#yt').html("");
$('#yelp').html("");
//var brand_name = $.trim($("#brands").val());
//alert('load method');
if (brand_id !== "") {
$(".chanel input[type=checkbox]:checked").each(function ()
{
//alert("Id: " + $(this).attr("id") + " Value: " + $(this).val() + " Checked: " + $(this).is(":checked"));
$exp = parseInt($(this).val());
switch ($exp) {
case 1:
$('#twsection').show();
var twitterBrandName = $('#twitterchannel').val();
console.log('twitterBrandName-' + twitterBrandName);
FirstTwfeed(twitterBrandName);
// Twfeed(twitterBrandName); // Load Twitter
break;
case 2:
$('#fbsection').show();
var facebookBrandName = $('#facebookchannel').val();
console.log('facebookBrandName-' + facebookBrandName);
FirstFbfeed(facebookBrandName);
// Fbfeed(facebookBrandName); // Load Facebook
break;
case 3:
$('#instsection').show();
var instagramBrandName = $('#instagramchannel').val();
console.log('instagramBrandName-' + instagramBrandName);
FirstInstfeed(instagramBrandName); // Load Instagram
//Instfeed(instagramBrandName); // Load Instagram
break;
case 4:
$('#ytsection').show();
var youtubeBrandName = $('#youtubechannel').val();
console.log('youtubeBrandName-' + youtubeBrandName);
FirstYtfeed(youtubeBrandName); //Load Youtube
//Ytfeed(youtubeBrandName); //Load Youtube
break;
}
});
} else {
$('#tw').html(msg);
$('#fb').html(msg);
$('#inst').html(msg);
$('#yt').html(msg);
$('#yelp').html(msg);
}
}
});
I am using Codeigniter framework for server script.ajax call request to my controller and controller all required API Libraries and send back HTML response back to ajax.
Please suggest,if i am missing anything.
Thanks,

Does jQuery.ajax() not always work? Is it prone to miss-fire?

I have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});

My object is undefined when I test it i QUnit

I'm using QUnit and have a test script for a JQuery UI Widget:
define(
['jquery',
'knockout',
'../Widget/SearchPod/searchPod',
'jqueryui',
'jquery.ui.widget',
'../Widget/SearchPod/clr.searchPod'],
function ($, ko, searchPod) {
var checkSearchBy = function () {
test('check if select has Search By text', function () {
var expected = "Search By";
alert(searchPod.employees);//.checkSearchByWidget());
deepEqual(searchPod.employees, expected, "We expect drop down text to
display 'Search By' by default");
return 1;
});
};
return {
checkSearchBy: checkSearchBy
};
}
);
For some reason whenever I run the test script, an error occurs saying that the parameter searchpod above is undefined or null. The code of searchpod is below:
require(['jquery',
'knockout',
'jqueryui',
'jquery.ui.widget',
'domReady!',
'Widget/SearchPod/clr.searchPod',
'Widget/Listbox/clr.combobox'],
function ($, ko) {
$(document).ready(function () {
$("#search-pod").searchPod({
ready: function () {
var minimumLength = 2;
$("#search-message").hide();
//start
//end
var employees = [*some data*]
var leaves_filed = [*some data*]
var claims_filed = = [*some data*]
function sortData(prop, asc) {
data = data.sort(function (a, b) {
if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
});
}
//This is to display search messages depends on selected search type and
function validateCriteria(selectedType) {
var searchMessage = 'No values match search criteria';
if (selectedType == 'ssn') {
if ($("#searchBox").val().length > minimumLength) {
searchMessage = 'Must enter all 9 digits of SSN';
}
}
$("#search-message").text(searchMessage);
}
// Search pod items
var selectedType = 'lastname';
var data = employees;
// Apply the combobox widget
$("#searchBy").combobox({
ready: function () {
},
select: function () {
selectedType = $("option:selected", this).val();
switch (selectedType) {
case 'lastname':
return;
if (employees.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetEmployeeListReport",
type: "GET",
processData: false,
success: function (result) {
employees.length = 0;
employees = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = employees;
}
});
}
else { data = employees; }
minimumLength = 1;
break;
case 'ssn':
minimumLength = 10;
break;
case 'eeid':
if (employees.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetEmployeeListReport",
type: "GET",
processData: false,
success: function (result) {
employees.length = 0;
employees = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = employees;
minimumLength = employees[5].eeid.length;
}
});
}
else { data = employees; minimumLength =
employees[5].eeid.length; }
break;
case 'leave_number':
if (leaves_filed.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetLeavesList",
type: "GET",
processData: false,
success: function (result) {
leaves_filed.length = 0;
leaves_filed = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = leaves_filed;
minimumLength = leaves_filed[0].leaveNumber.length;
}
});
}
else { data = leaves_filed; minimumLength =
leaves_filed[0].leaveNumber.length; }
break;
case 'claim_number':
if (claims_filed.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetClaimsList",
type: "GET",
processData: false,
success: function (result) {
claims_filed.length = 0;
claims_filed = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = claims_filed;
minimumLength = claims_filed[10].claimNumber.length;
}
});
}
else { data = claims_filed; minimumLength =
claims_filed[10].claimNumber.length; }
break;
}
sortData(selectedType, true);
$('#searchBox').val('');
}
});
sortData(selectedType, true);
//This will hide search-message when backpress is pressed.
$('html').keyup(function (e) {
if (e.keyCode == 8) {
if ($("#searchBox").val().length < minimumLength) {
if ($("#search-message").show()) $("#search-message").hide();
}
}
return;
});
//Code for Making SSN AutoComplete
$('#searchBox').keyup(function () {
if (selectedType == "ssn" && $('#searchBox').val().length == 10) {
var rptParam = "?ssn=" + $('#searchBox').val();
var ssnData = [{ "ssn": "", "lastname": "" }];
$.ajax({
url: "api/Dashboard/GetSsnList" + rptParam,
type: "GET",
processData: false,
success: function (result) {
ssnData = result.dataSet.dataTable.row;
var ssnArray = [];
ssnArray.push(ssnData);
if (ssnArray.length > 0) {
$("#searchBox").autocomplete({
minLength: 10,
source: function (request, response) {
var searchField;
var filteredArray = $.map(ssnArray, function (item) {
if (item.ssn != null) {
searchField = item.ssn;
if (searchField.toLowerCase().indexOf
(request.term) == 0 || searchField.indexOf
(request.term) == 0) {
return item;
}
} else { return null; }
});
response(filteredArray);
},
focus: function (event, ui) {
var focusValue;
focusValue = ui.item.ssn;
$("#searchBox").val(focusValue);
return false;
},
select: function (event, ui) {
}
}).data("ui-autocomplete")._renderItem =
function (ul,item){
return $("<li>")
.append(displayFormat)
.appendTo(ul);
};
}
$('#searchBox').autocomplete("search");
}
});
}
return;
});
$("#searchBox").focus(function () {
if (selectedType == 'ssn') {
$("#searchBox").autocomplete();
$("#searchBox").autocomplete("destroy");
return;
}
var searchField;
$("#searchBox").autocomplete({
minLength: minimumLength,
source: function (request, response) {
var filteredArray = $.map(data, function (item) {
if (selectedType === 'lastname') {
searchField = item.lastname;
}
if (selectedType === 'ssn') {
return false;
}
if (selectedType === 'eeid') {
searchField = item.eeid;
}
if (selectedType === 'leave_number') {
searchField = item.leaveNumber;
}
if (selectedType === 'claim_number') {
searchField = item.claimNumber;
}
if (searchField.toLowerCase().indexOf(request.term) == 0 ||
searchField.indexOf(request.term) == 0) {
if (selectedType === 'ssn' && request.term.length < 4) {
return null;
}
return item;
}
else {
return null;
}
});
if (!filteredArray.length) {
$("#search-message").show();
validateCriteria(selectedType);
}
else {
$("#search-message").hide();
}
response(filteredArray);
},
focus: function (event, ui) {
var focusValue;
if (selectedType === 'lastname') {
focusValue = ui.item.lastname;
}
if (selectedType === 'eeid') {
focusValue = ui.item.eeid;
}
if (selectedType === 'leave_number') {
focusValue = ui.item.leaveNumber;
}
if (selectedType === 'claim_number') {
focusValue = ui.item.claimNumber;
}
$("#searchBox").val(focusValue);
return false;
},
create: function (event, ui) {
$(this).autocomplete("widget").addClass("search-results-list");
},
open: function (event, ui) {
$(".search-results-list li.ui-menu-item").addClass("search-results-item");
},
select: function (event, ui) {
//return false; // Cancel the select event
var focusValue;
if (selectedType === 'lastname') {
focusValue = ui.item.lastname;
// TODO: call a function here that will send the name of the report to show
$('#report-popup-dialog-overlay').show();
$('#report-popup-dialog').show();
}
if (selectedType === 'eeid') {
focusValue = ui.item.eeid;
}
if (selectedType === 'leave_number') {
focusValue = ui.item.leaveNumber;
$('#dynamictext').text('Leave Report for ' + focusValue);
$('#dynamicHeader').text('Leave Report');
}
if (selectedType === 'claim_number') {
focusValue = ui.item.claimNumber;
$('#dynamicHeader').text('Claim Report for ' + focusValue);
$('#dynamictext').html("Loading...");
//Need to make Ajax Call to get the report.
var parameter = "?claimNumber=" + focusValue;
$.ajax({
url: "api/ViewReport/GetClaimReport" + parameter,
type: "POST",
processData: false,
success: function (result) {
$('#dynamictext').html("");
$('#dynamictext').html(result);
}
});
}
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
var displayFormat = "";
return $("<li>")
.append(displayFormat)
.appendTo(ul);
};
});
}
});
});
//Test helper functions
//2. checkSearchBy
function checkSearchBy() {
alert($('#searchBy').text());
return $('#searchBy').text();
}
return {
checkSearchByWidget: function () {
return checkSearchBy();
}
};
});
I've been at this for two days but cant seem to make the searchpod be seen by the test script above

Categories

Resources