...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
July 10, 2011

How to use a php code in javascript

Question by Javad Yousefi

I want to use php code in javascrip ,but it dosn’t work:

        <script type="text/javascript">
        function edit(pollNo)
        {
            <?php
                $result = mysql_query( 'CALL ret_poll('.pollNo.')' );
                $row = mysql_fetch_assoc($result);
                echo 'document.poll.pollTitle.value='.$row['title'];
            ?>

        }
    </script>

Answer by Starx

Javed, its not that you can’t use php in javascript. However the uses are very limited.

See an example

alert('<?php echo "hi"; ?>');

Once the server renders this, the script will be

`alert('hi');` //SO it will alert `hi` now

Mostly, you can use PHP and javascript mixture to create a script you want to run on the run time

For example

<script>
   <?php
   $location = $_SESSION['logged'] ? 'admin.php' : 'index.php';
   ?>
   window.location('<?php echo $location; ?>');
</script>

Or Something like this

<script>
    <?PHP if($test==true) { ?>
        function test() {
            //do something;
        }
    <?php } else { ?>
        function test() {
            //do something else but not the previous one
        }
    <?php } ?>
</script>

However, What you are trying is TRYING TO USE PHP CODES AS JAVASCRIPT Which is not possible !!!!!!!!

Instead, you can use AJAX, as other answers suggest, for a workaround.

A little demo of your probable solution is

FILE: myMYSQLPROCESSING.php

        // Your connections and other above                
        $result = mysql_query( 'CALL ret_poll('.$_POST['pollno'].')' );
        $row = mysql_fetch_assoc($result);
        echo $row['title'];

JS

    function edit(pollNo)
    {
        $.post("myMYSQLPROCESSING.php",
            { "pollno" : pollNo },
            function(data) {
                // Now data, will contain whatever you echo in myMYSQLPROCESSING.php
                // May be a success message or error message

                // and do whatever you want with the response

               document.poll.pollTitle.value=data; //in your case something like this
            }
        );
    }

This is a jQuery code, if you are not familiar with it.

Read more

how to "inject" built-in php functions

Question by gadelat

How can i modify returning value of built-in php function without creating new function with another name and renaming all of used functions with previous name to new one?
e.g.

function time() {
    return time()-1000;
}

Of course this won’t pass, isn’t there something like “function time() extends time() {}” or similar?

Answer by Paul Dixon

With the APD PECL extension you can rename and override built-in functions.

//we want to call the original, so we rename it
rename_function('time', '_time()');

//now replace the built-in time with our override
override_function('time', '', 'return my_time();');

//and here's the override
function my_time($){
        return _time()-1000;  
}

APD is intended for debugging purposes, so this isn’t a technique you should really consider for production code.

Answer by Starx

Why would you want to override PHP’s function anyway? If some function does not do what you exactly want, then create your own function. If it overrides, use a different name or create a class and put the function inside it.

What you are trying to achieve is a wrong solution for a problem!!!

Some examples

Instead of function name time() you can make cTime()(custom Time)
Just like I create my own function for print_r() as printr() to print array in my way

or something like

class FUNCTIONS {
    public function time() {
        return time()-1000;
    }
}
//Now access using
FUNCTIONS::time();
Read more
July 8, 2011

Optional for Microsoft.Fade

Question by pavan

I am converting my HTC file to jquery plugin.

In my HTC file i am using below Microsoft.Fade.

progid:DXImageTransform.Microsoft.Fade(duration=0.15,overlap=1.0)

It is IE only thing. So i want optional thing for other browsers.

Is there any optional thing for this.

Answer by Starx

On jQuery, There are several option to fade.

To certain opacity level, on certain time.

$("div").fadeTo(1000, 15);

or fade Out completely

$("#div").fadeOut(1000);

or fade in

$("#div").fadeIn(1000);
Read more
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']];
?>
Read more

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

Read more

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

Read more

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.

Read more
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
Read more

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.

Read more
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.

Read more
...

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