...

Hi! I’m Starx

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

Looping through Dynamic JSON String

Question by Starx

I have a POST request which receives a JSON String as a result. The fields, the values, or how deep the array is? These all are unknown. So, I need to loop through each of the json value, its index and its value and perform actions based on it.

$.post(
    "test.php", 
    { action: 'someaction', param: '2' },
    function(data) {
      //now data is a json string
      $.each(data, function() {
       key = data.key; //i need to retrieve the key
       value = data.value; //i need to retrieve the value also

       //now below here, I want to perform action, based on the values i got as key and values
      }
    },
    "json"
);

How can i get the values of JSON seperated as key and value?

Answer by Starx

Sorry, guys, but I solved it myself. Please dont be angry with me. (I will delete the question if it is required by the community.)

$.post(
    "test.php", 
    { action: 'someaction', param: '2' },
    function(data) {
      //now data is a json string
      $.each(data, function(key,value) {
       alert(key+value);
       //now below here, I want to perform action, based on the values i got as key and values
      }
    },
    "json"
);
Read more

How to Add text with superscript to a Button

Question by Sajja

I have a HTML button like

<input type="button" id="button" onclick="showSuper()" value="Click Me!" />

Inside JavaScript, I have

var showSuper = function() {
    var btn = document.getElementById('button');
    var spanSuper = "<sup>3</sup>";
    btn.value="You Clicked Me " +  spanSuper;
    //btn.value = "You Clicked Me " + <sup>a</sup>;
}

With the above function the button value is getting replaced with You Clicked Me <sup>3</sup>

I also tried with the comment statement that also didn’t succeed. How can add a superscripted text to the button?

Answer by Starx

You do not need script to do this. Use this instead

<button name="button" id="button" onclick="showSuper()">Click Me!</button>

Script

var showSuper = function() {
    var btn = document.getElementById('button');
    var spanSuper = "<sup>3</sup>";
    btn.innerHTML= "You Clicked Me " +  spanSuper;
}

Check Demo. Updated Demo with your solution

Read more

reading index value of a table row with many cells and reading the value from it using Jquery

Question by user679460

//PHP array   
 $Cashups = array(
    array(
        'cashup_id' => 146456,
        'display_time' => 'Wed 16th Mar, 9:55pm',
        'terminal_name' => 'Bar 1',
        'calculated_cash' => 389.20,
        'actual_cash' => 374.6,
        'calculated_tenders_total' => 1,551.01,
        'actual_tenders_total' => 1,551.01
    ),
    array(
        'cashup_id' => 146457,
        'display_time' => 'Wed 16th Mar, 9:56pm',
        'terminal_name' => 'Bar 2',
        'calculated_cash' => 493.3,
        'actual_cash' => 493.3,
        'calculated_other' => 1509.84,
        'actual_other' => 1509.84
    )
);

HTML

<?php foreach ($Cashups as $Cashup) { ?> 
<tr>
    <td class="Left"><?php echo $Cashup['display_time']; ?></td>
    <td><?php echo $Cashup['terminal_name']; ?></td>
    <td><?php echo number_format($Cashup['calculated_cash'], 2); ?></td>
    <td class="clickchange"><a  href="#"><?php echo number_format($Cashup['actual_cash'], 2); ?></a></td>
    <td><?php echo number_format($Cashup['calculated_other'], 2); ?></td>
    <td><?php echo number_format($Cashup['actual_other'], 2); ?></td>
</tr>
<?php } ?>

Jquery

I am able to input text boxes when clicked on the link(clickchange) with the help of an answer sent by user on stackoverflow.
I can read the values but am not able to read the indexes of the links when clicked. I would like to know how to apply each on function to read the indexes of the link. Once I read the inexes I can then update the td with thier respective values.

Please help. How do I read text?

Answer by Starx

I am guessing you want the index when clickChange is clicked.

$("td.clickchange").click(function() {
    var i = $(this).parent("tr").index();
    alert(i);
});
Read more

How to give css class to the OK button of dialog in JQuery?

Question by Girish Chaudhari

I am new in Jquery. I have a code for dialog.

$(this.choosePadsContainer).dialog({ 
        title: 'Choose pad locations',
        autoOpen: false,
        modal: true,
        buttons: { "OK": function () {
            //Extract all checked pad locations.
            var checkedPads;
            checkedPads = new Array();
            $(self.padLocationsForActivity + " input:checked").each(function (index, value) {
                checkedPads.push($(value).val());
            });
            //Set selected pad text.
            setSelectedPadText(self.selectedPadsLblIdFormat, $(self.hiddenActivityAreaCode).val(), checkedPads);
            $(this).dialog("close");
        }
        }
    });

I want to give css class to the OK button. How will it be done?

Answer by Jo-Herman Haugholt

AFAIK it’s not directly supported, but something this should work:

$(".ui-dialog-buttonset .ui-button", this.choosePadsContainer).addClass("foo");

Answer by Starx

I think you can do something like this.

$(window).load(function() {
    $("span[class=ui-button-text]:contains('OK')").each(function() {
          $(this).addClass("myClass");
    });
});
Read more

str_replace “|” using php

Question by Jean

I want to insert "|" in place of space " " using str_replace, but when I use it

str_replace("|", " ", $word);

All space between the words were deleted. Any help?

— The code

$word=explode(" ",$FromForm);
$word_count - str_word_count($_post['xxx'];
for($i=0;$i<=$word_count;$i++) {
   echo str_replace("|"," ",$word[$i]);
   //it echos fine without the string replace
}

Answer by Starx

I think you got the function the wrong way, if you are trying to replace certain text with |, then you have to do something like this.

str_replace(" ","|",$word);

UPDATE

Since you exploded $FromForm by " ", there will be nothing to replace by str_replace later on.

Read more
March 27, 2011

convert this link to POST mode

Question by homlyn

How can I convert this $_GET method to $_POST method?

$linkword .= "n<A HREF="$self?letters=$alpha[$c]$letters&n=$n">$alpha[$c]</A> ";

Answer by Starx

Instead of creating a anchor tag. Create a hidden form

$linkword .= "n<A HREF="$self?letters=$alpha[$c]$letters&n=$n">$alpha[$c]</A>";

Here is a Sample

<form name="hiddenform" method="POST" action="page.php">
   <input type="hidden" name="letters" value="<? echo alpha[$c].$letters; ?>" />
   <input type="hidden" name="n" value="<? echo $n; ?>" />
   <a onclick="document.forms['hiddenform'].submit();">Test Link <? echo $alpha[$c]; ?></a>
</form>

Jsfiddle Demo

Read more

Which is a less expensive query count(id) or order by id

Question by Alocus

I’d like to know which of the followings would execute faster in MySQL database. The table would have 200 – 1000 entries.

  SELECT id 
    from TABLE 
order by id desc
   limit 1

or

SELECT count(id) 
  from TABLE

The story is the Table is cached. So this query is to be executed every time before cache retrieval to determine whether the cache data is invalid by comparing the previous value.

So if there exists a even less expensive query, please kindly let me know. Thanks.

Answer by RichardTheKiwi

If you

  1. start from 1
  2. never have any gaps
  3. use the InnoDB engine
  4. id is not nullable

Then the 2nd could run [ever so marginally] faster due to not having to visit table data at all (count is stored in metadata).

Otherwise,

  • if the table has NO index on ID (causing a SCAN), the 2nd one is faster

Barring both the above

  • the first one is faster


And if you actually meant to ask SELECT .. LIMIT 1 vs SELECT MAX(id).. then the answer is actually that they are the same for MySQL and most sane DBMS, whether or not there is an index.

Answer by Starx

I think, the first query will run faster, as the query is limited to be executed for one row only, 200-1000 may not matter that much in this case.

Read more
March 24, 2011

Regex Query To seperate and extract two different set from a string?

Question by mrN

I need to extract two seperate information from a string.

For example,

$string = 'int(5)';
//Now I need "int" and the text inside the brackets "5" seperately;
$datatype = ?
$varlength = ?

How to extract those information?

Answer by Czechnology

Use this regex

^([a-z]+)(([0-9]+))$

if (preg_match('~^([a-z]+)(([0-9]+))$~i', 'int(5)', $matches)) {
  $datatype  = $matches[1]; // int
  $varlength = $matches[2]; // 5
}

EDIT

If you want to match more than just a number in the brackets, expand it as necessary:

^([a-z]+)(([0-9a-zA-Z, ]+))$ // numbers, letters, comma or space
^([a-z]+)(([^)]+))$          // anything but a closing bracket

Answer by Starx

In the case. you want to match anything inside the brackets, use this

preg_match('/^([a-z]+)(([a-zA-Z0-9,]+))$/', 'enum(1,a)' , $matches);
print_r($matches);
Read more
March 23, 2011

difference when using & and not using &

Question by Hacker

Possible Duplicate:
Reference – What does this symbol mean in PHP?

Hi,
I was using like

$formCheckbox = $form->addElement('radio',...);
$formCheckbox->setChecked(true);

this was working on windows properly but was not on linux i.e it was not checking the radio button.

so i changed it like

$formCheckbox = **&**$form->addElement('radio',...);
$formCheckbox->setChecked(true);

so i just used & while creating the element. I just wanted to know how does it make a difference. I am using HTML quick forms.

Answer by sharpner

in this case there is not much of a difference, because php handles objects internally as pointers..

but as long as you do not know what & stands for, don’t use it..

a short introduction to pointer:

$a = 10; 
$b = &$a; 
$b = 20; 
echo $a; -> 20 

$a = 10; 
$b = $a; 
$b = 20; 
echo $a; -> 10

so with & you only reference to another variable, instead of creating a new one

Answer by Starx

It is passing the variable as a reference, so that the changes are maintained always.

Check this http://php.net/manual/en/language.references.pass.php

Read more

(jQuery) How to delete all cell from this table?

Question by l2aelba

<table class="Table">
    <thead class="thead">
        <tr class="tr">
            <th class="th header">Done</th>
            <th class="th header">None</th>
            <th class="th header">None</th>
            <th class="th header">Done</th>
            <th class="th header">None</th>

            <tr>
                <td>info</td>
                <td>info</td>
                <td>info</td>
                <td>info</td>
                <td>info</td>
            </tr>
        </tr>
    </thead>
</table>

I want to delete all “None”s cell and all “info” of cells

http://jsfiddle.net/D6e4H/

Any idea ? Thanks

Answer by Furqan

use this

    $(".th:contains('None')") .remove();
    $("td:contains('info')") .remove();

Your jsFiddle has been updated.

Answer by Starx

I think you are looking for this

$("th:contains('None')").each(function(index,value) {
    //Grab all the "None" th and their indexes
    $("tr td:nth-child("+$(this).index()+")").remove();
    //remove the td with the same indexes on the next tr
    $(this).remove();
    // now also remove the "None" th
});

Here is your Solution

Read more
...

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