...

Hi! I’m Starx

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

How get data with jQuery.parseJSON

Question by Petr Šrámek

In page 1 I have this array:

$pole = array("countLike" => "countLike", "Message" => "Some message");
echo json_encode($pole);

And I want get this data on page 2, but this code doesn’t work.

function Like(id)
{
    $.post("page1.php", { action: "Like", "id": id }, function(data) {
        var obj = jQuery.parseJSON(data);
        $(".countLike#"+id).html(obj.countLike);
        $(".Message#"+id).html(obj.Message);
    });
} 

Can you help me please with this code.
Thanks.

Answer by Starx

Pass json as expected output from the post request.

function Like(id)
{
    $.post("page1.php", { action: "Like", "id": id }, function(data) {

        //data is already a json parsed string

        $(".countLike#"+id).html(data.countLike);
        $(".Message#"+id).html(data.Message);
    }, "json"); // <<<<< This is what you missed
} 
Read more

Check image type if renamed from .png to .jpg

Question by John

If it possible to check if the type of image if it was renamed from .png to .jpg?

I need this because when I use a resize function my website stop working if the uploaded image was renamed from .png to .jpg (I made my code to accept only .jpg images)

Answer by dev-null-dweller

getimagesize will contain info about image type:

$info = getimagesize('file.png');
if($info[2] == IMAGETYPE_JPEG){

}

Answer by Starx

You can always read the image type to check an image using exif_imagetype()

$image_type = exif_imagetype($filename);

Example:

<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
    echo 'The picture is not a gif';
}
?>
Read more

SEO URL based on category name without have a category id in URL

Question by Unknown Error

I have two table posts & categories

post_id | post_title  | post_content   | post_cat
--------------------------------------------------
1         Hello World  welcome to my..   1
.         ..           ..                ..

categories table

cat_id | cat_name | cat_parent
-----------------------------
1        News       NULL
2        Sports     1
.        ...        .. 

Let’s say current category link for news is http://domain.com/category/1/

MySQL statment

SELECT posts.post_id,
       posts.post_id,
       posts.post_title,
       posts.post_content,
       posts.post_cat,
       categories.cat_id,
       categories.cat_name,
       categories.cat_parent
FROM   posts
       INNER JOIN categories
         ON posts.post_cat = categories.cat_id  
       WHERE posts.post_cat = (int)$_GET['cat_id']

So we can get a result for post_cat = 1

According to my current database structure, how do I remove the ID but change it to be a nice slug? Example :-

Main category - http://domain.com/category/news/
Sub category  - http://domain.com/category/news/sports/

Let me know a clue how script will tell News is equal 1 on post_cat column?

Answer by Lix

You can use an .htaccess file to rewrite the URL’s for you.

The entry in the .htaccess file would look something like this :

RewriteEngine on
RewriteCond $1 ^category 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ parseCategoryUrl.php?q=$1 [L,QSA]

I’ll break down the lines here to help understand whats going on and what each line means :

  1. Turn the RewriteEngine on.
  2. This rewrite will only occur on URL’s where the first word after the host name is category – all URL’s starting with that word will be processed by the lines below.
  3. The rule will exclude URL’s that point to actual files !-f
  4. The rule will exclude URL’s that point to actual directories !-d
  5. The actual rule will capture the entire request_uri and pass it to the parseCategoryUrl.php file with the entire request as a parameter called q (query) in the $_GET array. The flags at the end of the rule (L,QSA) do two things.
    • L – This is the last rule. After processing this line the .htaccess file will stop performing actions on the current URL.
    • QSA – Append the query string to the rewritten URL (so that we can parse it later).

Your parseCategoryUrl.php file could contain something similar to the following :

$request = explode('/',$_GET['q'] );
array_shift($request);

The first line will split the request by slashes into an array – and the second line removes the word category from the beginning of the array (because we know that we are parsing a category URL).

The final $request array, with a URL example such as :
http://example.domain.com/category/news/sports
Will be this :

Array
(
    [0] => news
    [1] => sports
)

So you see here that you have now successfully split the URL into an array; All you have to do now is query your database and and provide the user with the correct page.
Because the parseCategoryUrl.php page in fact has no output, you could just use an include() function to insert the correct page according to the URL that was provided.


SEO is about making your pages and their URL’s more informative to search engines so that a user searching the internet will be able to receive page results that are related to their search query. A search engine looking at the URL :
http://domain.com/category/1/2
will not be able to extract much information. However if your URL contains (as your question requires), category information, then a search engine will be able to deduct that the specific URL is related to :

  • http://domain.com/category/news/ – news
  • http://domain.com/category/news/sports – sports news
  • http://domain.com/category/blog/ – blog
  • etc…

Answer by Starx

It is not as different as generate an url with id. Use the same logic to generate the url with title. However they way I see it, there is only one thing, you need to remember.

The category name has to be unique at all cost.

Place a .htaccess to ensure the titles are properly redirected you the page

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /category.php?title=$1 [L]

Then, instead of using id in the query use the title

SELECT posts.post_id,
       posts.post_id,
       posts.post_title,
       posts.post_content,
       posts.post_cat,
       categories.cat_id,
       categories.cat_name,
       categories.cat_parent
FROM   posts
       INNER JOIN categories
         ON posts.post_cat = categories.cat_id  
Where 
      categories.cat_name = 'News'

As for the subcategory also, the above query should work, since all the categories are placed in same table.

Read more

Folder with Get value

Question by Smile Applications

Could someone with more experience than me explain how it works the link (for example):

http://www.facebook.com/zuck  

I think it’s the same thing of this

http://www.facebook.com/profile.php?id=4

I imagine that “zuck” is a GET type string but I don’t understand how I can do the same thing.

Thank You very much

Answer by ilya iz

.htaccess file:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /profile.php?id=$1 [L]

Answer by Starx

Actually, i am not sure about it, but by the way I see it, facebook probably uses both ways to get to a profile

I quick .htaccess to make sure all the request arrive on same page.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /profile.php?input=$1 [L]

Now, in the profile.php, it should do a simple check like

$input = $_GET['input'];

if(is_string($input)) {
 // then retrieve profile id, based on the string
}
//now either way you have an unique identifier at last
//
//
// use your logic further more
Read more

Quit "tab" from ul with css

Question by matt

The list on html have by default a “tab” for each item that I want to erase.

HTML code:

<h2>list title</h2>
<ul>
    <li>item one</li>
    <li>item two</li>
    ...
    <li>item n</li>
</ul>

this is the css I have:

.notstyled{list-style-type:none;}

and looks like (the “|” will be like the edge of the screen):

|list title
|
|    item one
|    item two
|    ...
|    item n
|

what I’m looking for will be having the list items at the edge, like this:

|list title
|
|item one
|item two
|...
|item n
|

I know the example is very stupid..

Thanks in advance!

Answer by Starx

Clear the padding of the ul

ul { padding: 0; }

Just in case, you dont like the outer spacing of the ul clear the margin or padding as well.

ul {
    padding: 0;
    margin: 0;
}
Read more
March 2, 2012

Better way to get first element of returned array

Question by TecBrat

I found myself using this:

$var=(string)array_shift(array_values($item->xpath($s)));

where $s is an xpath search string and the return is an array of objects that contain strings.

It works, but I’m not sure it’s the best way to get the data I want.

I could use a tempvar, but I wanted to avoid that.

Any suggestions?

Answer by Mike Purcell

Careful with array_shift, as it will remove the element from the array stack, if you simply want the first value, you can use current:

$var = (string) current($item->xpath($s));

Answer by Starx

I believe this gives the same result.

$var=array_shift($item->xpath($s));
Read more

Am I protected from MySQL injection when I am using $this->data?

Question by huzzah

I am new to cakephp and security. I have read that security is built in for protection from MySQL injection if you follow cake’s conventions, but can someone tell me if my save() will be safe without manually calling the Security class?

function edit($id) {
 $this->set('title', 'Edit your property');
 $this->Unit->id = $id;    
 if (empty($this->data)) {        
$this->data = $this->Unit->read();    
} else { 

    if ($this->Unit->saveAll($this->data)) {            
        $this->Session->setFlash('Your property has been updated.');            

        }   
}
}

Answer by Achamenes

CakePHP will quote the data for you. Unless you are using a method similar to:

$this_year = date('Y-m-d h:i:s', strtotime('-1 year'));

$this->Baker->updateAll(
    array('Baker.approved' => true),
    array('Baker.created <=' => $this_year)
);

which takes SQL literals, you are safe and must not quote the data yourself to avoid getting the quotes in the data. Source: http://book.cakephp.org/2.0/en/models/saving-your-data.html

Answer by Starx

I will say no as your parameter is not specialised or sanitized anywhere. Something like this, would limit the risk

function edit($id) { 
   // type cast the id to be forced into number and check if $id has greater than 1 
   if((int)$id > 0) {

   // hence the injection vulnerability at $id is fixed
   //....remaining part
   }
}
Read more

How to close iframe from inside iframe?

Question by Luca Frank Guarini

I’ve got a WordPress site where posts are loaded into an iframe.

This is the code that works:

<a class="trick" rel="<?php the_permalink() ?>" href="<?php the_permalink() ?>"><?php the_title(); ?></a>

$(document).ready(function(){

    $.ajaxSetup({cache:false});
    $(".trick").click(function(){
        var post_link = $(this).attr("rel");
        $("#frame").css("display","block");
        $("#frame").attr("url", post_link);
        $("body").css("overflow","hidden");
    });

  });         </script>
<iframe id="frame" frameborder="no" allowtransparency="true" width="100%" height="100%" scrolling="no" src=""></iframe>

Now, how to close this loaded iframe from inside the iframe?

The main page is index.php (main wordpress loop), the content of the iframe is single.php (single post) without header and footer.

Thanks.


This is what i’ve got in single.php

<head>

<script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
    $(document).ready(function(){
        $("#close").click(function(){
            $('#frame', window.parent.document).remove();

             });

        });

    </script>


</head> 

<body>
<div id="container-single">
    <button id="close" >Close</button>



    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

        <article <?php post_class('single') ?> id="post-<?php the_ID(); ?>">

            <h1 class="entry-title"><?php the_title(); ?></h1>

            <div class="entry-content">

                <?php the_content(); ?>

                <?php wp_link_pages(array('before' => 'Pages: ', 'next_or_number' => 'number')); ?>

                <?php the_tags( 'Tags: ', ', ', ''); ?>

                <?php include (TEMPLATEPATH . '/_/inc/meta.php' ); ?>

            </div>


        </article>



    <?php endwhile; endif; ?>

    </div>

</body>

Answer by Starx

I know a little trick actually.

Make a function on your parent page

var closeIFrame = function() {
     $('#iframeid').remove();
}

Inside the iframe you want to close call from anywhere you want

parent.closeIFrame();

Tricky, isn’t it?

Read more

jquery function that load html code into a div and then load other content into div inside html loaded

Question by Raphael D.G

I’d like to know what’s the way to load an html page (page1.html) into a div in webpage active (index.html) and then load another html page (page2.html) into a div that will be inside of page loaded (page1.html). I mean.

index.html

<div id="content"></div>
<a class="link" href="#">load</a>

script

$(document).ready(function() {
    $('a.link').live('click', function() {
        $('#content').load('page1.html', function(){
            $('#content2').load('page2.html');
        });
    });
});

page1.html

<div id="content2"></div>

It’s works fine for only 1 click, at the second click it loads page2.html for 0,5 seconds and then loads page1.html.

What’s the problem ???

Thank you

Answer by Starx

If I am correct, you are trying to load onto the second secontainer, after first container is loaded

Add a simple class on your markup

<div id="content" class="toload"></div>

&

<div id="content2" class="toload"></div>

Now, here is the magical jQuery you need

$(document).ready(function() {
    $('a.link').live('click', function() {
        $('.toload').load('page1.html', function(){
            $(this).removeClass('toload');  //Remove the class so that next time it does not get affected
        });
    });
});
Read more

Fastest way to build this string

Question by tester

say I have an array of objects with html strings inside (there are other things, but i’m specifically focusing on the html property of each object. e.g.

var items = [{
    html: '<div>test</div>'
}, {
    html: '<div>test</div>'
}, {
    html: '<div>test</div>'
}];

I need to build a string using all of these strings and I need them in the same order they’re given to me, so a reverse while loop is out.

is there anything faster at building the html than the following?

var html = [];
for (var i = 0, itemLen = items.length; i < itemLen; i++) {
    html.push(items[i].html)
}
output.innerHTML = html.join('');

Answer by user1150525

faster would be:

var html = '';
for (var i = 0, itemLen = items.length; i < itemLen; ++i)
    html += items[i].html;
output.innerHTML = html;

Edit:

This is faster:

var html = '';
for (var i = 0, itemLen = items.length; i < itemLen; html += items[i++].html);

Answer by Starx

This is much faster than yours

var html = '';
for (var i = 0, itemLen = items.length; i < itemLen; i++) {
    html += items[i].html;
}
output.innerHTML = html;
Read more
...

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