...

Hi! I’m Starx

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

Using variables to check if certain things are allowed

Question by Marshall Mathews

i was thinking of implementing features of turning on and off certain things on my website like registering and logging of.
I could include a file with variables like so

<?php
$upload = 1;
$register = 1;
?>

And then in suppose my register.php file i could do a check like so

if($register == 1){
//Show form
} else { echo "Registration is disabled" }

i was wondering if this would be a security issue as i read somewhere that stuff can be suffixed the url to bring the same effect
Like so

register.php?register=1

But that does not work if register globals are turned off, is this much of a security issue?

Answer by Starx

NO

register.php?register=1 will only be accessed from $_GET['register']
Unless you’re using an older version of PHP with register_globals turned on Thanks Lex

If you are configuring some features on the server, I suggest you use sessions instead.

$_SESSION['upload'] = 1;
$_SESSION['register'] = 1;

Unlike constants, they can be changed, if some criteria is met.

And register_globals() is removed from the latest PHP 5.4.0, so, dont use that.

Read more

Using same session ID in ajax can't connect to MySQL DB

Question by jeffery_the_wind

I have made a generic PHP script to use for an AJAX call. I have the username and password for the mysql connection stored in SESSION variables. In order to start the same session in this ajax script, I pass the session ID via post to the ajax script. The variables are being passed correctly and I checked using error_log that the username and password SESSION variables are the correct values. Here is the ajax_script.php:

<?php

session_id($_POST['session_id']);
session_start();

mysql_connect('10.X.X.X',$_SESSION['username'],$_SESSION['password']);

$results = mysql_query($_POST['query']);

echo json_encode($results);

?>

However, the connection cannot be established. I checked the log file and this is the error:

 PHP Warning:  mysql_connect(): Access denied for user 'username'@'25.1.1.1' (using password: YES) in /ajax_script.php on line 6, referer: http://25.1.1.1/index.php?option=com_content&view=article&id=180

Does anyone know why I cannot connect like this?

Previously I made a similar script, but did NOT start the same session referencing the session_id like above. I passed user names and passwords via post, and the connection worked.

Thanks!

** EDIT ** Sorry, I used the wrong IP for the mysql connection. the following code works:

<?php

session_start();

$ajax_connection = mysql_connect('10.X.X.X',$_SESSION['username'],$_SESSION['password']);

$result_set = array();

while ($result_set[] = mysql_fetch_assoc($results)){
    // do nothing
}

echo json_encode($results);

?>

Answer by Starx

You dont need to

session_id($_POST['session_id']);

Just session_start() is enough

Maybe your session is expiring on close. Use the following snippet on both pages

session_cache_expire(30); //expire in 30 minutes

Check this answer for more information on session expiring.

Read more

How to add jquery click event to gRaphael graphics?

Question by 3gwebtrain

I made a chart using g.Raphael:

$(function(){
    var r = Raphael("pieChart"),
            pie = r.piechart(320, 240, 100, [55, 20, 13, 32, 5, 1, 2, 10]);

            r.text(320, 100, "Interactive Pie Chart").attr({ font: "20px sans-serif" });
            $(pie.sector).click(function(){
                alert('hi');//not work!
            })

})

Later I added the click event to pie.sector, but my event is not work… any one know the right way to handle gRaphael with jQuery?

Answer by Starx

Just select the pie

$(pie).click(function(){
    alert('hi');
})
Read more

Save as the part of a file

Question by user1278479

I would like have a button and when you click this button, un can save save as a part of the file.

For example if in DOM there is:

<div>
  <div id="myButton">My Button</div>
  <h1>My Title</h1>
  <p>My Text</p>
</div>

Then when you click myButton the navigator opens a window for saving a file untitled “my button” with the content “My Text”. Is it possible or should i use a pop up or anything else to do that?

Due to the risk of hacking, i dont think it’s directly possible, but maybe a navigator plug in can do it ? Because i dont care for the support of cross-navigator, it’s only for a personal use.

Thanks !

Answer by Starx

You cannot do it with javascript alone, you need server-side script like PHP and then you have to send a ajax request to the server to page to save the text

Here is a scratch of what your code is going to look like

$("#myButton").click(function() {
    //show some saving somewhere

    $.post("yourserverpage.php", 
    { 
       //Send the data
       title : $(this).parent().chidren("h1").html(), 
       text : $(this).parent().chidren("p").html(),
    }, function(data) {
       //sucess
       // do something on success
    }
);
Read more

Toggling divs in javascript

Question by Faryal Khan

I want to toggle divs by clicking on links. but things are not going well for me when I click on a link it shows a new div but don hide the previous one

JavaScript Code

<script type="text/javascript">
    function toggle(id){ 
        var el = document.getElementById(id);
        if(el != null && el.style["display"]== 'none'){ 
            el.style["display"] = "block";
        }
    }
</script>

My divs code

<?php foreach($titles_data as $title){ ?>
 <div style="display:none" id="content_<?php echo $title['idtitles'] ?>">
   <div id="left-ad"></div>
 </div>
<?php } ?>  

My links code

<?php foreach($titles_data as $title){ ?>
<li class="flag_<?php echo strtoupper($title['language']) ?>">
 <a id="title_<?php echo $title['idtitles'] ?>" href="" title="<?php echo $title['title'] ?>" onclick="toggle('content_<?php echo $title['idtitles'] ?>')">
 </a>
</li>
<?php } ?>

How can it be done so that when i click on link its respective iv becomes visible and the previous one hides?

Thanks

Answer by Starx

To toggle the display, you dont need to do that much

$("#elementid").toggle();

In reference to your question

$('a').click(function() { // however this is select all anchors, better use class
                          // selector like $(".mylinkclass")
   var id= $(this).attr('id'); //get the id
   var ids = id.splite("_"); //split the id on "_", to extract the idtitles
   $("#content_"+ids[0]).toggle(); // use that to toggle
});
Read more

Adding margin with Jquery

Question by Josh Davies

I am trying to center tags within a div but depending on what page you are on it can depend on how many tags there will be as it’s for an image gallery. So i am trying to do it with Jquery.

Basically what i want to say is:

For every tag add 5% to the margin.

Can someone point me in the right direction to do so. I was thinking of using the .size() to calculate the amount of tags but not sure where to go then.

Thanks.

Answer by Starx

Use the * selector

$("*").css("margin","5%");

However, for the safety purposes, you have to limit the use of such wildcard selector. There are lots of other ways you can select mass elements.

  1. Class Selecotors: $(".myclass')
  2. Tag Selecotors: $("div")
  3. Atrribute: $("input[type="text"]')
Read more

Form submitted, response via ajax

Question by Andy

Currently I have this, which works nicely – it’s an email signup list which returns a successful response or error, as appropriate.

$.ajax({  
    type: "POST",  
    url: "mailing_list/mailing_list_add2.php",  
    data: dataString,  
    success: function(response) { 
        $('#emailform').html("<div id='display_block'></div>");
        $('#display_block')                      
        .hide()  
        .fadeIn(500, function() {  
            $('#display_block').html(response)
        });             
}  
}); 
return false; 
});

The form is in a div with ID “emailform” and the “display_block” is the response. What I need is for the response to automatically disappear after a short time and for the form to fade back in. I’ve tried a few things but nothing that has worked yet.

Any help on what to add to the above code would be appreciated.

Answer by redDevil

Assuming your initial html is like,

<div id="emailform">
   <form>
   ...
   </form>
</div>

you can proceed like this,

.ajax({       
type: "POST",       
url: "mailing_list/mailing_list_add2.php",       
data: dataString,       
success: function(response) {  

    var backupHtml = $('#emailform').html();        
    $('#emailform').html("<div id='display_block'></div>");            

    $('#display_block')                               
    .hide()       
    .html(response)    
    .fadeIn(500, function() {               
        $(this).fadeOut(5000,function(){
            $('#emailform').html(backupHtml);
        }); 
    });

}   
});  

Answer by Starx

To do instead of all mumbo jumbo.

$('#emailform').html("<div id='display_block'></div>");
$('#display_block').hide().html(response).stop().fadeIn(500);   
Read more

Setting attributes in jquery

Question by BlackFire27

I have a problem with running jquery:

    <!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <script type="text/javascript" src="jQuery.js"></script>
      <script type="text/javascript">
       $(function(){

            $('form').attr('id','myNewId');
        });
       </script>
    </head>
    <body>

        <div align="center">
            <form id="myID">
            My Name: <input type="text" name="text"/>
            </form>

        </div>
    </body>
</html>

no error happens , and no intellisense with netbeans..why the code doesnt work ?!?

UPDATE: now it works..

No intellisense with Netbeans..Here is my version:

> Product Version: NetBeans IDE 7.1.1 (Build 201203012225)
Java: 1.7.0_03; Java HotSpot(TM) Client VM 22.1-b02
System: Windows XP version 5.1 running on x86; Cp1255; en_US (nb)
User directory: C:Documents and Settingsdddddddddddd.netbeans7.1.1
Cache directory: C:Documents and Settingsdddddddddddd.netbeans7.1.1varcache

Answer by Starx

jQuery Intellisense is already available on Netbeans. [read more]

It should work the way you are coding [demo], but as of jQuery 1.6+ , you can also use .prop() to set values for attributes[demo]

$('form').prop('id','myNewId');

In case jQuery is not defined, may be it is conflicting with a different jQuery version. Use this at the top of your script

  $.noConflict();
Read more

making files in the folder donwloadable using php or javascript

Question by Shrestha Sunil

I am trying to making files to be downloadable after clicking the link of the listed file. I am not getting idea how to make it possible. I have completed to list file using following scripts. Now I have to provide listed file to be downloadable after clicking the file name. Plz help…

$dir = 'd:/temp_file/voice/';
if (is_dir($dir)) {
 if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
    if($file != '.' && $file != '..')
        echo "filename: ".$file."<br />";
               // header('Content-type: audio/wav');

             //   header('Content-Disposition: attachment; filename="'.$dir.$file.'"');

              //  readfile($dir.$file);
    }
    closedir($dh);
 }
}

Answer by Starx

Files are already downloadable by default.

Create a php file, through which the file will be downloaded. For example: download.php Place the following codes on them.

 $filename = $_GET['filename']; 
 $dir = "../path/to/directory/"; //$dir = 'd:/temp_file/voice/';
 // ^ Use Relative links           ^ Not system dependent link as this
 if(is_file($dir.$filename)) {
    header('Content-type: audio/wav');
    header('Content-Disposition: attachment; filename="'.$dir.$file.'"');
    echo file_get_contents($dir.$file);
 }

Next link to this page as this

<a href="download.php?name=filename.jpg">Download FileName</a>
Read more
...

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