...

Hi! I’m Starx

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

create a dynamic url in codeigniter like facebook

Question by Nisha haridas

I need to create a dynamic url in codeigniter like the facebook application. Is it possible to create such url using the codeigniter framework?
eg:
1. www.facebook.com/nisha
2. www.facebook.com/dev

Answer by Starx

Its pretty easy to setup this by the use of routes. Read their routing guide

$route['([a-zA-Z]+)'] = "controller/user/$1";

However, if their is only one way of accessing the website, is like domain.com/username then its ok, otherwise, this will prove be a hard catch on the long run. On that case, limit the Route to a limited scope like

$route['users/([a-zA-Z]+)'] = "controller/user/$1";

This will help in the extending the system in numerous way

Read more

Processing JSON output from mysql through php

Question by rudawg

Ok so i managed to figure out the php code and it is working and is outputting in the right json format when i view it in browser. Here’s the code thanks to help from Starx:

<?php
include ("Includes/dbConnect.php");

$_GET['date'];

$query2 = "SELECT * FROM events";
$checkevent = mysqli_query($cxn,$query2) or die("Couldn't execute query!");
$dates = array();
    while ($row2 = mysqli_fetch_array($checkevent))
        {
        $eventDate = $row2['eventDate'];
        $eventName = $row2['eventName'];
        $eventHost = $row2['host'];

        $dates[$eventDate] = array('title' => $eventName, 'desc' => $eventHost);

        }
    echo json_encode(array("dates" => $dates));
?>

this outputs:
{“dates”:{“2012-03-16”:{“title”:”Table Quiz”,”desc”:”MSU”},”2012-03-20″:{“title”:”Welcome”,”desc”:”Me”}}}

So there has to be a problem with my jquery code. i altered it as to Starx’s specifications but still nothing, anyone have any ideas??

    <script type="text/javascript">
    $(document).ready(function() 
 {
$("#ical").ical({ 


beforeMonth:function(date)
    {
        $.ajax({
            type: "GET",
            url: "getCalendarEvents.php",
            dataType: "json",
            data: "date="+date,
            async: false, //stop rendering the calender until eventdates is changed.
            success: json.each(function(k,v){
                $.fn.ical.changeEventDates(v); //this function changes the eventdates
            }   
        })
    }   
});
});

</script>

Answer by Starx

Make sure there is no futher operation after you echo the encoded json. So use an exit() at the end to confirm this

echo json_encode($dates);
exit;

Updates

On that case, notice that you are using two dimensional array for $date. When using $date[] = array(..) So you have to access it like

json.each(function(k,v) { 
    //Now v will hold the json format 
    $.fn.ical.changeEventDates(v);
});

Update 2

{“dates”:{“eventDate”:{“title”: “eventName”, “desc”: “eventHost”}, “eventDate”: {“title”: “eventName”, “desc”: “eventHost”}}}

This format is not quite possible, since every item has same key eventDate. You can do it another way. Change up the following in the php

echo json_encode(array("dates" => $dates));
exit;

Now , json in your success function will hold similar format

function(json){
   // This will hold the json is this format
   // {"dates":{ 0 :{"title": "eventName", "desc": "eventHost"}, 1 : {"title": "eventName", "desc": "eventHost"}}}
   // Note the numeric indexing
}   
Read more

appending an <object> dynamically in IE doesn't work

Question by CCrawler

I tried several methods, none seem to work:

1 (I tried this one with other elements and it doesn’t work either):

$('#container').append('<object attribute="value"></object>');

2 (I found that this way worked with IE with most elements, but no luck here) :

var newSwf = $('<object></object>').attr('attribute', 'value');
$('#container').append(newSwf); //appendTo doesn't work either

None of the above seems to have any effect on the DOM, like nothing is appending at all. I know IE works funny with the append function, but until now, I always managed to find a workaround. I have no clue with this one though. Any ideas?

EDIT:

It seems it was my mistake, something else on my code was causing the problem in IE. I’m terribly sorry, I was hiting against a wall and I thought it was some sort of .append() issue, since IE always works funny with that.

The second method worked, as it does with other elements.

Answer by Starx

As mentioned in my comment, it works on IE 8+. But in case they are not, stick to native JavaScript for this

var newobject = document.createElement('object')
newobject.setAttribute('id','objectid');
document.getElementById("container").appendChild(newobject);

Demo

Read more

How to clear the session using a button and javascript

Question by user782104

Session is client side staff, but is it possible through clear it using javascript code?
I would like too have the idea like this and ,can it convert to jquery format? Thank you.

js

    $(function(){
  $("#closeTab").click(function() {
    window.parent.$('#tt').tabs('close','Create List');
        $.post("clear.php",function(data){
      });
  });
});

php

    <?
if (isset($_SESSION['lname']))
unset($_SESSION['lname']);
if (isset($_POST['creminder']))
unset($_SESSION['creminder']);
?>

Is this one ok ?

Answer by Shyju

make an ajax call to the server and let your server page kills/ends the session

HTML

<a href="#" id="aKill" > Kill Session</a>

Script

$(function(){

  $("#aKill").click(function(){
        $.post("serverpage.php",function(data){
        // if you want you can show some message to user here
     });
});

and in your serverpage.php, Execute the PHP script to terminate the session.

Answer by Starx

Create a separate file to clear the session only. clearsession.php

session_start();
session_destroy();

Now, make a simple request

$("#aKill").click(function(){
    $.get("clearsession.php");
}
Read more

Center logo in html5 boilerplate

Question by Barbara

I’m using html5 boilerplate and their .ir class. I made the logo clickable, I want to center it in the page but so far no luck. I tried margin: 0 auto; and text-align: center; but they both don’t seem to work.

The html

   <a href="/"><h1 class="ir">logo header</h1></a>

and the css

    h1 {
    height: 373px;
    }

    .ir {
    display: block;
    border: 0; 
    text-indent: -999em; 
    overflow: hidden; 
    background-color: transparent; 
    background-repeat: no-repeat; 
    text-align: left; 
    direction: ltr; 
    *line-height: 0; 
    background-image: url(http://i.imgur.com/yYnyJ.jpg);
    }
    .ir br { display: none; }

Answer by Starx

Add background-postion: center; to the rule. You might want to use top center as the value, if you want the align image at the top and centered at the same time.

Note:: The image size have to be subsequently smaller than the <h1> to appear on the center.

Moreover, I would recommend using the shorthand property as well.

.ir {
    display: block;
    border: 0; 
    text-indent: -999em; 
    overflow: hidden; 
    text-align: left; 
    direction: ltr; 
    *line-height: 0; 
    background: url(http://i.imgur.com/yYnyJ.jpg) transparent no-repeat center;
}
Read more
March 19, 2012

Can I add elements of two forms by using .serializeArray() function of Javascript

Question by user1254174

I have a Web Page which contains 3 forms. Each one has a large list of elements ( Input, select).
We were using query string to update the page on user submit using the serialize function and passing the params in the URL. In one such case, the length of the URL has crossed the maximum allowed string length in IE browser.

Now I am planning to change that to POST method and also send the elements using Jquery serializeArray function as the Server expected the data to be in form of an Array.

I am not able to find sufficient data on .serializeArray() function.
Can the output of the .serializeArray() function for each form in my page be combined and then submitted ?
Is there any other method by which I can do this?.

Any suggestions is welcomed.

Answer by Starx

You can combine the serialized data in an array and send

var data = new Array();

data[] = $("formone").serialize();
data[] = $("anotherform").serializa();

$.post("toapage.php", { formdatas : data }, function(msg) {
   alert(msg); //on success
});
Read more

how to pass array string in javascript function from php end as a argument

Question by Samad

Hey Guys i have a little issue of JavaScript and i don’t know how to solve this Query that why i put this Question in stackoverflow also helps are definitely appreciated

I am getting the error missing ) after argument list in my Firebug console.

emissing ) after argument

My Question is how to pass $char_data variable in JavaScript function as a argument

Define php variable

<?php 
$chart_data = "['NBA',1],['NFL',2],['MLB',3],['NHL',4]"; 
$div = "graph";
?

Call Javascript function with define argument

<script>
dynamicChartArray('<?php echo $div;?>','<?php echo $chartdata;?>')
</script>

A function of javascrpit

<script>
function dynamicChartArray(div,chartdata){
var myData = new Array(chartdata);
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
<script>

Answer by Carl

Rather than creating an array out of a string in javascript, why not just just get the PHP to output it as an array to start with?

Just add an extra set of [] which javascript reads as an array.

$chart_data = "[['NBA',1],['NFL',2],['MLB',3],['NHL',4]]"; 

then ditch the quotes on the output (which are responsible for causing the error messages)

 dynamicChartArray('<?php echo $div;?>', <?php echo $chartdata;?>);

and then myData can just equal chart data (since its already an array)

var myData = chartdata;

Answer by Starx

You dont need var myData = new Array(chartdata);.

chartdata is already an array.

Read more

show message in log file with php

Question by JERC

I need to know how to show a message in the log in apache with php, I know that java has this instruction

System.out.println

and in tcl

 ns_log notice

but there are some equivalent in php?

Thanks!!!

Answer by Starx

Use error_log() function to set custom error messages

error_log("Oracle database not available!", 0);

Or you can save the errors to custom log file as

error_log("Oops, something went wrong!", 3, "/var/tmp/my-errors.log");
Read more

how to check if there is one selected radio button among the group?

Question by assehj

Good day… I am here again to ask your idea on solving this problem. I have displayed questions using while loop. Each questions have 5 radio buttons each. The problem is, I have to check if one among the group of radio button is clicked. How to do this one using php or javascript? I have here my sample program.. Thanks in advance…

$ctr = 1;
$partIDTemp = "";
while($rowItems = mysql_fetch_array($resultItems)){                          
   if( $partIDTemp != $rowItems['partID'] ){
      if($ctr != 1)
         echo "<tr ></tr>";
         echo "<tr style='font-family: Arial, Helvetica, sans-serif; font-weight:bold'><td colspan='3'>" . $rowItems['description'] . "</td></tr>";
   }
echo "<tr bgcolor=white style='font-family: Arial, Helvetica, sans-serif;'><td align='center'>" . $ctr . "</td>";
$rows =$rowItems['WPID'];
echo "<td>" . $rowItems['descriptions']. "</td>";
$response = "response_".$rows;
echo "<td><input type='radio' name='$response' value='5' />
      <input type='radio' name='$response' value='4' />
      <input type='radio' name='$response' value='3' />
      <input type='radio' name='$response' value='2' />
      <input type='radio' name='$response' value='1' />
  </td>";
$ctr++;
$partIDTemp = $rowItems['partID'];
}                            

Answer by Starx

Since you are monitoring the users activity, you have you use Javascript, unless you can wait till the form is submitted.

Using jQuery, you can attach a snippet on the submit event like this

$("#formid").submit(function() {
   var checked = $(this).children('input[name="checkboxname"]:checked').val();

});

Pure javascript of this would be this

var myform = document.forms['myform'];
myform.onsubmit = function() {
   var elements = myform.getElementsByTagName("input");
   var value;
   for(var i =0; i< elements.length; i++) {
      if(elements[i].type == "radio" && elements[i].checked) {
         value = elements[i].value;
         break;
      }
   }
   alert(value);
   return false;
}

Here is a demo

Read more

How to enable jQuery intellisense on netbeans 7.1?

Question by BlackFire27

Possible Duplicate:
NetBeans jQuery plugin code completion

I downloaded the latest Netbeans, placed the following codes but the intellisense is not working.

<script type="text/javascript" src="js/jQuery.js"></script>

<script type="text/javascript">           
    $(document).ready(function() {
        $("a").click(function() {
            alert("Hello world!");
        });
    });
</script>

Answer by Starx

I just found this link and should help you out.

Follow these steps

  • In your project folder, create a folder named js, and add it to your project.

  • Locate the jQuery library that you downloaded onto your computer. Copy the file to this js folder

Further more, it says to trigger the intellisense include the library as such

<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
                                         <!-- ^ Be sure to include the version number -->
<script type="text/javascript">
     // Try it inside here and it should work
</script>

The display of intellisense

Read more
...

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