...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
March 7, 2013

Checking Array for null element

Question by V1rtua1An0ma1y

So I’ve created my own class with 5 private fields: Each is an array with a pre-set length. It’s my way of creating a table, where each array is a column, and they have pre-set lengths because not every cell will contain an element (So, not using anything dynamic).

Anyway, my question is: Can I check to see if a specific cell of a specific array contains “null”? Using .equals(null) gives a nullpointerexception 🙁

Answer by user000001

When you call .equals(...) you call a method of the object. If it is null, it has no method. Therefore null check like this:

if (myArray[position] == null) {
    ....

}

Answer by Starx

Mixed up for loops and null construct

for(Integer ints : intNum) {
    if(intNum != null) {
      //valid
    }
} 
Read more

Replacing characters only a set amount of time

Question by William N

I’ve been googling a bit, but I can’t figure out what keywords to use.

I’m saving the users date of birth, and I want to make sure the format is YYYY-MM-DD.
I’m thinking something like:

if(!ctype_digit(str_replace("-", "", $dob)) || strlen(str_replace("-", "", $dob)) != 8)
{
   echo "Incorrect format: date of birth";
}

For this, I need to use strlen() to only replace three – chars. If it’s more or less than 3, then echo incorrect format. How do I achieve this? Or is there a better way?

Answer by Starx

How about using regex?

if ( !preg_match( "/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $dob) )
{ 
    echo "Invalid date.";
}
Read more

.is(':checked') returns always true

Question by artworkad シ

HTML:

<table id="list">
   <tr>
      <td><input type="checkbox" checked="true"></td>
      <td>...</td>
   </tr>
   <tr>
      <td><input type="checkbox" checked="true"></td>
      ...
   </tr>
   ...
</table>

JS:

$('#list tr').each(function(){
   console.log(
        $(this).find('input[type="checkbox"]').is(':checked')
   );    
});

Problem: the above log statement always returns true. Each tr holds some data and I want to perform an action using this data. But the user can deselect some entities which in this case is not possible because is(':checked') always returns true, even if the entry is deselected/unchecked.

Any ideas how to fix this?

Answer by Starx

Your ‘checked’ attribute has true as its value, so it will return true as even having <input type="checkbox" checked /> will also going be checked.

I created a demo with your code, with additional function to retrieve .is(":checked") as it’s property changed.

$("input").change(function() {
    console.log($(this).is(':checked'));
});

And It shows the change. Your problem must be somewhere else.

Read more

Tables vs Div vs Spans

Question by samyb8

I have always heard that it is better to avoid using <table> in HTML.

However, I encountered a situation in which a table would make my life easier when building a page that shows multiple products and their characteristics.

Should I try to hack it so that I do not need a table, or should I just go with a table?

Answer by Starx

No, you should not avoid the TABLE concept. Learn/Use it to display tabular data, not web layouts.

Learn about those elements from the W3C.

  1. Tables
  2. Div
  3. Span
Read more

I need to pullback data from a jquery ajax post and break the array out to seperate outputs

Question by Ezos

I need to get the array and instead of just pushing the data into an html div – get back the php variable.

My $.ajax post —-

  <script type="text/javascript">
    $(function() {

        $("#login").click(function() {
            var theName = $.trim($("#username").val());

            if(theName.length > 0)
            {
                $.ajax({
                  type: "POST",
                  url: "callajaxdemo.php",
                  data: ({name: theName}),
                  cache: false,
                  dataType: "text",
                  success: onSuccess
                });
            }
        });

        $("#resultLog").ajaxError(function(event, request, settings, exception) {
          $("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
        });

        function onSuccess(data)
        {
            $("#resultLog").html("Result: " + data);
            //$.mobile.changePage('stats.html', { transition: 'slideup'}, true, true);
        }

    });
</script>'

My PHP file is —–

<?php
 $username = $_POST['username']; 
 $password = $_POST['password'];

$host = 'https://api.qpme.com/api/accounts/me';

$process = curl_init($host);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($process);

$content = json_decode($return);

/*
echo "<pre>";
print_r($content);
echo "</pre>";
*/

print $content->email . "<br>";
print "<h3>" . "Welcome" . ' ' . $content->firstName . ' ' . $content->lastName . '!' . "<h3>";

?>'

The goal would be to get back the array and then post certain parts of it to different jquery mobile pages.

Answer by Starx

You can send JSON data back to AJAX request.

Change your arrays to JSON like this:

echo json_encode($yourData);

To read this, you have to setup your script to accept JSON data

        $.ajax({
          type: "POST",
          url: "callajaxdemo.php",
          data: ({name: theName}),
          cache: false,
          dataType: "json", // <--- Here
          success: onSuccess
        });

Then you can access the properties as JavaScript Object.

    function onSuccess(data)
    {
        // access using data.item1
        //           or data.item2 how you prepare your array
    }
Read more

Reload parent dialog content when child dialog is closed

Question by user1277546

I have a large jQuery dialog window that opens up many more dialog windows inside when buttons are clicked in the parent dialog window for updating the database.

I want to update the parent window when the child dialogs are closed.

I can see how to do this with event close and load(url) but how do I make the association between child and parent without specifying each and every ID.

Answer by Starx

Without some markup structures, I cannot understand how your child dialogs resides inside parent.

jQuery has a function called .closest() that travel up the DOM tree to find the nearest matching selector, so you can use this by giving a class to the parent dialog. And select them, when you want to use it like.

$(this).closest(".parent").html("Updated Content");
// ^ Represent your child dialog as you want
Read more

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'']) {

    //.....

}
Read more
March 6, 2013

CSS child bigger than parent allowed?

Question by Programista

Quick question.

I know i can make child div bigger than parent, but is it allowed by w3c? Is it against some rules? Any performance problems?

Answer by albertxing

There are many cases where you would need an overflow in the parent div, with a larger child div: for example, a fixed-position content frame.

And there should be no performance impediment; it should be around the same as rendering the child div as a sibling of the parent.

Answer by Starx

W3C specifications does not limit you what kind of value you use for its attributes, except for few cases like:

  • Integer Id Attribute

So, to answer your question, Yes it is allowed.

Read more

convert date format within a webservice php context

Question by Peter van der Lely

I am consuming a webservice in php. The piece of code below gives me the following result with regard to the date notation:

Begindatum : 2012-07-02T00:00:00. I would like to have that in a European format like:

Begindatum : 02-07-2012. I’ve been trying to imlement the standard solution:

Convert date format yyyy-mm-dd => dd-mm-yyyy

but without succes. Help is appreceated.

 foreach($array as $k=>$v){
 print "
 <tr>
      <td>
            <ul>
                <li><b>Naam         : {$v->Naam}</b></li>
                <li><b>Status       : {$v->Status}</b></li>
                <li><b>Aanbieder    : {$v->VerstrekkerNaam}</b></li>
                <li><b>Bedrag       : {$v->Bedrag}</b></li>
                <li><b>Begindatum   : {$v->Begindatum}</b></li>

            </ul>
      </td>
</tr>

Answer by Starx

You can try this

$d = "2012-07-02T00:00:00";
echo $newDate = date("d-m-Y",strtotime($d));

Demo

In your code you may apply it as

foreach($array as $k=>$v){
 print "
 <tr>
      <td>
            <ul>
                <li><b>Naam         : {$v->Naam}</b></li>
                <li><b>Status       : {$v->Status}</b></li>
                <li><b>Aanbieder    : {$v->VerstrekkerNaam}</b></li>
                <li><b>Bedrag       : {$v->Bedrag}</b></li>
                <li><b>Begindatum   : {" . date("d-m-Y",strtotime($v->Begindatum)) ."}</b></li>
            </ul>
      </td>
</tr>
Read more
March 5, 2013

Why are my variables not interpolated inside strings?

Question by peace

<?php 

$array = array('1' => 'one', '2' => 'two','3','three');

foreach($array as $num => $number){
    echo 'Numburic: $num <br /> Number: $number';
};

?>

The result I’m looking for:

1. one
2. two
3. three

Answer by Starx

For that output, you have to do:

foreach($array as $num => $number){
    echo "$num. $number <br />";
};

Your mistakes as pointed in other answers is using a single quotes to wrap your string with a PHP variable inside. Only when you use " (double quotes) your variables will be parsed by PHP.

Also your array definition is wrong (Credit: Musa’s Comment). Change

$array = array('1' => 'one', '2' => 'two','3', 'three');
                                        // ^ This is a separate array item 
                                        //   not its index

To

$array = array('1' => 'one', '2' => 'two','3' => 'three');
Read more
...

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