[Php-avanzado] Pasar array de php a javascript por parametro

Lucas Calviño thelookus en gmail.com
Jue Jul 29 23:23:35 ART 2010


Ok, ya lo terminé, efectivamente hice un array con los datos de la consulta
y luego los paso a js, uso un conjunto de funciones js muy bien escritas que
encontré y le adapté un script que genera nuevos inputs.
Todo es para cargar ítems en una factura determinada.

Para los que alguna vez necesiten un autocompletar lo paso por acá, aunque
pueda haber mejores este me pareció simple y liviano.

<?php
//Funcion que convierte un array php en un array js
function php2js ($var) {

    if (is_array($var)) {
        $res = "[";
        $array = array();
        foreach ($var as $a_var) {
            $array[] = php2js(trim($a_var));
        }
        return "[" . join(",", $array) . "]";
    }
    elseif (is_bool($var)) {
        return $var ? "true" : "false";
    }
    elseif (is_int($var) || is_integer($var) || is_double($var) ||
is_float($var)) {
        return $var;
    }
    elseif (is_string($var)) {
        return "\"" . addslashes(stripslashes($var)) . "\"";
    }

    return FALSE;
}

*ESTA SERÍA LA PARTE DE GENERAR LA CONSULTA Y PONERLA EN UN ARRAY*
*//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//*
*//**//**//**//**//**//*
//init the SOAP Client
require("lib.php"); //API CASPIO
$wsdl = "https://b3.caspio.com/ws/api.asmx?wsdl";
$client = new SoapClient($wsdl);

//Armo el array con la consulta de los productos
$php_array = $client->SelectDataRaw("silveral", "administracion",
"1kE9u58vu82HircT5", "Productos_visibles",
true,
"Productos_Codigo, Productos_Descripcion",
"Productos_Codigo IS NOT NULL",
"Productos_Codigo ASC",
" - ", " ");*
**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//
**//**//**//**//

*//Convierto el array php en array js
$js_array = php2js($php_array);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Carga Item Factura</title>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="JavaScript" type="text/javascript">
function autoCompleteDB()
{
    this.aNames=new Array();
}

autoCompleteDB.prototype.assignArray=function(aList)
{
    this.aNames=aList;
};

autoCompleteDB.prototype.getMatches=function(str,aList,maxSize)
{
    /* debug */ //alert(maxSize+"ok getmatches");
    var ctr=0;
    for(var i in this.aNames)
    {
        if(this.aNames[i].toLowerCase().indexOf(str.toLowerCase())==0)
/*looking for case insensitive matches */
        {
            aList.push(this.aNames[i]);
            ctr++;
        }
        if(ctr==(maxSize-1)) /* counter to limit no of matches to maxSize */
            break;
    }
};

function autoComplete(aNames,oText,oDiv,maxSize)
{

    this.oText=oText;
    this.oDiv=oDiv;
    this.maxSize=maxSize;
    this.cur=-1;


    /*debug here */
    //alert(oText+","+this.oDiv);

    this.db=new autoCompleteDB();
    this.db.assignArray(aNames);

    oText.onkeyup=this.keyUp;
    oText.onkeydown=this.keyDown;
    oText.autoComplete=this;
    oText.onblur=this.hideSuggest;
}

autoComplete.prototype.hideSuggest=function()
{
    this.autoComplete.oDiv.style.visibility="hidden";
};

autoComplete.prototype.selectText=function(iStart,iEnd)
{
    if(this.oText.createTextRange) /* For IE */
    {
        var oRange=this.oText.createTextRange();
        oRange.moveStart("character",iStart);
        oRange.moveEnd("character",iEnd-this.oText.value.length);
        oRange.select();
    }
    else if(this.oText.setSelectionRange) /* For Mozilla */
    {
        this.oText.setSelectionRange(iStart,iEnd);
    }
    this.oText.focus();
};

autoComplete.prototype.textComplete=function(sFirstMatch)
{
    if(this.oText.createTextRange || this.oText.setSelectionRange)
    {
        var iStart=this.oText.value.length;
        this.oText.value=sFirstMatch;
        this.selectText(iStart,sFirstMatch.length);
    }
};

autoComplete.prototype.keyDown=function(oEvent)
{
    oEvent=window.event || oEvent;
    iKeyCode=oEvent.keyCode;

    switch(iKeyCode)
    {
        case 38: //up arrow
            this.autoComplete.moveUp();
            break;
        case 40: //down arrow
            this.autoComplete.moveDown();
            break;
        case 13: //return key
            window.focus();
            break;
    }
};

autoComplete.prototype.moveDown=function()
{
    if(this.oDiv.childNodes.length>0 &&
this.cur<(this.oDiv.childNodes.length-1))
    {
        ++this.cur;
        for(var i=0;i<this.oDiv.childNodes.length;i++)
        {
            if(i==this.cur)
            {
                this.oDiv.childNodes[i].className="over";
                this.oText.value=this.oDiv.childNodes[i].innerHTML;
            }
            else
            {
                this.oDiv.childNodes[i].className="";
            }
        }
    }
};

autoComplete.prototype.moveUp=function()
{
    if(this.oDiv.childNodes.length>0 && this.cur>0)
    {
        --this.cur;
        for(var i=0;i<this.oDiv.childNodes.length;i++)
        {
            if(i==this.cur)
            {
                this.oDiv.childNodes[i].className="over";
                this.oText.value=this.oDiv.childNodes[i].innerHTML;
            }
            else
            {
                this.oDiv.childNodes[i].className="";
            }
        }
    }
};

autoComplete.prototype.keyUp=function(oEvent)
{
    oEvent=oEvent || window.event;
    var iKeyCode=oEvent.keyCode;
    if(iKeyCode==8 || iKeyCode==46)
    {
        this.autoComplete.onTextChange(false); /* without autocomplete */
    }
    else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode <= 46) ||
(iKeyCode >= 112 && iKeyCode <= 123))
    {
        //ignore
    }
    else
    {
        this.autoComplete.onTextChange(true); /* with autocomplete */
    }
};

autoComplete.prototype.positionSuggest=function() /* to calculate the
appropriate poistion of the dropdown */
{
    var oNode=this.oText;
    var x=0,y=oNode.offsetHeight;

    while(oNode.offsetParent && oNode.offsetParent.tagName.toUpperCase() !=
'BODY')
    {
        x+=oNode.offsetLeft;
        y+=oNode.offsetTop;
        oNode=oNode.offsetParent;
    }

    x+=oNode.offsetLeft;
    y+=oNode.offsetTop;

    this.oDiv.style.top=y+"px";
    this.oDiv.style.left=x+"px";
}

autoComplete.prototype.onTextChange=function(bTextComplete)
{
    var txt=this.oText.value;
    var oThis=this;
    this.cur=-1;

    if(txt.length>0)
    {
        while(this.oDiv.hasChildNodes())
            this.oDiv.removeChild(this.oDiv.firstChild);

        var aStr=new Array();
        this.db.getMatches(txt,aStr,this.maxSize);
        if(!aStr.length) {this.hideSuggest ;return}
        if(bTextComplete) this.textComplete(aStr[0]);
        this.positionSuggest();

        for(i in aStr)
        {
            var oNew=document.createElement('div');
            this.oDiv.appendChild(oNew);
            oNew.onmouseover=
            oNew.onmouseout=
            oNew.onmousedown=function(oEvent)
            {
                oEvent=window.event || oEvent;
                oSrcDiv=oEvent.target || oEvent.srcElement;

                //debug :window.status=oEvent.type;
                if(oEvent.type=="mousedown")
                {
                    oThis.oText.value=this.innerHTML;
                }
                else if(oEvent.type=="mouseover")
                {
                    this.className="over";
                }
                else if(oEvent.type=="mouseout")
                {
                    this.className="";
                }
                else
                {
                    this.oText.focus();
                }
            };
            oNew.innerHTML=aStr[i];
        }

        this.oDiv.style.visibility="visible";
    }
    else
    {
        this.oDiv.innerHTML="";
        this.oDiv.style.visibility="hidden";
    }
};

/*function createAutoComplete()
{
    var aNames = <?php //print_r($js_array); ?>;
    new
autoComplete(aNames,document.getElementById('txt'),document.getElementById('suggest'),20);
}
*/
function createAutoComplete1(txt_input, suggest_div)
{
    var aNames = <?php print_r($js_array); ?>;
    new
autoComplete(aNames,document.getElementById(txt_input),document.getElementById(suggest_div),20);
}

/*<![CDATA[*/
var c=1;
function newInput()
{
    //Create DIV
    var div = document.createElement('div');
    div.id = "div_" + c;
    document.f1.appendChild(div);
    //Input TEXT
    var inpt = document.createElement('input');
    inpt.type="text";
    inpt.name="input_" + c;
    inpt.id="txt_" + c;
    inpt.setAttribute ('autocomplete', 'off');
    inpt.setAttribute ( 'style', "border:#000000 1px solid; width:250px;");
    div.appendChild(inpt);
    //Link +
    div.innerHTML += "<a style='text-decoration:none' href='#'
onclick='javascript:newInput()'> [+] </a>";
    //Link -
    div.innerHTML += "<a style='text-decoration:none' href='#'
onclick='javascript:removeInput(\"div_" + c + "\")'> [-] </a><br>";
    //Create DIV SUGGEST
    var divS = document.createElement('div');
    divS.id = "suggest_" + c;
    divS.setAttribute ( 'style', "visibility:hidden; border:#000000 1px
solid; width:auto;");
    divS.setAttribute ( 'class', "suggest");
    div.appendChild(divS);
    createAutoComplete1(inpt.id, divS.id);
    c += 1;

}
function removeInput(id)
{
    if(cantElementForm() > 1)
        document.f1.removeChild(document.getElementById(id));
    else
        alert ("ATENCIÓN!\nNo se puede borrar el único elemento de carga");
}

function cantElementForm()
{
    return document.forms.item(0).elements.length;
}
/*]]>*/
</script>
<style type="text/css" media="all">
.suggest{
    position:absolute;
    background:#fff;
    width:200px;
    }

.suggest div{
    background:#fff;
    color:#000;
    padding-left:4px;
    cursor:hand;
    text-align:left;
    }

.suggest div.over{
    color:#fff;
    background:#000;
    }
</style>

<script type="text/javascript">

</script>

</head>

<body onLoad="newInput(); createAutoComplete();">
<?php
    //echo "Factura Nro.: ".$_GET['FacturaID'];
    echo "Factura Nro.: ";
?>
<br />
<div>
    <form action="#" method="get" name="f1" id="f1" autocomplete=off>
<!--        <div id="div_0">
            <input type="text" name="searchField" id="txt_0"
style="border:#000000 1px solid;width:150px;" autocomplete=off>
            <a href="#" onclick="javascript:newInput()"
style="text-decoration:none"> [+] </a><br>
            <div class="suggest" id="suggest_0"
style="visibility:hidden;border:#000000 1px solid;width:150px;"></div>
           </div>
-->    </form>
</div>


</body>
</html>
------------ próxima parte ------------
Se ha borrado un adjunto en formato HTML...
URL: http://www3.fi.mdp.edu.ar/pipermail/php-avanzado/attachments/20100729/1af3c930/attachment-0001.htm 


Más información sobre la lista de distribución Php-avanzado