June 27, 2011

Equivalent of PHP Sessions in JavaScript

Question by user635614

I was going to ask about how to implement sessions in JS,I found few functions that can be used like this example I found :

String exforsys = request.getParameter("test"); 
session.setAttribute("test", exforsys);

And then just use session.getAttribute( exforsys);

But no response, I guess it’s only used in servlets or something.

Anyway, I decided that maybe someone has an alternative way other than just use sessions, what am trying to do is click on a link in one page and depending on which link was pressed I will load different information.

Since its a onclick function, I’m stuck with JS!

So I need to pass this information to the second page, cookies works well cause it can be handled with both PHP and JS easily but some computers deletes cookies and that wouldn’t be nice!

Any suggestions or other ways I can reach what I want but with out using sessions?

Answer by Starx

Sessions are server variables. Thus cannot be used by javascript.

However, you can retrieve the session variables, through ajax request

Script (jQuery)

//This portion will be triggerend once the dom is loaded and is ready
$(document).ready(function() {
    $.post("getsession.php",
       { "variable" : "yourneededsessionvariable" }, 
       fucntion(data) {
         //data containss your session data
       }
    );
});

PHP

//getsession.php
<?PHP
session_start();
echo $_SESSION[$_POST['variable']];
?>

base direcory of script

Question by rohit

i am making twitter application when i call callback.php it shows some error
here is some part of my callback.php where i think it has some problem

////// First establish base directory for app
define('QA_BASE_DIR', dirname(empty($_SERVER['SCRIPT_FILENAME']) ? __FILE__ : $_SERVER['SCRIPT_FILENAME']).'/../../');

$qainc=$_SERVER['DOCUMENT_ROOT'] . '/qa-include';        //second

$piinc=$_SERVER['DOCUMENT_ROOT'] . '/qa-plugin';

/* Start session and load lib */
session_start();

require_once $piinc. '/twitter-oauth-login/twitteroauth/twitteroauth.php';
require_once $piinc. '/twitter-oauth-login/config.php';

i want my directory url so i write second line
www.domain.com/qa-plugin —– i want this url but this command return this address
“/usr/local/apache/htdocs/qa-include”
how to correct error please help me out….

Answer by Starx

getcwd(); //returns the current directory

More info

How can I get inline-block to render consistently when applied to table cells?

Question by Nathan Bell

I have a simple HTML table that I want to render consistently across every modern browser (IE9, latest FF, Chrome, Safari). If I apply widths and “display: inline-block” to just the table cells, FireFox 4 and Chrome will allow the table cells to ‘wrap’ into a second row, as if they were just regular inline-block elements. In IE9, however, the cells are treated like classic table cells, and do not maintain their widths and are scrunched into one row.

Full example of the code is here: http://jsbin.com/ujeber/6

Is there a CSS property that can be applied to the table, tr, or td elements to get IE9, Chrome and FireFox 4 to behave in the same way as each other? If not, which of these browsers is following the standards correctly, or are the standards ambiguous in this case?

Markup:

<table>
  <tr>
    <td>Test1</td>
    <td>Test2</td>
    <td>Test3</td>
    <td>Test4</td>
  </tr>
</table>

Style:

  td {
    width:300px;
    display:inline-block;
  }

  table {
    width: 650px;  
  }

I know that this isn’t the typical/suggested way to use the table element. I am asking in the context of the expected behavior of rendering engines. I’m not looking for answers related to choosing semantically appropriate tags.

Answer by thirtydot

I can’t find a way to make IE9 give your desired result with display: inline-block.

Unless your actual use case is somehow different than your simplified test case, you should just be able to switch to float: left on td, which does work:

http://jsbin.com/ujeber/7

floats and inline-block are often interchangeable. But, they both have different strengths and weaknesses. With floats, you have to clear/contain them. With inline-block, you have to deal with extra gaps (commonly fixed by removing whitespace in HTML), and it doesn’t work in IE6/7 without further tricks.

Answer by Starx

No, there isn’t any CSS properties, to wrap the cells.
P.s. AFAIK

Cancel tab selection in jQuery

Question by Mike

I have created some tool that has 4 pages.
I order to navigate between the pages I am using jQuery “tabs” (in the header of each page).

Is there a way to cancel the clicking operation after some tabs was clicked?
For example: If the page wasn’t saved the user will get a propper warning: “click YES in order to continue without saving or click NO in order to stay in the unsaved page”.

Thanks in advance.
Mike

Answer by Starx

In order to cancel or abort the tab’s ajax request do something like this

$('#tabs').tabs({
    ajaxOptions: {
        timeout: 10000,
        error: function() {
            // If error occurs while trying to load a page via AJAX, abort the tabs
            $('#tabs').tabs('abort');
        }
    }
});

For more information go here.

June 26, 2011

how do i access these array keys as a variable in CI?

Question by ktm

Array
(
    [abc] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [title] => hello 12
                    [meta_keyword] => 
                    [meta_description] => 
                    [tags] => sdfgdfg
                    [status] => draft
                    [body] => dsfdsf dfdsafsdfsdfsdf
                    [photo] => images/blog/nari.jpg
                    [raw] => nari
                    [ext] => .jpg
                    [views] => 0
                     => 
                    [categoryid] => 5
                    [subcatid] => 7
                    [featured] => 
                    [pubdate] => 2011-06-17 03:39:55
                    [user_id] => 0
                )

            [1] => Array
                (
                    [id] => 2
                    [title] => hello xyz
                    [meta_keyword] => 
                    [meta_description] => 
                    [tags] => xcfasdfcasd
                    [status] => draft
                    [body] => dfdsafsdf dsfdsf dfdsafsdfsdfsdf
                    [photo] => images/blog/nari.jpg
                    [raw] => nari
                    [ext] => .jpg
                    [views] => 0
                     => 
                    [categoryid] => 1
                    [subcatid] => 2
                    [featured] => 
                    [pubdate] => 2011-06-17 03:43:12
                    [user_id] => 0
                )

for example if i want to echo out title I would do echo $abc['title'] but it’s not working pls help,

the above output is a result of print_r($count['abc]);
it shows nothing when i do print_r($count['abc']['title'])

Answer by Jared Farrish

You would need to use the numeric key as well: $abc[0]['title'].

In other words, you’ve got an array with array members of an array type which use numeric keys, in which each of those members are arrays which use associative keys to access values. So you need to access each array in $abc to get to the array which contains your title values.

EDIT

If you’re trying to loop through these values, you would need to loop through each array. Such as:

$c_abc = count($abc);

for ($i = 0; $i < $c_abc; $i++) {
    echo "{$abc[$i]['title']}<br/>";
}

Answer by Starx

To access you array variables, the right way is like this

$count['abc'][0]['title']

However, in your title, you are asking about Array keys as variables?

Actually this does not need to be related with CI.

A simple example

$array = array ( "hi" => "bye");
extract( $array);
//it will make "hi" a variable :: $hi = "bye"

echo $hi; // will output bye

How can I run Ajax functions syncrronously from Javascript?

Question by MarieMarie

I have the following code:

$('#DoButton').click(function (event) {
  event.preventDefault();
  $("input:checked").each(function () {
    var id = $(this).attr("id");
    $("#rdy_msg").text("Starting" + id);
    doAction(id);
  });
});

function doAction(id) {
            var parms = { Id: id };
            $.ajax({
                type: "POST",
                traditional: true,
                url: '/adminTask/doAction',
                async: false,
                data: parms,
                dataType: "json",
                success: function (data) {
                    $("#rdy_msg").text("Completed: " + id);
                },
                error: function () {
                    var cdefg = data;
                }
            });
        }

When the button is clicked it checks the form and for each checked input it calls doAction() which then calls an Ajax function. I would like to make it all synchronous with a 2 second delay between the completion of one call and the running of the next. The delay is to give the user time to see that the last action has completed.

By setting async=false will that really make the ajax function wait?

How can I add a 2 second wait after the Ajax has run and before the next call to doAction?

Answer by redexp

Try to do it using recursion

$('#DoButton').click(function (event) {
  event.preventDefault();
  doAction( $("input:checked").toArray().reverse() );
});

function doAction(arr) {
    if( arr.length == 0 ) return;

    var id = arr.pop().id;
    $("#rdy_msg").text("Starting" + id);
    $.ajax({
        type: "POST",
        traditional: true,
        url: '/adminTask/doAction',
        async: false,
        data: { Id: id },
        dataType: "json",
        success: function (data) {
            $("#rdy_msg").text("Completed: " + id);
            setTimeout(function(){ doAction(arr); }, 2000);
        },
        error: function () {
            var cdefg = data;
            $("#rdy_msg").text("Error: " + id);
            setTimeout(function(){ doAction(arr); }, 2000);
        }
    });
}

Answer by Starx

There is option in jQuery to set the ajax function synchronous

$.ajaxSetup({
   async: false
});

To make the function to wait you can use .delay()

Try the solution of this question also.

June 22, 2011

Remembering options in a select box array after submitting through php

Question by Marcus Edensky

<form method="post">
    <select name="box[]">
        <option value="1" <?php if ($_POST['box[0]'] == "1") echo "selected="selected";"?>>1</option>
        <option value="2" <?php if ($_POST['box[0]'] == "2") echo "selected="selected";"?>>2</option>
        <option value="3" <?php if ($_POST['box[0]'] == "3") echo "selected="selected";"?>>3</option>
    </select>
    <p>
    <select name="box[]">
        <option value="1" <?php if ($_POST['box[1]'] == "1") echo "selected="selected";"?>>1</option>
        <option value="2" <?php if ($_POST['box[1]'] == "2") echo "selected="selected";"?>>2</option>
        <option value="3" <?php if ($_POST['box[1]'] == "3") echo "selected="selected";"?>>3</option>
    </select>
    <p>
    <input type="submit" value="Submit">
</form>

When I use box names “box1” and “box2”, it works without a problem. What am I doing wrong?

****** EDIT ********

Thanks a lot for your comments, but I actually found the solution myself, even if it doesn’t make much sense. Instead of using $_POST[‘box’][0] and [1] at the if statement, I simply used $box[0] and [1]. Even though it’s posted, apparently php sees it as a normal array, and not as some kind of $_POST-array! Working code:

<form method="post">
    <select name="box[]">
        <option value="1" <?php if ($box[0] == "1") echo "selected='selected'";?>>1</option>
        <option value="2" <?php if ($box[0] == "2") echo "selected='selected'";?>>2</option>
        <option value="3" <?php if ($box[0] == "3") echo "selected='selected'";?>>3</option>
    </select>
    <p>
    <select name="box[]">
        <option value="1" <?php if ($box[1] == "1") echo "selected='selected'";?>>1</option>
        <option value="2" <?php if ($box[1] == "2") echo "selected='selected'";?>>2</option>
        <option value="3" <?php if ($box[1] == "3") echo "selected='selected'";?>>3</option>
    </select>
    <p>
    <input type="submit" value="Submit">
</form>

Answer by Marcus Edensky

Thanks a lot for your comments, but I actually found the solution myself, even if it doesn’t make much sense. Instead of using $_POST[‘box’][0] and [1] at the if statement, I simply used $box[0] and [1]. Even though it’s posted, apparently php sees it as a normal array, and not as some kind of $_POST-array! Working code:

<form method="post">
    <select name="box[]">
        <option value="1" <?php if ($box[0] == "1") echo "selected='selected'";?>>1</option>
        <option value="2" <?php if ($box[0] == "2") echo "selected='selected'";?>>2</option>
        <option value="3" <?php if ($box[0] == "3") echo "selected='selected'";?>>3</option>
    </select>
    <p>
    <select name="box[]">
        <option value="1" <?php if ($box[1] == "1") echo "selected='selected'";?>>1</option>
        <option value="2" <?php if ($box[1] == "2") echo "selected='selected'";?>>2</option>
        <option value="3" <?php if ($box[1] == "3") echo "selected='selected'";?>>3</option>
    </select>
    <p>
    <input type="submit" value="Submit">
</form>

Answer by Starx

Both, elements have same name. Thats the problem.
$_POST['box[0]'] , $_POST['box[1]'] , contains the array of the two elements, not the value it self.

How can I ensure two floated items stay side-by-side even if there isn’t enough width for both of them?

Question by David H

I have the following HTML:

<div  >
  <div >
    <div style="float: left;">
      <input type="checkbox" value="False" />
    </div>
    <div style="float: left;" >         XXXXXXXXXXXXXXXXXXXXXXXXXXXXX </div>
  </div>
</div>

It displays the XXX to the right of the checkbox. However, if I reduce the screen width, the XXX goes under the checkbox.

Is there any way that I can “lock” the XXX text inside the DIV so the XXXX always appears to the right and on the same line?

(Note that I want to keep using DIV as later on I do some jQuery things with the DIVs.)

Answer by Starx

That is what float:left is supposed to do. It will remain in the left side as much as possible. If the element before is also floated to the left side, it will try to float to left, together with it, if the space is available. That’s why when you resize your screen and there is not enought space for the div to float to the together with previous element, it will float to the left, down the previous element.

PHP method chaining

Question by Headspin

So i was wondering if there is a way to method chain, when the initial method is a static function. Here is what I mean:

    class foo
    {
        public static function a()
        {
            $foo = new foo;
            return $foo->bar(); 
        }

        public function bar()
        {
            return $this;
        }

        public function b()
        {
            return 1;
        }
    }

    print foo::a()->b();

EDIT
print foo::a()->b(); not print foo:a()->b();

Answer by Starx

Static Methods or Other Methods, as long as the method is returning an object either self or some other, the methods can be chained, with the same method you are attempting.

class foo {
   public function __construct() {
   }
   public function create() {
       // create something;
       return $this;
   }
   public function performSomethingElse() {
      // perform something
      return $this;
   }
}
$object = new foo;

$object -> create() -> performSomethingElse();
June 21, 2011

which file is the js error in and how to correct it?

Question by zhuanzhou

enter image description here

http://www.idcspy.com/asp-hosting.html

when loads over the page , at the bottom of the IE broswer window. it shows an alert(the page has an error), it’s an javascript error.but i don’t know which js file has the error in and how to correct it. thank you,

Answer by Starx

Use Developer tools, to find and debug the error

IE: Press F12
Firefox: Downlaod addon known as Firbug
Chrome: Right click -> Inspect Element to get started or (Ctrl + Shift + J)
...

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