$jQuery Tree from json data ---> .live is killing me - json

I'm trying to build a tree from json data, this data are loaded on demand from php files. My problem is that i can't find a way to get to lvl 3 ;). Here is my code:
$(document).ready(function()
{
//Get the screen height and width
var Height = $(document).height()/2;
var Width = $(window).width()/2;
$("#div1").hide();
$("#div2").hide('slow');
$.ajax(
{
type: 'post',
async: true,
url: "getparents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
beforeSend: function ()
{
//Show the Loading GIF at centered position
$('#loading').css({'top': Height, 'left': Width}).show();
},
success: function(json_data)
{
$("#div1").empty().show();
$('<ul class="parentContainer"></ul>').appendTo("#div1");
$.each(json_data, function(key, object)
{
$('<li id="node">'+object.name+'</li>').data('id', object.id).appendTo(".parentContainer");
if (object.childbool == true)
{
$('li:last').addClass('childfull')
}
});
},
error: function ()
{
$('#loading').hide();
alert('Something Went Wrong with the Loading please hit back in a minute');
},
complete: function ()
{
$('#loading').hide();
}
});
function getChild(id, node)
{
$.ajax(
{
type: 'post',
async: true,
url: "getchilds.php",
data: {'id' : id},
dataType: "json",
cache: false,
beforeSend: function ()
{
$('#loading').show();
},
success: function(json_data)
{
$('<ul class="childContainer"></ul>').appendTo(node);
$.each(json_data, function(key, object)
{
$('<li id="node">'+object.name+'</li>').data('id', object.id).appendTo(".childContainer");
if (object.childbool == true)
{
$('li:last').addClass('childfull')
}
});
},
error: function ()
{
$('#loading').hide();
alert('Something Went Wrong with the Loading please hit back in a minute');
},
complete: function()
{
$('#loading').hide();
}
});
}
$("li.childfull, li.openchildfull").live('click',function()
{
if ($('li.childfull'))
{
var node = $(this);
var id= $(this).data('id');
$(node).html(getChild(id, node));
$(node).removeClass().addClass('openchildfull');
}
else
{
$(node).removeClass().addClass('childfull');
$(node).children().remove();
}
});
});
I think .live is killing me. I get my parents on load; when I click on one I get its children ALL pretty and well, but when I click on a child to get its children I get a very funny behavior. I get its children correctly indented but with no class="childfull" and I get an other copy of them not properly indented but with correct class.. I don't know what is going wrong... Any ideas/corrections are welcome.
P.S: You don't want me to describe to you what happens when I click on the messed up 3rd lvl childfull :P.

Instead of going through the headache of building your own tree, have a look at the jstree plugin. You can pass different formats to it, including json. It allows for complete customization and allows infinite(possible :p) child levels.

Related

ajax json parsing to return related values

I am trying to only parse the information related to a certain "market_name" however I cannot seem to figure out how. The api is located at https://stocks.exchange/api2/ticker which displays information related to the entire exchange. I simply need all of the information returned relating to the "market_name" I am searching for such as ETH_BTC
Ajax:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
last = data.last;
console.log(last);
$("#btcprice").text(last);
},
error: function() {
//alert("Was unable to get info!");
}
});
That's because data is an array of objects, not a single object.
Try:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function (data) {
// find object
var market = data.find(function (obj) {
return obj.market_name == 'ETH_BTC';
});
$("#btcprice").text(market.last);
},
error: function() {
//alert("Was unable to get info!");
}
});
Use array filter() method to filter out the record having market_name as ETH_BTC.
array.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
DEMO
var jsonObj = [{"min_order_amount":"0.00000010","ask":"0.00000017","bid":"0.0000001","last":"0.00000010","lastDayAgo":"0.00000009","vol":"154955.9586604","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ATR_BTC","market_id":338,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.000032","bid":"0.000012","last":"0.00003200","lastDayAgo":"0.000065","vol":"372.5011152","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ETH_BTC","market_id":35,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.00003595","bid":"0.00003","last":"0.00003000","lastDayAgo":"0.00003001","vol":"26.44435669","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ARDOR_BTC","market_id":262,"updated_time":1527789301,"server_time":1527789301}];
var res = jsonObj.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
console.log(res);
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
var results = [];
var searchField = "market_name";
var searchVal = "ETH_BTC";
for (var i=0 ; i < data.length ; i++)
{
if (data[i][searchField] == searchVal) {
results.push(data[i]);
}
}
$("#btcprice").text(results[0].last);
},
error: function() {
//alert("Was unable to get info!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a simple code in which you find what you want simply just change searchVal statically or dynamically according to your need......

Country autosuggest is working but failsed in webproxy?

I am building a codeigniter site which is almost done. In my site country autosuggest is working fine. But when I am trying to acces the site with webproxy hidedoor.com, country auto suggest is not working. I really dont know whow to tackle it. I had tried unsuccesssful attempt of jsonp as well. So can you guy's help me?
my json handling code is,
$(function() {
$("#ville").autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo base_url().'autocomplete/suggestcity'; ?>",
data: { term: $("#ville").val()},
crossDomain: true,
dataType: "json",
//jsonp: 'callback',
//dataType: "html",
type: "POST",
success: function(data){
var citydetails = new Array();
for(i=0; i<data.lang.length; i++)
{
citydetails[i]=data.lang[i]+', '+data.countryname[i];
}
response(citydetails);
$(".ui-menu-item a").click(function(){
set_value($(this).html());
for(i=0; i<=citydetails.length; i++)
{
if(citydetails[i] == $(this).html()){
$("#co_num").val(data.co_num[i]);
$("#geoname_id").val(data.geoname_id[i]);
}
}
});
}
});
},
minLength: 2
});
});

jquery validation onSubmit ajax post JSON response

I have a very complicated post using jquery validation and an AJAX post that gets a JSON response back from the server and puts it in a jqGrid... But it seems as though my onsuccess is never being called at any point...
$(document).ready(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
},
submmitHandler: function (form) {
e.preventDefault();
animateLoad();
debugger;
var theURL = form.action;
var type = form.methd;
var data = $(this).serialize();
$.ajax({
url: theURL,
type: type,
data: data,
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
}
});
});
It would seem I never get into the submmitHandler. Event though I manage to get to my server side function and it does return, it prompts my UI to save a file which contains the JSON results...
No good.
Am I going about validating my form before my AJAX post the wrong way? Does anybody have any advice about best practices in validating AJAX posts?
UPDATE... MARK R. This is what I attempted. It seems as though I never get in to the success function... My suspicion is that I am not really posting via ajax, but instead doing a full post. I don't understand why.
$('#submitMRN').click(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
}
});
if ($('#submitMRN').valid()) {
$("#list").block({ message: '<img src="../../Images/ajax-loader.gif" />' });
$.ajax({
url: $('#submitMRN').action,
type: $('#submitMRN').method,
data: $('#submitMRN').serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
}
});
$('#SubmitButton').click(function (){
//Check that the form is valid
$('#FormName').validate();
//If the Form is valid
if ($('#FormName').valid()) {
$.post(...........
}
else {
//let the user fix their probems
return false;
}
});//$('#SubmitButton').click(function (){

ajax json output parsing in jquerymobile

public function actionajaxSearch() {
$data_fetched=Person::model()->findByAttributes (array('Code'=>'Cust0001'));
echo CJSON::encode($data_fetched); }
$('#searchResult').live('pageshow', function(e,info)
{
$.post('?r=mobile/ajaxSearch',$('form').serialize(),
function(res)
{
arrayvalue =res;
$.each(arrayvalue, function(i, profile) {
alert(i);
alert(profile);
});
}
});
I am getting the output as json encode one.
In traversing alert i am getting the value each character not by key or value.
Any help?
Adding the datatype and contenttype solved the problem. Added the complete code for other's ref.
public function actionajaxSearch() {
$data_fetched=Person::model()->findByAttributes (array('Code'=>'Cust0001'));
echo CJSON::encode($data_fetched); }
$('#searchResult').live('pageshow', function(e,info)
{
$.ajax({
beforeSend: function() { $.mobile.showPageLoadingMsg(); },
complete: function() { $.mobile.hidePageLoadingMsg() },
url: '?r=mobile/ajaxSearch',
data: $('form').serialize(),
type: 'POST',
ContentType: "application/json",
dataType: "json",
success:function(res) {
if(res !='')
{
$.each(res, function(key, value) {
var li='<li>'+value['Code']+'</li>';
$("#mylist").append(li); //append li to ul of id list
}); //eachfunction
$('#mylist').listview();
$('#mylist').listview('refresh');
}//sucess
});

jQuery UI - Autocomplete with extra params - returned data

All,
I've moved on to using the ui autocomplete rather than the plugin, took me a while to figure out extra params based on an example I found here, but that part works.
I'm having problems with dealing with the return data. In the code below I can alert out the title being returned, but I get a drop down of 'UNDEFINED' in the browser.
Thanks in advance.
$('#DocTitle').autocomplete({
source: function(request, response) {
$.ajax({
url: "index.pl",
dataType: "json",
data: {
Title: request.term,
maxRows: 10
},
success: function(data) {
response($.map(data, function(item) {
alert(item.TITLE);
return {
TITLE: item.TITLE
}
}))
}
})
}
});
I am using jquery UI autocomplete as follows and it is working quite fine for me. You may try on the similar lines.
$('input[type=text][name=City]').autocomplete({
source: function(request, response) {
$.getJSON($('input#CitySuggestionsLink').val(), {
term: request.term,
stateId: $('select#StateName option:selected').attr('value')
}, response);
},
search: function() {
// custom minLength
var term = this.value;
if (term.length < 1) {
return false;
}
},
delay: 200,
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
return false;
}
});