...

Hi! I’m Starx

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

css rules not showing up

Question by Anders Kitson

I have the following css rules set for #container nav at this site

#container nav {
    margin-left: none;
    margin-right: none; } }

although when I use inspector the margins are not written, the selector is just empty no rules at all. Not sure what could be causing this. How do I debug this?

Answer by sweetamylase

Should be:

#container nav {
    margin-left: 0;
    margin-right: 0;
}

none is not a proper value for margin. Should use 0.

Answer by Starx

none is not an acceptable value for margin. Use 0 instead.

Read more

After MYSQL query return if the row was updated or inserted

Question by Joris Blanc

So I’m working on a part of my website where users can uprate and downrate content, this is stored one row per rating with a +1 for an upvote and a -1 for a downvote.

I also will be having a total of upvote - downvotes of the users profile page. The total of these votes will be stored in the mysql table of the users information.

My problem is that when someone votes something, lets say a downvote so I substract one to the total value of the votes on the users profile. But then if the user changes his mind and modifies the vote to an upvote well for the final value to be right I have to actually add 2 ( +1 to compensate the -1 and an other +1 for the upvote)

$sql = "    
    INSERT INTO `votes`
    (
        `added_by`, 
        `value`,
        `post_id`,
        `ip_created`
    )  VALUES (
        '".$logedInUser['User_ID']."',
        '".$value."',
        '".$this->post_id."',
        '".ip2()."'
    )
    ON DUPLICATE KEY UPDATE `value` = '".$value."'
";
$db->sql_query($sql);

I know that I can figure out a way to do it, but it will require a few other queries and I’m hopping there is a way to be able to return if it was inserted or updated. (I know that the query will only return TRUE or FALSE)

Answer by Starx

Based on your current data structure, I think instead of the hack of adding 2 to balance the data when the user upvote and subtracting 2 when he downvotes again. Try this:

  1. You have to first remove the vote.
  2. Then cast another vote to make the change.
Read more

JQuery on click not working

Question by Jamie Fearon

I’m having strange behaviour where within the same file a change event is working but a click event isn’t. I understand I may have not posted enough code, but I just want to see if anyone knows why on event may work but another will not. Here is my code:

class AddBTS
  constructor: () ->

    $('#a').on 'change', (evt) => @a evt
    $('#b').on 'change', (evt) => @b evt
    $('#c').on 'click', (evt) => @c


  a: (evt) =>
    console.log 'a works'

  b: (evt) =>
    console.log 'b works'

  c: () =>
    console.log 'c works'

The html it refers to:

<input type="file" id="a">
<input type="file" id="b">
<button id="c">OK</button>

The events work fine on a and b, but the click event doesn’t work on c.

My compiled JS is executed after the DOM loads.

Could anyone give me some pointers on what may cause this and I will try it out.

Interestingly, when I double click on c I get the following error:

Error in event handler for 'undefined': IndexSizeError: DOM Exception 1 Error: Index or size was negative, or greater than the allowed value.

Answer by user1737909

You have to call your c function :

@c()

Without parens, you’re only accessing it. Remember, CoffeeScript isn’t Ruby ;).

Answer by Starx

I dont think you need the evt since you are not using it.

$('#c').on 'click', () => @c
Read more

What's wrong with this PHP code dealing with the database

Question by Rogers

Ok , so I am trying to dynamically insert elements into two arrays , which are $prov_date and $decom_date. The thing is that when I test the elements that are entered for both arrays .. $decom_date has all the 2 dates pushed into the array when the status is decommissioned ,which is correct but $prov_date only has one element pushed into the array and it should have also 2 dates as shown in the database table, but only one date is there .. what could be wrong with my code below for the provisioned status ?

 $prov_sql2 = '
  SELECT
    date_format(StatusChangeTimestamp,"%d-%m-%Y %H:%m") as StatusChangeTimestamp,
    date_format(StatusChangeTimestamp,"%e/%c/%Y %H:%m") as display_StatusChangeTimestamp,
    month(StatusChangeTimestamp) as prov_month,
    year(StatusChangeTimestamp) as prov_year,
    date_format(StatusChangeTimestamp,"%d-%m-%Y %H:%m")as display_date,
    Status
  FROM 
    STxStatusChangeHistory
  WHERE 
    ESN = "'.$row2["ESN"].'"';

 $prov_date  = array();
 $decom_date = array();
 $prov_result2 = mysql_query($prov_sql2);

 while ($prov_row2 = mysql_fetch_array($prov_result2, MYSQL_ASSOC)) {
   if ($prov_row2['Status'] == "Provisioned") {
     array_push($prov_date, $prov_row2["display_date"]);
   }

   if ($prov_row2['Status'] == "Decommissioned") {
     array_push($decom_date, $prov_row2["display_date"]);
   }

 }

@Starx this is what is returned from the query

array(6) { ["StatusChangeTimestamp"]=> string(16) "16-10-2010 13:10" ["display_StatusChangeTimestamp"]=> string(16) "16/10/2010 13:10" ["prov_month"]=> string(2) "10" ["prov_year"]=> string(4) "2010" ["display_date"]=> string(16) "16-10-2010 13:10" ["Status"]=> string(11) "Provisioned" } array(6) { ["StatusChangeTimestamp"]=> string(16) "18-10-2010 10:10" ["display_StatusChangeTimestamp"]=> string(16) "18/10/2010 10:10" ["prov_month"]=> string(2) "10" ["prov_year"]=> string(4) "2010" ["display_date"]=> string(16) "18-10-2010 10:10" ["Status"]=> string(14) "Decommissioned" } array(6) { ["StatusChangeTimestamp"]=> string(16) "12-10-2010 13:10" ["display_StatusChangeTimestamp"]=> string(16) "12/10/2010 13:10" ["prov_month"]=> string(2) "10" ["prov_year"]=> string(4) "2010" ["display_date"]=> string(16) "12-10-2010 13:10" ["Status"]=> string(12) "Provisioned " } array(6) { ["StatusChangeTimestamp"]=> string(16) "14-10-2010 13:10" ["display_StatusChangeTimestamp"]=> string(16) "14/10/2010 13:10" ["prov_month"]=> string(2) "10" ["prov_year"]=> string(4) "2010" ["display_date"]=> string(16) "14-10-2010 13:10" ["Status"]=> string(14) "Decommissioned" } array(1) { [0]=> string(16) "16-10-2010 13:10" }

Answer by Dave Hale

You have a space after the provisioned in your db table for the 2nd entry.

Use trim maybe to ensure no whitespace carried over from the db.

if (trim($prov_row2['Status']) == "Provisioned") {

Answer by Starx

How about you change your implementation. Is basically does the same thing.

$prov_date[] = $prov_row2["display_date"];
Read more

jQuery syntax error?

Question by user1977591

I found an example here on stackoverflow that I am trying to recreate and use a solution.
here is the link to the example: Refreshing Partial View in MVC 3

what is wrong with my syntax?

function RefreshPartial() {
        $('#invited-teams').load('/Challenge/GetInvitedTeams', {Model.ChallengeId});
    }   

will this work? or does it need to have the curly brackets?

function RefreshPartial() {
        $('#invited-teams').load('/Challenge/GetInvitedTeams', "<%= Model.ChallengeId %>" );
    }   

UPDATE:

 function RefreshPartial() {
        $('#invited-teams').load('/Challenge/GetInvitedTeams',
            {'paramname' : <%:Model.ChallengeId %> });
    }   

my partial view:

            <div id="invited-teams">
                <% Html.RenderPartial("InvitedTeams", Model.InvitedTeams); %>
            </div>

So, this is what my refreshPartial method is looking like:

function RefreshPartial() {
        alert("in refresh partial");
        alert("<%:Model.ChallengeId %>");
        $('#invited-teams').load('/Challenge/GetInvitedTeams', { 
            'paramname': '<%:Model.ChallengeId %>'
        });


    }

it alerts both alerts correctly, with the 2nd one having the correct ChallengeID. The page is still going blank though. hmm..

Answer by Starx

Your function does not specify a parameter name.

function RefreshPartial() {
    $('#invited-teams').load('/Challenge/GetInvitedTeams', {
       'paramname' :'<%:Model.ChallengeId %>'//Or your ASP wrapper here
    });
}  
Read more

Change ID attribute dynamically in for-loop

Question by Dymond

The title could be misleading but i will try to explain.

I have an Ajax function that gets the value of some XML nodes. Now I want to change the ID of every created element with value of the xml-nodes.

I have something like this.
XML file

<notes>
    <note>
        <text>Hello Dog</text>
        <id>1</id>
    </note>
    <note>
        <text>Hello Cat</text>
        <id>1</id>
    </note>
</notes>

Now for call every text node I use a loop

stickers = myXML.getElementsByTagName("note");
for( i = 0; i < stickers.length; i++) {
    var idNod =  (stickers[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
    var textNod = (stickers[i].getElementsByTagName("text")[0].childNodes[0].nodeValue);
    add_sticker(idNod);
    add_sticker(textNod);
}

// add_sticker() is the function that created the elements dynamically …

So the output of this will become

Note1 = Hello Dog id 1,
Note2 = Hello Cat id 2

But I want somehow to use the idNod and use it as ID attribute
so it would look something like this

<div id=1>hello dog</div>
<div id=2>hello Cat</div>

In the loop I entered

stickers[i].setAttribute("id", idNod);

But that didn’t do anything, not neither gave me an error.

Answer by Starx

Why does your add_stickers are called twice to create one element? You should design your function to take both values and create the element.

function add_sticker(idNod, textNod) {
    var div = document.createElement("div");
    div.id = idNod;
    div.innerHtml = textNod;

    //Other parts
};
Read more

jQuery Ajax Appears to be POSTing but can't catch the values

Question by MG55114

What am I missing here?

I am trying to pass an array of strings via a jQuery AJAX POST.

var json = JSON.stringify( selectedTags );
var data = json;

var apiCall = $.ajax({
    url: "service-getemails-multiple.php",
    data: data,
    type: "POST"
    //beforeSend: alert(data)
}).done(function(data) {
    $(".ui-dialog-titlebar-close").show();
    var html = '<textarea style="width: 100%; height: 90%" id="emailsTextbox">' + data + '</textarea>';
    html += data;
    html += "" target="new">Send Email</a></p>";
    $("#dialog").html(html);
    $("#emailsTextbox").focus();
    $("#emailsTextbox").select();
});

My catcher (“service-getemails-multiple.php”) is currently extremely simple and I don’t understand why it’s failing to catch the AJAX request (POST).

<?php

var_dump($_POST);

?>

In Firebug, I can see the values being passed under XHR/Post as parameters and under source. If I uncomment “beforeSend: alert(data)” that alerts the values just fine.

So what am I doing wrong?

Answer by ITroubs

try this:

var json = JSON.stringify( selectedTags );
var thedata = json;
....
var apiCall = $.ajax({
    url: "service-getemails-multiple.php",
    data: {mydata: thedata},
    type: "POST"
    //beforeSend: alert(data)
}).done(function(data) {
    $(".ui-dialog-titlebar-close").show();
    var html = '<textarea style="width: 100%; height: 90%" id="emailsTextbox">' + data + '</textarea>';
    html += data;
    html += "" target="new">Send Email</a></p>";
    $("#dialog").html(html);
    $("#emailsTextbox").focus();
    $("#emailsTextbox").select();
});

Answer by Starx

I think the function is confused about data: data part.

Try this

var apiCall = $.ajax({
    url: "service-getemails-multiple.php",
    data: json, // <!-- Use json instead. Its the same thing
    type: "POST"
    //beforeSend: alert(data)
}).done(function(data) {
    $(".ui-dialog-titlebar-close").show();
    var html = '<textarea style="width: 100%; height: 90%" id="emailsTextbox">' + data + '</textarea>';
    html += data;
    html += "" target="new">Send Email</a></p>";
    $("#dialog").html(html);
    $("#emailsTextbox").focus();
    $("#emailsTextbox").select();
});
Read more

How to control jQuery events when you have nested HTML?

Question by Cristian David Jimenez Duarte

For example:

<ul>
<li>
   first element
   <ul>
    <li> second element
       <ul>
          <li> third element </li>
       </ul>
      </li>
   </ul>
</li>
</ul>

<script>
$('li').click( function() {
   alert('hello world!!!');
});
</script>

The output is:

THREE ALERTS WHEN I CLICK THE THIRD ELEMENT

TWO ALERTS WHEN I CLICK THE SECOND ELEMENT

ONE ALERT WHEN I CLICK THE FIRST ELEMENT

How to prevent with jQuery this?

What I’m needing is: ONE ALERT FOR EACH CLICK IN ANY ‘LI’ ELEMENT.

Answer by Starx

As you have nested li elements. The click handler applies to all li elements including the parent li‘s.

You need to stop propagating the event bubble. So that once it execute the event handler, it does not goes up the DOM tree to trigger the same event.

$('li').click( function(e) {
   alert('hello world!!!');
   e.stopPropagation();
});
Read more

Add php within a string

Question by Brown

I want to take

$imgsrc = get_template_directory_uri() . '/s.php?strings=';

and add the_content_rss('', TRUE, '', 4) after strings.

How do I go about doing that?

$imgsrc = get_template_directory_uri() . '/titles.php?strings=' . the_content_rss('', TRUE, '', 4);

doesn’t seem to output a single URL.

Answer by Starx

First thing that you should understand is

String concatenation requires functions that return value not output/echo them.

So, make sure get_template_directory_uri() and the_content_rss('', TRUE, '', 4); returns a value instead of displaying them. If both functions return a value, the URL should be build as expected.

Read more
...

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