...

Hi! I’m Starx

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

URL prevent href button action php

User222914’s Question:

Hi I have a href tag where I order an array values(up to down or down to up),so my problem is that when I click twice in the same button I have no action performed.That because of in my url I have something like that:
When I click for the 1st time on my button the action is done,but I click again on the same button nothing,but when I click ‘F5’ action the action is done:
Exemple in my URL when I click one time:

http://localhost/home/test.php?dir=down&keyword=1

The second time I click the URL remains the same but no action is done.it is done when I click on F5.

My hyperlink:

echo "<a href="$_SERVER[PHP_SELF]?dir=down&keyword=$keywordkey"><img src=web/images/remove.png /></a>";

How can I resolve this ?
Thank you!!!

After you click on the button for the first time, you give command to your script to sort it downwards.

Once this action is complete, you still have same command to provide to your script i.e. down

Since it is a same command going to the your code, is does exactly same thus, the results are also same.

Read more

PHP referencing nested array values

Jpmyob’s Question:

I’m having trouble returning a value out of a nested array…

the array dump looks like this

object(myObj)#1 (3) { 
["thing1"]=> string(5) "abcde" 
["thing2"]=> string(2) "ab"
["data"]=> array(3) { 
    [0]=> string(3) "370" 
    ["id"]=> string(3) "370" 
    [1]=> string(26) "" 
    ["name"]=> string(26) "abcdefghijklmnopqrstuvwxyz" 
    [2]=> string(0) "" 
    ["address"]=> string(0) "" 
    [3]=> string(4) "wxyz" 
    ["email"]=> string(4) "wxyz"
}

I want to get to “name” inside the “data” array….

I’ve tried

echo $myObj['data']['name'];

also

echo $myObj -> $data -> $name;

they always come back as UNDEFINED.

Use

$myObj -> data['name'];

It sure is confusing. Let me explain.

The var_dump result you saw has two parts on them, one is object dump and another array .

object(myObj)#1 (3) {  <-- Starting point of object

["thing1"]=> string(5) "abcde"  <-- This is a property which has string value

["thing2"]=> string(2) "ab"     <-- This is a property which has string value


"data" here is a property of 
       object so you have to use
       $myObj -> data to access it

["data"]=> array(3) {           <-- But this is an array so you have to use 
                                    data[] to access its value
    [0]=> string(3) "370" 
    ["id"]=> string(3) "370" 
    [1]=> string(26) "" 
    ["name"]=> string(26) "abcdefghijklmnopqrstuvwxyz" 
    [2]=> string(0) "" 
    ["address"]=> string(0) "" 
    [3]=> string(4) "wxyz" 
    ["email"]=> string(4) "wxyz"
}
Read more

Why cant we use &lt;wrapper&gt;&lt;/wrapper&gt;?

Shannon Hochkins’s Question:

I can use something like <section id="wrapper"></section>, however because I’m so pedantic, is there anything wrong with using <wrapper></wrapper> as my html element?

I’m using html5 shiv and modernizer, it does work fine however I just wanted to know if there’s anything particularly wrong with doing it this way.

<section> elements represent a section in the page, not YOUR LAYOUT. This is very important and is confused by most of starters in HTML5 including me.

Let me show where you are wrong, using another example:

<section id="banner">
</section>

Banners are a part of layout not web content. Thus they do not have any section. They have to represented by <div> as they used to be in HTML 4.

<section id="wrapper">...</section>

Is wrong in the same way, because wrappers are purely layout specific tasks, thus it does not represent any specific content on your page. <sections> should always represent differentiated content and not others.

Here is an example of HTML5, that can be considered valid.

<div id="wrapper">

    <section id="mainArticle">

    </section>
    <section id="aboutAuthor">

    </section>
    <aside id="relatedArticles">

    </aside>

</div>
Read more
May 20, 2013

Storing cookies for future form submissions

Yosef Naser’s Question:

Is there any way to store data submitted in cookies and when the same form is loaded again the text fields are filled with the stored values in cookies ?

I have a shopping website and i don’t wanna require customers to register, so when they order an item and come back again to order another item the form is prefilled with their information.

I’ve looked around but no one seems to mention such thing.

You can use $_COOKIE[] to access and retrieve information stored in cookie.

Read more

what is wrong with my code? it should output 0-9 but it failed to do so. I think the error is in go()

User2384484’s Question:

Can you help me debug this code? I can’t see the errors in it. There is also no ouput to determine the error.

 function go()
{
    var procedures = [];

    for (var i = 0; i < 10; i++) 
    {
        procedures[procedures.length] = function () 
        {
            alert("You are now " + i + " years old");
        } 
        run_procs(procedures);
    }

    function run_procs(procs) 
    {
        for (var i = 0; i < procs.length; i++)
        {
            procs[i]();
        }
    }

    go();
}

You have executed the function inside the function. Put go(); outside.

Read more

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");
        });

    }
});
Read more
May 18, 2013

JQuery Load, Notify Calling Window?

MvcNewbie’s Question:

I am using the JQuery event “load” to notify when the entire html window has loaded as well as all scripts have executed. I understand the intention of this function is to be used with in the document.ready event. However, I have one window spawning other windows and I need for the parent window to be notified when the child window is completely finished loading so I can insert saved content. Can anyone please guide me in the right direction.

Thank you!

You can check the loaded event using load event

$('#iframe').on('load', function (e) {
   //.......
});
Read more
May 17, 2013

jQuery.post not receiving errors from php script

Preahkumpii’s Question:

I know this has been asked before and I have looked at every post I could find that deals with this. I still cannot get the jQuery.post function to correctly receive the error from a php script. Here are both.

PHP:

<?php 
##CONFIGURATION
# LIST EMAIL ADDRESS
$toemail = "email here";

# SUBJECT (Subscribe/Remove)
$subject = "Someone has contacted International Designs";

# RESULT PAGE
$location = "../thank-you.php";

## FORM VALUES ##
$myname = $_REQUEST['myname'];
$myemail = $_REQUEST['myemail'];
$mymessage = $_REQUEST['mymessage'];

if ( empty($myname) || empty($myemail) || empty($mymessage) ) {

    exit('{"error":"That value was invalid!"}')

} else {

    # SENDER
    $email = $myname . " <" . $myemail . ">";

    # MAIL BODY
    $body .= "Name: " . $myname . " nn";
    $body .= "Email: " . $myemail . " nn";
    $body .= "Message: " . $mymessage . " nn";
    # add more fields here if required

    ## SEND MESSGAE ##

    mail( $toemail, $subject, $body, "From: $email" ) or die ("Mail could not be sent.");

}

?>

JS:

if (verify(myname, myemail, mymessage, human, hash, patt)) {
  $.post(myform.attr('action'), myform.serialize(), function() {
    $('#email-success').fadeIn();
    myform[0].reset();
    setTimeout("$('#email-success').fadeOut();", 5000);
  }, 'json')
  .fail(function() {
    alert('An error has occurred. Please try again later.')
  });
}

I have tried about 5 different methods already, none of which have worked. When I put ‘json’ as the datatype in the .post function the .fail always fires, no matter what’s in the php script. If I leave datatype out, then .fail never fires under any circumstance. I have a feeling the problem is with the php commands and datatype. Any help is appreciated.

Although, yours is a valid JSON data, I always recommend to use json_encode() function to create JSON string.

exit(json_encode(array("error" => "That value was invalid!")));

Another is make sure you send correct headers to ensure the script knows its a json data. So

header('Content-Type: application/json');
exit(json_encode("error" => "That value was invalid!"));
Read more
May 16, 2013

Parse error: syntax error, unexpected T_STRING in /// on line 3

User2373405’s Question:

i have writeen a php code to replace SQL row values. but some thing went wrong when i ran this.

ERROR : Parse error: syntax error, unexpected T_STRING in …… on line 3

i think i should not use these " " right ? any other corrections…

when i ran this without " " got this error

Error updating comment table: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘1’ at line 1

<?php    
include_once("db.php");    
$sql1 = "update table1 set marks = replace(c2,"NK",'NOKIA')";
$sql2 = "update table1 set marks = replace(c2,"SM",'SAMSUNG')";
$sql3 = "update table1 set marks = replace(c2,"A",'APPLE')";
$sql4 = "update table1 set marks = replace(c2,"CH",'CHINAPECE')";
$sql5 = "update table1 set marks = replace(c2,"WO",'WORLDCLASS')";
if (mysql_query($sql1 && $sql2 && $sql3 && $sql4 && $sql5))
  {
  echo "Replaced.";
  }
else
  {
  echo "Error in replacing: " . mysql_error();
  }
?> 

Thank you!

Your problem is due to unescaped quotes. Use Single Quotes to define the values in a query string. It is less confusing that way.

Also there is a problem with the statements. Since you are combining statements they have to terminated using delimeter ;

$sql1 = "update table1 set marks = replace(c2,'NK','NOKIA');";
$sql2 = "update table1 set marks = replace(c2,'SM','SAMSUNG');";
$sql3 = "update table1 set marks = replace(c2,'A','APPLE');";
$sql4 = "update table1 set marks = replace(c2,'CH','CHINAPECE');";
$sql5 = "update table1 set marks = replace(c2,'WO','WORLDCLASS');";

And query like this:

mysql_query($sql1);
mysql_query($sql2);
mysql_query($sql3);
mysql_query($sql4);
mysql_query($sql5);

NOTE: Please dont use MYSQL_* API Functions they are deprecated

Read more

JQuery single click event on a group of buttons

Ahmd0’s Question:

I’m using the following JQuery code to trap clicks on a single button:

$(function () {

    //Set up click event on the Remove button
    $('#ButtonRemove').click(function (event) {
    //Process button click event
    }
}

where the HTML itself is this:

<input type="submit" name="ButtonRemove" value="Remove Now" id="ButtonRemove" />

But one of my pages is generated dynamically, which means that it can have a variable number of Remove Now buttons, each having the following HTML:

<input type="submit" name="ButtonRemove_01" value="Remove Now" id="ButtonRemove_01" />
<input type="submit" name="ButtonRemove_02" value="Remove Now" id="ButtonRemove_02" />
...
and so on

So can I adjust my JQuery statement to catch all those buttons in one method?

EDIT: Wow. Thank you everyone! There’re so many ways to do it. JQuery is very handy!

There are several ways. If you want to catch event for all submit buttons.

$(":submit").on("click", function() {
 // Carry on
});

But it seems like you are trying to select element that start with ButtonRemove. So

$("[name^='ButtonRemove']").on("click", function() {
    // This function will apply on the elements whose name start with "ButtonRemove"
});
Read more
...

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