February 28, 2013

Code Igniter : base_url() at CSS file doesn't work

Question by Esgi Dend HigherCloud

base_url() doesn’t work at CSS file…

here’s my php :

<link rel="stylesheet" type="text/css" href="<?=base_url()?>css/style.css"/>
<body>
</body>

here’s my css/style.css :

body {
  background:#356aa0 url(<?=base_url()?>img/background.png) repeat-x;
  color:#fff;
}

the text color change to white, but the image doesn’t show up…
if i use url(../img/background.png), it show up…
but when i open url localhost/project/index.php/control/function/var1/var2, it doesn’t show up…

It’s Solved, Thanks every one… :]

i make php file at view folder like this :

<?php header("content-type: text/css"); ?>

body {
    background:url(<?=base_url()?>img/background.png);
}

and i load the php file i just make with function at controller, and then i link it :

<link type="text/css" rel="stylesheet" href="<?=base_url()?>control/style.php"/>

It’s work, Thanks guys…

Answer by Starx

CSS file does not get parse as PHP file. If you really want to do something like that, rename your file as styles.php

OPEN the page and add

header("content-type: text/css");

This tells the page to be treated as a text based CSS file. Then you can simple echo your remaining CSS like

echo "
body {
....
....
";

To fix the base_url() not being accessible from styles.php set a session variable to keep that. You can keep this on your index.php of codeignitor.

$_SESSION['base_url'] = base_url();

Now, use this inside styles.php.

background: url("<?php echo $_SESSION['base_url']; ?>"/../../some.jpg");

What does =+ mean in JavaScript

Question by dk89

I was wondering what the =+ operator means in JavaScript. It looks like it does assignments.

Example:

hexbin.radius = function(_) {
   if (!arguments.length)
       return r;
   r = +_;
   dx = r * 2 * Math.sin(Math.PI / 3);
   dy = r * 1.5;
   return hexbin;
};

Answer by mpm

r = +_;
  • + tries to cast whatever _ is to a number.

Answer by Starx

It is not an assignment operator:

  • _ is just a parameter passed to the function
  • + infront as +_ casts that variable _ to a number or integer value

DO NOT CONFUSE IT WITH += operator

making a span behave like a button

Question by Nick Ginanto

I have the following html

<div class="btns">

<div id="green">    <span class="btn btn-block btn-large btn-success disabled green_btn">Green</span>

 <div class="num">(1)</div>
</div>
<div id="red">
    <form class="button_to" >
        <div>
            <input class="btn btn-block btn-large btn-danger red_btn"
            type="submit" value="Red">
        </div>
    </form>
    <div class="num">(0)</div>
</div>
</div>

and css

.btns {
    position: relative;
}

.num {
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
}

#green, #red {
    display: inline-block;
    width: 49%;
    position: relative;
}

.green_btn, .red_btn {
    margin-bottom: 4px;
}

I can’t figure out why the (1) under green span isn’t behaving like (0) under the red button. If I remove bottom:0; it fixes the green but messes up red.

Here is a jsfiddle to illustrate the problem http://jsfiddle.net/HajHV/

What am I missing here?

Answer by ethagnawl

It’s because of the form’s margin.

margin: 0 0 20px;

Answer by Starx

Basically is the problem of form’s margin. I removed your CSS and simply added this:

form { margin: 0; }
#green, #red {
    width: 48%;
    float:left;
    position: relative;
}
.num { margin: 0 auto; width: 10px; }

Fixed

Remove white space on HTML/CSS banner?

Question by js111

I have tried every kind of CSS trick I know to remove this white space including cell-padding, margins, padding ect ect.

Any idea how to remove this white space below the “sign up” on this banner?

http://oil.wpengine.com/

enter image description here

Answer by ThinkingStiff

Add vertical-align: top to this <img> in the row below the row with the “sign up” <img>. I did it inline here, but you’ll probably want a class.

<img src="images/OFC_Home_Header_15.png" width="75" height="10" style="vertical-align: top">

enter image description here

Answer by Starx

This is a slicing problem. Fix this image

<img width="75" height="10" alt="" src="images/OFC_Home_Header_15.png">

This solves the problem:

<img width="75" height="10" alt="" src="images/OFC_Home_Header_15.png" style="margin-top:-2px;">

Get current HTML element in PHP

Question by Sanjay Manohar

I may have misunderstood the purpose of PHP here. But I want to do the following:

I have a PHP function, and I call it from HTML, e.g.

  <BODY>
    <DIV id='A'>
      <?php emit("hello1"); ?>
    </DIV>
    <DIV id='B'>
      <?php emit("hello2"); ?>
    </DIV>
  </BODY>      

And I want to know, within the function, which DIV it was called from.
e.g.

  <?php function emit($txt){
           echo "$txt";
           echo "from DIV id $DIVID"
        } 
  ?>

And I want it, obviously, to print

hello1 from DIV id A
hello2 from DIV id B

Is there any way of finding the “current” DIV’s ID?

Answer by Starx

Yes, you have misunderstood the purpose of PHP.

PHP is a server side programming language, it does not run on the HTML page, but before the HTML gets loaded on to the browser.

The task that you are trying to do can be done from JavaScript if interested. I will give an example of jQuery:

var emit = function(el, txt) {
    var id = el.attr('id');
    el.html(txt+" from DIV id "+id);

}

Now call using

emit($("#a"), "hello1");

Same can be done from JS in the following way

var emit = function(el, txt) {
    el = document.getElementById("el");    
    id = el.getAttribute('id');
    el.innerHTML(txt+" from DIV id "+id);
};

Use like:

emit("a", "hello1");
February 27, 2013

PHP navigating parent folders

Question by tPlummer

I can not find a good example/explanation on how to traverse directories in a PHP script.

I have to call a class from a directory that is a great-great-great…great-great grandparent of the current file.

Since the directory of the file I cam calling is closer to the root than the current php script, I just want to say “c:folderscript.php”.

when I use require_once (dirname('c:/folder/').'script.php'); I get config errors.

This is on IIS. Is the slash direction a factor?

Answer by Oldskool

Yes, the slash matters between Windows/Linux. That’s why the DIRECTORY_SEPARATOR constant was invented, they differ per build. You should be able to:

define('DS', DIRECTORY_SEPARATOR); // Alias to keep it short and readable
require_once('C:' . DS . 'folder' . DS . 'script.php');

Answer by Starx

It might be more suitable to transverse from the root directory.

Generally this is represented by a “/”

require_once("/some/script.php");

Or, define a base directory on the top of executing script and use this as the helper variable on your links. Below is an example:

define("BASEDIR", "../../../../"); // Point to the great great great grans parents just once and use them

need to call ajax function from inside jquery modal dialog box

Question by vinylDeveloper

I have a dialog box that loads from an ajax call.. It works good. I want to have a link inside my dialog box that updates a DB and loads the results via ajax to the parent page, without my dialog closing. Is this even possible? Here is what I have so far.

This is what my parent page called deals_calendar.php looks like. The ajax call works fine and opens a dialog box that is loaded with content from get_deals.php.

<script type="text/javascript">  
$("#calendar td").on('click', function() {
    var data = $(this).data();

     $.ajax({
        type:"GET",
            url: "get_deals.php",
            data: { monthID: data.month, dayID: data.day, yearID: data.year },
            success: function(data){
        var title = $( "#dialog" ).dialog( "option", "title", "Deals" );
        $('#dialog').dialog({
                open: function (event, ui){
                     $('a').blur();
                     $(this).scrollTop(0); 
                    }
            });
        $("#dialog").html(data).dialog("open");
         }   
    });

$("#dialog").dialog(
       {
        bgiframe: true,
        autoOpen: false,
        height: 450,
        width:900,
        modal: false,
          closeOnEscape: true

       }    
);
});

</script>

<div id="dialog" title="Dialog Title"> </div>
<div id="return"></div>

Then in my get_deals.php script I have this

<script type="text/javascript">  


$('#click').live('click', function(){
$.ajax({
    type:"POST",
    url: "deals_add_to_queue.php",
    data: { monthID: data.month, dayID: data.day, yearID: data.year },
    success: function(data){
                alert("Please work!");
                ("#return").html(data);
         }   
    });

});
</script>

 <a id="click" href="#">click me</a>

I can’t get this ajax call to fire and update the content on deals_calendar.php. Any help would be great. thanks

Answer by Starx

If the event is not being fired, you need to use event delegation.

$('body').on('click', '#click' function(){

    $.ajax({
        type:"POST",
        url: "deals_add_to_queue.php",
        data: { monthID: data.month, dayID: data.day, yearID: data.year },
        success: function(data){
                    alert("Please work!");
                    ("#return").html(data);
             }   
   });

});

using document.getElementById

Question by Codejoy

I am having a heck of a time getting some data from a dom I want.

I have some html here:

 <ul id="userMenu">
      <li class="userGreet devi">I WANT THIS TEXT HERE </li><li> <a href="javascript:void(0)" class="more" title="Menu">Menu</a>
      <ul> ....
            <li class="home">   
            </li>
      </ul>
      ...</li>
 </ul>

I know if I say

var x = document.getElementById('userMenu');  

I can get “something” back (though this is all in a portal so its incredibly difficult to put java script break points into this). So I am not sure how I can go further to get the string "I WANT THIS TEXT HERE " ?

I think I have to walk through childNodes but not sure how or what exactly I am getting back so I can get at that string, also getElementById didn’t work for the class= would that be getElementByClass ?

New to this DOM stuff.

Answer by jfriend00

Using plain javascript and making your code more robust if the order of elements changes a little bit, you could use both the id and the class to get it like this:

var text = document.getElementById('userMenu').getElementsByClassName("userGreet")[0].innerHTML;

or using tag names, it could be done like this:

var text = document.getElementById('userMenu').getElementsByTagName("li")[0].innerHTML;

Answer by Starx

You can scan through like this

var x = document.getElementById('userMenu');  
var xChilds = x.childNodes;
var requiredElement = null;
for(var i = 0; i < xChilds.length; i++) {
   if(xChilds[i].className.indexOf('usergreet devi') !== -1) {
      requiredElement = xChilds[i];
      break;
   }
}

console.log(requireElement);

jQuery $.post not returning data

Question by Cuonic

I’m using $.post to send a form via ajax to a PHP page, which returns JSON data. Once upon a time, it worked perfectly, and the function(data) executed as normal. Somehow, I’ve broke it, and now it doesn’t even touch the function(data). I’ve tried undoing most of what I’ve done, but I still can’t find the problem.

Here’s the script :

$("#modifyhome").submit(function(event) {
    if($("#modifyhome").valid()) {  
        event.preventDefault();

        var $form = $( this ),
            title = $form.find('input[name="title"]').val(),
            content = $form.find('textarea[name="content"]').val();

        $.post("?action=page-accueil", {"title": title, "content": content},
            function(data) {            
                if(data['error'] == 1)
                {           
                    $().message(data['message']);
                    $("div.jquery-message").effect("shake", {times: 3}, 900);
                }
                else if(data['error'] == 0)
                {           
                    $().message(data['message']);
                    $("div.jquery-message").effect("bounce", {times: 3}, 900);
                }
                else
                {           
                    $().message("Erreur de connexion au serveur : veuillez r&eacute;essayer.");
                    $("div.jquery-message").effect("shake", {times: 3}, 900);
                }
            }, "json"
        );
    }
    else
    {
        $("[id^=qtip-]").effect("pulsate", {times: 3}, 600);
        return false;
    }
});

And here is what the PHP page (?action=page-accueil) returns :

{"error":0,"message":"Page modifi&eacute;e."}

That all checks out as valid JSON, but it’s as if jQuery doesn’t recognize it for some reason. Any help is greatly appreciated 🙂

Answer by Starx

I used to get this problem too, I am exactly not sure of the reason why. But I have a solution that works.

$.post("?action=page-accueil", 
    {"title": title, "content": content},
    function(data) {
        data = eval("("+data+")");
        //.... Then continue it
});

Or, use .parseJSON() function to read the string as JSON, if you dont want to use eval()

$.post("?action=page-accueil", 
    {"title": title, "content": content},
    function(data) {
        data = $.parseJSON(data);
        //.... Then continue it
});

loop the .append() with selector as variable

Question by user2108245

I am trying to loop the .append() function in order to change the selector each time with different value. But, I don’t know the syntax for the selector in order to meet my target. So, how to change it? Thanks so much!
Ka Ho

<script type="text/javascript">
var a=3;
for (var i=0;i<a;i++)                       {                           
$i.append(i);
}
</script>

<div class="0"></div> // expected: display 0
<div class="1"></div> // expected: display 1
<div class="2"></div> // expected: display 2

Answer by Starx

First of all numeric class and ids are not supported that much as you think it is.

Update your HTML to something like this

<div class="box-0"></div>
<div class="box-1"></div>
<div class="box-2"></div>

Then you can use the script provided by deadlock in his answer.

var a=3;
for (var i=0;i<a;i++) {                           
    $(".box-"+i).append(i); //this is what you need
}
...

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