May 29, 2015

convert string array to object array highchart and json

Code Demon’s Question:

I have this script

var portfolio_in_arrears = [];
var portfolio_future = [];
var portfolio_good_standing = [];
var portfolio_ingrace_period = [];

$.each(JSON.parse(response.portfolio), function(index, value){
    portfolio_in_arrears.push(value.in_arrears);
    portfolio_future.push(value.future_clients);
    portfolio_good_standing.push(value.good_standing);
    portfolio_ingrace_period.push(value.grace_period);
});

and this part of the highchart options

series: [{
    name: 'Future',
    data: portfolio_future //sample [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
    }, {
    name: 'In Grace Period',
    data: portfolio_ingrace_period //sample [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
    }, {
    name: 'Arrears',
    data: portfolio_in_arrears //sample [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
    }, {
    name: 'Good standing',
    data: portfolio_good_standing //sample [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]

I did successfully retrieved and parse the data from the json response and put on there corresponding array

var portfolio_in_arrears = [];
var portfolio_future = [];
var portfolio_good_standing = [];
var portfolio_ingrace_period = [];

but sadly when i tried to bind those array on the series option, it didnt work. When i check it on the console e.g. console.log(portfolio_future), I see the array like this

["146", "143", "123", "106", "106", "94", "76", "71", "69", "83", "66", "66", "98", "98", "96", "90", "85", "102", "102", "94", "135", "126", "111", "125", "116", "116", "108", "129", "113", "93", "102", "86", "86", "68", "81"]

which the proper array for the series option is

[3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]

so any ideas how to turn this

["146", "143", "123", "106", "106", "94", "76", "71", "69", "83", "66", "66", "98", "98", "96", "90", "85", "102", "102", "94", "135", "126", "111", "125", "116", "116", "108", "129", "113", "93", "102", "86", "86", "68", "81"]

to

[146, 143, 123, 106, 106, 94, 76, 71, 69, 83, 66, 66, 98, 98, 96, 90, 85, 102, 102, 94, 135, 126, 111, 125, 116, 116, 108, 129, 113, 93, 102, 86, 86, 68, 81]

as you can see, there’s no double qoutes stuff on each of the number.

You can solve this by specifying the value is strictly numeric. Use parseInt() function

Here is how you would use it.

portfolio_in_arrears.push(parseInt(value.in_arrears));

An example here.

August 4, 2013

jquery not fetching results from json based on search input?

Baljeet Singh’s Question:

I have the working code which displays all the results from the json, I tweaked the code to display only the results based on the search, But i don’t know what is the problem is, it still shows all the results,

The code is following:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery PHP Json Response</title>
<style type="text/css">
div
{
text-align:center;
padding:10px;
}

#msg {
width: 500px;
margin: 0px auto;
}
.members {
width: 500px ;
background-color: beige;
}
</style>
</head>
<body>
<input type="text" id="search-json-input" />
<input type="button" id="search-json-submit" value="search" />
<br/>
<br/>
<input type="button" name="next" id="next" value="NEXT" />
<br/>
<input type="button" name="previous" id="previous" value="PREV" />
<br/>
<div id="msg">
    <table id="userdata" border="1">
        <thead>
            <th>Email</th>
            <th>Sex</th>
            <th>Location</th>
            <th>Picture</th>
            <th>audio</th>
            <th>video</th>
        </thead>
        <tbody></tbody>
    </table>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script type="text/javascript">

var users = [];
var idx = 0; 

var url = "json.php";
    var search_query = jQuery('#search-json-input').val();
    var search_query_regex = new RegExp(".*"+search_query+".*", "g");
$.getJSON(url, function (data) {

    users = data.members;

    renderRow(idx);
    $('#next').click(function() {
        idx++;
        renderRow(idx);
    });
    $('#previous').click(function() {
        idx--;
        renderRow(idx);
    });
});

$("#search-json-submit").click(function(){


    for(var y=0;y<users.length;y++){ 
    if((users[y].email).match(search_query_regex) ||
           (users[y].sex).match(search_query_regex) ||
   (users[y].location).match(search_query_regex)) {

        renderRow(y)

        }
     }
});

var renderRow = function (idx) {
    //alert(idx);
    if (idx < 0) idx = 0;
    if (idx > (users.length - 1)) idx = (users.length - 1);
    var user = users[idx];

    var tblRow = "<tr>" + "<td>" + user.email + "</td>" + "<td>" + user.sex + "</td>" + "<td>" + user.location + "</td>" + "<td>" + "<img src=" + user.image + ">" + "</td>" + "<td>" + "<audio src=" + user.video + " controls>" + "</td>" + "<td>" + "<video src=" + user.video + " controls>" + "</td>" + "</tr>";
    $('#userdata tbody').html(tblRow);


};

</script>
</body>
</html>

The result of json.php can be seen here: http://sco7.com/components/phonegap/json.php

Move your code to fetch JSON into your event handler. Your code execute directly upon occurence, so it does not find any value on the input box.

$("#search-json-submit").click(function(){
    var url = "json.php";

    var search_query = jQuery('#search-json-input').val();
    var search_query_regex = new RegExp(".*"+search_query+".*", "g");
    $.getJSON(url, function (data) {

        users = data.members;

        renderRow(idx);
        $('#next').click(function() {
            idx++;
            renderRow(idx);
        });
        $('#previous').click(function() {
            idx--;
            renderRow(idx);
        });
    });

   //... Rest of the handler
});
June 20, 2013

Adding div from JSON in jQuery?

Ted’s Question:

I am getting some data from a page in JSON format
JSON:
{
‘name’ : ‘maverick’,
Image : ‘Jason’
}

I now need to take these values and add them to the #main div.

        <div id="main">
        <div class="a"> name: Eithan <img src="img/Eithan.jpg" /> <div>
        <div class="a"> name: Emma <img src="img/Emma.jpg" /> <div>
       </div>

How do I do that in jQuery for the case there are several objects in the JSON?

You can do this by using $.getJSON() function.

$.getJSON("link/to/json", function(data) {
    $.each(data, function(i, item) {
        $('#main').append('<div class="a"> name: ' + item.name + ' <img src="img/' + item.image + '.jpg" /></div>');
    });
});
May 20, 2013

event after json completes loading

Simmi Simmi’s Question:

i am loading data using json in my image slider i want to perform some action once json completes loading images .

    $.ajax({
       type: "GET",
       url: "photos.xml",
       dataType: "xml",
       success: function( xml ) {
          $(xml).find('item').each(function() {
             var path = $(this).attr('path');
             var width = $(this).attr('width');
             var height = $(this).attr('height');
             var id = $(this).attr('id');
             var alt = $(this).attr('alt');
             var longdesc = $(this).find('longdesc').text();
             var description = $(this).find('desc').text();
             $('#myImageFlow').prepend('<img src="'+path+'" id='+id+'  height="'+height+'"  width="'+ width+'" longdesc="'+longdesc+'" alt="'+alt+'"/>');
             imgArr[i] = description;
             i = i + 1;
         });
      }
  });

How to do this?

You can use .promise() function to do such things.

$(list).promise().done(function() {
   console.log("image completed loading");
});

Use as:

$.ajax({
    type: "GET",
    url: "photos.xml",
    dataType: "xml",
    success: function(xml) {
        var xmlList = $(xml).find('item');
        xmlList.each(function(){
            var path = $(this).attr('path');
            var width = $(this).attr('width');
            var height = $(this).attr('height');
            var id = $(this).attr('id');
            var alt = $(this).attr('alt');
            var longdesc = $(this).find('longdesc').text();
            var description = $(this).find('desc').text();
            $('#myImageFlow').prepend('<img src="'+path+'" id='+id+'  height="'+height+'"  width="'+ width+'" longdesc="'+longdesc+'" alt="'+alt+'"/>');
            imgArr[i] = description;
            i = i+1;
        });
        $(xmlList).promise().done(function() {
           console.log("image completed loading");
        });

    }
});
May 16, 2013

Create subset of php array and convert to json

Dilettante’s Question:

This is one of those that should be easy. I’m not even sure if “subset” is the right way to describe it.

My initial array looks like this:

array(3) { [0]=> array(5) { ["id"]=> string(1) "1" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 01:58:48" ["created"]=> string(19) "2013-05-15 01:58:48" } [1]=> array(5) { ["id"]=> string(2) "11" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "45" ["date"]=> string(19) "2013-05-15 03:34:59" ["created"]=> string(19) "2013-05-15 03:37:01" } [2]=> array(5) { ["id"]=> string(2) "25" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 22:47:46" ["created"]=> string(19) "2013-05-15 22:52:02" } } 

I’d ultimately like to end up with just the date and price values, swap them so that date is first in the array, reformat the date, and convert it to a json array that looks something like this:

[{"date":"Mar. 15","price":"50"},{"date":"Mar. 15","price":"45"},{"date":"Mar. 15","price":"50"}] 

I ran a foreach statement to get at the data and reformat the date, then went out of my league with splice, unset, and other functions that took me in the wrong direction. Any ideas?

Create a quick function to create another array with only selected elements:

function datePriceToJson($array) {
   $a = array();
   foreach($array as $i => $a) {
      $a[] = array("date" => $a['date'], "price" => $a['price']); //Creae a new array based on the one you want
   }
   return json_encode($a);
}

datePriceToJson($array);
April 9, 2013

How to apply WHERE clause again array or jscon encoded value

M4l33n’s Questions:

Values are stored under company_id like

["2"]
["2", "1"]

where 2 and 1 are the IDs of companies. Now i want all result of ID 2. How can i fire query again json encoded data.

select * from tbl where company_id = 2

This is what I need to perform.

For more info, json format is the result of dynamic (fill by database values) Select List in Zend2.

And what if it was array instead of json, how this simple select query can be executed.

As each ID is a number inside double quotes you can just query with a LIKE statement:

select * from tbl where company_id LIKE '%"2"%'

And what if it was array instead of json, how this simple select query can be executed.

You can store JSON into a mysql database because it is a string. But an array is not a string, so you can not store it there. You would need to serialize it but for that you should prefer JSON.

The alternative would be to create a table that stores the relationships to the companies.

MySQL has a datatype called SET You can use this data type on this task. This will allow you to enter comma separated values and still be able to query as per single item.

Manual: http://dev.mysql.com/doc/refman/5.0/en/set.html

Your query will have to be updated to something like this:

SELECT * FROM tbl_name WHERE FIND_IN_SET('2', company_id);

But, this problems arises because the tables are not normalized properly. Adding a reference table and querying this reference table will be a much better option, when the application reaches large-scale.

March 7, 2013

How do I get specific parts of JSON files for use with HTML?

Question by user2137541

I would like to import JSON data from a file, the code I have at the moment is:

<script>                            
    $.getJSON('data.json', function(data) {             
    var output = "<tr>";
    for ( var i in data.users) {
    output += "<td>"
    + "-- "
    + data.users[i].time
    + " --<br>-- "
    + data.users[i].senderID
    + " --<br>"
    + data.users[i].message
    + "<br></br></td>";
    }
    output += "</tr>";
    document.getElementById("placeholder").innerHTML = output;
    });
</script>

But I can no longer access it as it doesnt get generated with a nice neat name like “users” as you can see below it is “¬í t’” but you cant reference to that as part of it isnt valid characters

    ¬í t’{  
    "messageId": 53,  
    "userTo": {    
    "userId": 4,    
    "userName": "Bob123",    
    "userLastCheckedDate": "Mar 7, 2013 11:14:53 AM"
    },

    "userFrom": {
    "userId": 1,
    "userName": "Joe123",    
    "userLastCheckedDate": "Mar 7, 2013 10:41:44 AM"
    },

    "messageContent": "a lovely message here",
    "messageSentDate": "Mar 7, 2013 11:36:14 AM",
    "messageReadDate": "Mar 7, 2013 12:49:52 PM"
    }

Any ideas? Thanks!

Also, this is the java that generates the JSON

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(userMessages.get(0));
    out.write(json);

Answer by Starx

You can access the object as array too.

for ( var i in data['’ t'']) {

    //.....

}
February 27, 2013

jQuery $.post not returning data

Question by Cuonic

I’m using $.post to send a form via ajax to a PHP page, which returns JSON data. Once upon a time, it worked perfectly, and the function(data) executed as normal. Somehow, I’ve broke it, and now it doesn’t even touch the function(data). I’ve tried undoing most of what I’ve done, but I still can’t find the problem.

Here’s the script :

$("#modifyhome").submit(function(event) {
    if($("#modifyhome").valid()) {  
        event.preventDefault();

        var $form = $( this ),
            title = $form.find('input[name="title"]').val(),
            content = $form.find('textarea[name="content"]').val();

        $.post("?action=page-accueil", {"title": title, "content": content},
            function(data) {            
                if(data['error'] == 1)
                {           
                    $().message(data['message']);
                    $("div.jquery-message").effect("shake", {times: 3}, 900);
                }
                else if(data['error'] == 0)
                {           
                    $().message(data['message']);
                    $("div.jquery-message").effect("bounce", {times: 3}, 900);
                }
                else
                {           
                    $().message("Erreur de connexion au serveur : veuillez r&eacute;essayer.");
                    $("div.jquery-message").effect("shake", {times: 3}, 900);
                }
            }, "json"
        );
    }
    else
    {
        $("[id^=qtip-]").effect("pulsate", {times: 3}, 600);
        return false;
    }
});

And here is what the PHP page (?action=page-accueil) returns :

{"error":0,"message":"Page modifi&eacute;e."}

That all checks out as valid JSON, but it’s as if jQuery doesn’t recognize it for some reason. Any help is greatly appreciated 🙂

Answer by Starx

I used to get this problem too, I am exactly not sure of the reason why. But I have a solution that works.

$.post("?action=page-accueil", 
    {"title": title, "content": content},
    function(data) {
        data = eval("("+data+")");
        //.... Then continue it
});

Or, use .parseJSON() function to read the string as JSON, if you dont want to use eval()

$.post("?action=page-accueil", 
    {"title": title, "content": content},
    function(data) {
        data = $.parseJSON(data);
        //.... Then continue it
});
February 25, 2013

PHP PDO data into Json_Encode + but only first line appears

Question by Adam

                       $sql='SELECT word,language,acceptable FROM profanity;';
                       $pds=$database_miscellaneous->pdo->prepare($sql); 
                       $pds->execute(); 
                       //$row=$pds->fetch();
        foreach($pds as $row) {
            $profanityText = json_encode(array('word' => $row['word'],
                                       'language' => $row['language'],
                                       'acceptable' => $row['acceptable']));
        }

I have the above code. The catch is it works but only the first line from the database goes into the json array. I’ve run the query directly against the DB and it pulls all the data.

I’m guessing my foreach loop has an issue or many the way I’m doing the PDO call.

any ideas?

Answer by Starx

The problem is that the variable holding the json encoded values $profanityText gets overidden every time in the loop.

Use this

    $rows = array()
    foreach($pds as $row) {

        $rows[] = array('word' => $row['word'],
            'language' => $row['language'],
            'acceptable' => $row['acceptable']);
    }
    $profanityText = json_encode($rows);

Or, if you are not manipulating your data in anyway, you can just directly call (as mentioned by deceze)

$profanityTest = json_encode($pds->fetchAll(PDO::FETCH_ASSOC));
August 4, 2012

Parsing JSON array of objects with jQuery

Question by Christopher Buono

What I am trying to do is parse this JSON: http://www.theunjust.com/test/container.php

And just get it to show at this point…

Here is my current code(its all jacked up)

$(document).ready(function(){
    var jsonurl = "container.php";
  $.getJSON(jsonurl, function(data) {         
    $.each(data.encompass,function(i,valu){
    var content,
    cont = '',
    tainers = valu.containers;

  $.each(tainers, function (i) {
    var tid = tainers[i].TID,
    top = tainers[i].Top,
    cat = tainers[i].Category,
    date = tainers[i].Date,
    icon = tainers[i].Icon,
    clink = tainers[i].ContainerLink,
    uid = tainers[i].UniqueID;

        cont += '<a href="' + clink + '">' + uid + '</a> ';
        $('ul').append('<li>' + tid + ' - ' + top + ' - ' + cat + ' - ' + date + ' - ' + icon + ' - ' + clink + ' - ' + uid + ' (' + cont + ')</li>');
    }); 
  }); 
}); 
});

I know that the code doesn’t make sense, this is more of a learning experience for me rather than a functioning tool. The issue may be in the JSON data itself, if that is the case, what stackoverflow web service post would you recommend?

What I eventually aim to do is run multiple web services and combine them… So that container.php loads and has all of the information that is required for a wrapping div, then entries.php loads and fills the divs that was generated by containers..

I’m currently learning jQuery and Honestly, I’m not to this level yet, but I am getting there pretty quick.

I really appreciate the help, and would like if you could point me in the direction to become a JSON parsing pro!

Answer by Starx

containers contain single node. So simply use

$.each(tainers, function (i, v) {
    var tid = v.TID,
    top = v.Top,
    cat = v.Category,
    date = v.Date,
    icon = v.Icon,
    clink = v.ContainerLink,
    uid = v.UniqueID;

    cont += '<a href="' + clink + '">' + uid + '</a> ';
    $('ul').append('<li>' + tid + ' - ' + top + ' - ' + cat + ' - ' + date + ' - ' + icon + ' - ' + clink + ' - ' + uid + ' (' + cont + ')</li>');
});
...

Please fill the form - I will response as fast as I can!