...

Hi! I’m Starx

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

Send a message when pressing Enter

Question by Sora

Here is my code:

<input type="text" id='MsgToSend" + ToClient + "t" + FromClient + "' onkeypress='ClientOnTyping();' />

where the FromClient and the ToClient are dynamically generated.

JavaScript:

function ClientOnTyping() {
  if(e.keyCode==13) {
     // i know i should do this but my problem is what is 'e' in my case how can i specify it ?
  }

}

Answer by Starx

You need to attach an event listener on the element for keydown event.

var btn = document.getElementById('MsgToSend');
btn.addEventListerner('keydown', function (e) {
    if(e.keyCode==13) {
     // i know i should do this but my problem is what is 'e' in my case how can i specify it ?
    }
});

On traditional browsers, you can attach the event handler this way.

var btn = document.getElementById('MsgToSend');
btn.onkeydown = function (e) {
    e = e || window.event;
    var keyCode = e.keyCode || e.which;
    if(keyCode==13) {
     // i know i should do this but my problem is what is 'e' in my case how can i specify it ?
    }
});
Read more

why is jqXHR.responseText returning my PHP file and not executing the script?

Question by Mr.Student

I’m trying to simply execute an ajax request to my server. The request passes my form data to signUp.php where the information is then process. Then php will echo back a responseText to my jqXHR object and I print the alert. The problem is that my php file is being executed, rather the jqXHR.responseText is instead returning the my php file itself as if it were a text file. A sample php responseTest would look like …

"<?php
 php code ...
  ?>"

Instead I want the responseText to return my echoes. The code is written bellow.

            var formData = new FormData(document.getElementById("signUpForm"));
            $.ajax({
                url: "./cgi-script/signUp.php",
                type: "POST",
                xhr: function giveXmlHTTP(){
                    myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload){
                        myXhr.upload.addEventListener('progress',progressHandler, false);
                    }
                    return myXhr;
                },
                success: function(data,statusText,jqXHR){
                    alert(jqXHR.responseText);
                },
                data:formData,
                cache: false,
                contentType: false,
                processData: false
            });

        }

Answer by Starx

These generally happens when PHP does not gets parsed. So make sure you are running on the SERVER which is capable and configured to run PHP and are not double clicking the HTML page.

Read more

Insert statement not working using execute(array()) of PDO Extension

Question by shnisaka

 $stmt = $conn->prepare("INSERT INTO user VALUES ('',:username,md5(:password),'',1,'','',:email,'',0,0,'',:cover,:dateofbirthYear:dateofbirthMonth:dateofbirthDay,NOW(),:sex,:country)");
 $stmt->execute(array(
  ':username'   => $username,
  ':password' => $password,
  ':email'   => $email,
  ':cover' => $cover,
  ':dateofbirthYear'   => $dateofbirthYear,
  ':dateofbirthMonth' => $dateofbirthMonth,
  ':dateofbirthDay'   => $dateofbirthDay,
  ':sex' => $sex,
  ':country'   => $country 
    ));

For some reason this insert statement is not working. I am very new in PDO so I do not know much about it. What am I doing wrong?

this statment gives me this error :

Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens’ in /home/manga/public_html/new/register.php:80 Stack trace:
#0 /home/manga/public_html/new/register.php(80): PDOStatement->execute(Array)
#1 {main} thrown in /home/manga/public_html/new/register.php on line 80

Answer by Starx

You have prepared your query in the wrong way

INSERT INTO user VALUES ('',:username,md5(:password),'',1,'','',:email,'',0,0,'',
:cover,:dateofbirthYear:dateofbirthMonth:dateofbirthDay,NOW(),:sex,:country
     // ^ These need to either single or separated

For what you are trying, you can do it this way

//Prepare the date of birth earlier
$dob = $dateofbirthYear.$dateofbirthMonth.$dateofbirthDay;

//Then pass it as a single $variable

$stmt = $conn->prepare("INSERT INTO user VALUES ('',:username,md5(:password),'',1,'','',:email,'',0,0,'',:cover,:dob,NOW(),:sex,:country)");
 $stmt->execute(array(
  ':username'   => $username,
  ':password' => $password,
  ':email'   => $email,
  ':cover' => $cover,
  ':dob'   => $dob, // <-- Problem solved
  ':sex' => $sex,
  ':country'   => $country 
    ));
 // Then it will execute
Read more

$(this).attr not working

Question by user1716672

I’m using fancybox and I want to get the element class before fancybox executes. So I have:

$(".agent-file-popup").fancybox({
    'onStart': function () {
        console.log($(this).attr('class'));
        console.log($(".agent-file-popup").attr('class'));
        return true;
    }
});

The first log outputs “undefined” but the second log outputs the correct class. Why can I not use “this” as the element in this situation?

Answer by Starx

$(this) is one of very popular construct to indicate current element is focus, which can be used inside event and selector functions. This is as equal to JavaScript’s this construct wrapped by jQuery’s function to provide access to jQuery’s function.

$(".user").click(function() {
    //Here $(this) will represent the element that was click with class .user
});

Plugins are generally developed as extensions to jQuery’s jQuery() function, they are hardly responsible to detect the current element.

So, when you are initializing the plugin $(this) might easily represent nothing.

Fancybox has a way to get the current element.

onstart: function(itemArray, selectedIndex, selectedOpts){
 // selectedIndex holds the current selected box on itemArray as the collection object.
}
Read more

Running a Zend Framework Project on a shared server

Question by Mikey

I’m trying to upload my ZF Project to shared hosting

On my XAMPP, ZF’s index page is located (and I access my page) at http://localhost/ZFprojectname/public

On the shared hosting in the root directory I have installed Joomla.

I want to access my ZF in the manner of http://mywebsite.com/booking/

so in this case, when going to http://mywebsite.com/booking/ I should be accessing ZF’s public folder (as far as I understand).

And, I’d like to put my ZFproject in public_html/somefolderName/

How would you do it?

Answer by Starx

Shared hosting do not support defining Document Root path so you can use .htaccess to forward the request to public folder instead.

Create a .htaccess file inside the booking directory with the following rule.

RewriteEngine On

RewriteRule ^.htaccess$ - [F]

RewriteCond %{REQUEST_URI} =""
RewriteRule ^.*$ /public/index.php [NC,L]

RewriteCond %{REQUEST_URI} !^/public/.*$
RewriteRule ^(.*)$ /public/$1

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^.*$ - [NC,L]

RewriteRule ^public/.*$ /public/index.php [NC,L]
Read more

how do i replace certain words in a sentence with php

Question by Imtiaz

Suppose I have this sentence: “The president obama came back to america from africa with his family”.

How do I replace “obama” with “bush”?

Answer by Starx

Using str_replace() functions:

$sentence = "The president obama came back to america from africa with his family";
$changed = str_replace("obama", "bush", $sentence);
Read more

jQuery simulate click

Question by Bwyss

I want to trigger a function when the page is loaded, I can see here: jQuery call function after load that there are many ways to do this.
However when I add $('#button').click in front of my function then the ‘getType function’ is not recognized. For example:

$('#button').click(function getType(id) {
    //...some code
});

error: getType is not defined

What am I doing wrong?

Answer by Starx

The .click() method requires a callback function. So you can do something like this instead:

//Define your function somewhere else
function getType(id) {
    //...some code
}

$('#button').click(function() {
    getType($(this).attr('id')); //Execute it when its clicked.
});
Read more

Opening a new page on website exit

Question by user2152403

What I want is to have a new page or pop up to be activated when:

  1. a visitor on my website closes the browser
  2. a visitor on my website types another URL in his browser.

I have this JS, but it is activating a new website (www.newpage.com) also als for internal links. How can I disable this action for internal links?

<script type="text/javascript">
var leaving = true;
function checkUrl(href) {
    leaving = (((href.indexOf("http://") > -1) || (href.indexOf("www.") > -1)) && (href.indexOf(window.location.host) == -1));

}
function pop() {
    if(leaving) window.open("http://www.newpage.com");
}
window.onunload = pop;
var e = documents.getElementsByTagName("a");
for(var i=0;i<e.length;i++) e[i].onclick = "checkUrl(this.href)";
</script>

Answer by Starx

How can I disable this action for internal links?

Use specific links with id instead of getting all the anchors based on tag name.

var e = documents.getElementById("anchorId");
e.onclick = "checkUrl(this.href)";

Also, Listens to the comments. POPUPs are the big NO is current web world

Opening a new window when a user is actually trying to leave??? This may have the tendency to the make the viewer angry and never return on the site. BAD MOVE

Read more
March 8, 2013

Jquery Looping through elements created at runtime

Question by dev_darin

i have a list that is passed to a page and the elements are created at runtime. I would like to loop through these elements and preform some action for each element. Under is my code:
for each person that gets created from this list i would like to preform a check on that person. Can someone help me i am only getting the check happening once:

jQuery:

$(document).ready(function() {

    $("#userId").each(function(i){
        if ($("#userId").val != '') {
            alert('not null' + i);
        }
    });                 
});

JSP:

<c:forEach items="${person}" var="person">

<input= type="text" id="userId" value="${person.userid}" />
    First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Answer by Andbdrew

you cannot have multiple elements on a page with the same id attribute. try using classes instead.

try something like:

$(document).ready(function() {

   $(".userId").each(function(i){
       if ($(this).val() != '') {
           alert('not null' + i);
       }
   });
});

Another thing to note is that .val is a method, so you need to call it to get the value. Use .val() instead of .val. As you have your code now, $(selector).val is a function, so it will never be the empty string you are testing it against.

Also your JSP should be something like:

<c:forEach items="${person}" var="person">

<input= type="text" class="userId" value="${person.userid}" />
    First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Answer by Starx

Your loop will create multiple element with same ID, first change that. It is better to use class names instead.

<c:forEach items="${person}" var="person">

    <input= type="text" class="user" id="userId-${person.userid}" value="${person.userid}" />
       <!--             ^ Use Class &  ^ Id to uniquely identify the user -->
       First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Next you can use .find() to find even the dynamically generated element. But I recommend using my solutions using the class attribute.

$(".user").each(function(i) {
    if ($(this).val() != '') {
          alert('not null' + i);
    }
});
Read more

Is it possible to fire an event handler when the element is enabled or disabled?

Question by Rakesh Juyal

I want to execute a method when the input is enabled or disabled. Is it possible to do in jQuery?

I want to do something similar to this ( non-working code below ):-

$('input').on('enabled', function(e){
   alert( 'Just now someone enabled : ' + $(this).attr('id') );
   executeSomeHandlerForENABLED();
}).on('disabled', function(e){
   alert( 'Just now someone disabled : ' + $(this).attr('id') );
   executeSomeHandlerForDISABLED();
});

Answer by Starx

YES, but what you are trying is not an easy task.

What you can do is, use propertychange event (which by the way is not available on IE) to catch the change in properties.

I googled and found this solution implemented. A plugin to watch the property as it changes. For IE it fallbacks to setTimeout() which is very sad indeed.

Anyways, your solution utilizing that solution would be something like:

$("input").watch('disabled', function() {
    console.log($(this).is(":disabled"));
});
Read more
...

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