Problem with return in AJAX PHP

1

I have a problem using AJAX.

I have created a function to call a function within a PHP class by means of AJAX and at the moment of calling the function, I return a response with a return.

This is my AJAX function, where the php class identifies 'cmd' and interprets it as a function.

function nk_route_get(ModuleUrl, Data = {}, Alert = {}) {

    if (Data['cmd']) {

        $.ajax({
            data: Data,
            url: ModuleUrl,
            type: 'get',
            beforeSend: function () {

            },
            success: function (response) {


                if (response == 1) {
                    $(".alert").addClass("hidden");
                    $('#alert-success').removeClass('hidden')
                    $('#alert-success-text').html("<i class=\"fa fa-check fa-2x\"></i>&nbsp;" + Alert['success']);
                    $("input").css({"border-color": "#ced4da"});
                } else if (response == 2) {
                    $('#alert-danger').removeClass('hidden')
                    $('#alert-danger-text').html("<i class=\"fa fa-exclamation-triangle fa-2x\"></i>&nbsp;Ha ocurrido un error, consulte con el administrador.<br>");
                } else {
                    $('#alert-danger').removeClass('hidden')
                    $('#alert-danger-text').html("<i class=\"fa fa-exclamation-triangle fa-2x\"></i>&nbsp;" + response);
                    // $("#Alert").html(response);
                }
            }
        });

    }

    else {

        console.warn("No se han mandado los parametros solicitados.")

    }

} 

This is what I put in my PHP function where I call a function that returns a return.

 $html = nk_forms::html("ul",["class"=>'list-group list-group-flush'],nk_forms::html("li",['class'=>'list-group-item'],'asjjhd'));


 $Scripts = "$('#Modal-Body').html('{$html}');";

 echo "<script>{$Scripts}</script>";;

And this is the function that returns a return.

static function html($Tag,$Attr,$Html){

        $HtmlAttr = "";

        if (!$Tag || !$Attr || !$Html){
            return false;
        }

        if (is_array($Attr)){

            foreach ($Attr as $id => $value ){
                $HtmlAttr .= $id . " = '" . "{$value}'";
            }

        }

        $HtmlTag = "<{$Tag} {$HtmlAttr} >{$Html}</{$Tag}>";

        return $HtmlTag;

    }

The problem with this is that the return cuts off the AJAX response.

    
asked by AlejandroBec 07.05.2018 в 17:54
source

4 answers

1

I am not an expert in php, but I notice that your html function is generating invalid html. When you set an attribute for an html tag you should use double and non-simple quotes like you do in this part of the cycle:

if (is_array($Attr)){
   foreach ($Attr as $id => $value ){
       $HtmlAttr .= $id . " = '" . "{$value}'";
   }
}

That said, the goal is to generate a label such as:

<div class="clase-x"></div>

But your code is generating the html even with some unwanted separations, I give you an approximation of what is generating your function:

<div class = 'clase-x' ></div>

I leave my test code based on yours to watch, to clarify I'm escaping the double quotes that way, if there is a better way in php you can comment on it.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script>
<div id="Modal-Body"></div>
<?php
     function html($Tag,$Attr,$Html){
     $HtmlAttr = "";
     if (!$Tag || !$Attr || !$Html){
         return false;
     }
    if (is_array($Attr)){
        foreach ($Attr as $id => $value ){
            //esta linea es diferente a la tuya
            $HtmlAttr .= $id."=\"{$value}\"";
        }
    }
    //esta linea es diferente a la tuya
    $HtmlTag = "<{$Tag} {$HtmlAttr}>{$Html}</{$Tag}>";
    return $HtmlTag;
 }

//esta linea es una adaptación de la tuya
$html = html("ul",["class"=>'list-group list-group-flush'],html("li",['class'=>'list-group-item'],'asjjhd'));
$Scripts = "$('#Modal-Body').html('{$html}');";

echo "<script>{$Scripts}</script>";
?>

All this code I have put in a single php file so it should work as it is.

Greetings

    
answered by 07.05.2018 / 22:27
source
0

As I see it, you need to print the variable $html :

$html = nk_forms::html("ul",["class"=>'list-group list-group-flush'],nk_forms::html("li",['class'=>'list-group-item'],'asjjhd'));
echo $html;
    
answered by 07.05.2018 в 18:12
0

I do not know the framework that you are using but in the ajax part only send the request and not the data that the function has, my answer is not 100% secure since the class is called and second the function

function nk_route_get(ModuleUrl,Data,Alert) {

         $.ajax({
          type: "get",
          url: 'html/'+ModuleUrl+'/'+Data+'/'+Alert,
          //data: $("#myForm").serialize(), 
          async: false,
          dataType: 'json',
          success: function (response) { 
            alert(response);
            /*
           if (response == 1) {
                    $(".alert").addClass("hidden");
                    $('#alert-success').removeClass('hidden')
                    $('#alert-success-text').html("<i class=\"fa fa-check fa-2x\"></i>&nbsp;" + Alert['success']);
                    $("input").css({"border-color": "#ced4da"});
                } else if (response == 2) {
                    $('#alert-danger').removeClass('hidden')
                    $('#alert-danger-text').html("<i class=\"fa fa-exclamation-triangle fa-2x\"></i>&nbsp;Ha ocurrido un error, consulte con el administrador.<br>");
                } else {
                    $('#alert-danger').removeClass('hidden')
                    $('#alert-danger-text').html("<i class=\"fa fa-exclamation-triangle fa-2x\"></i>&nbsp;" + response);
                    // $("#Alert").html(response);
                }
            */

            //  show_lista_asistencias(id);
          },
          error: function(jqXHR, text, error){
                // Displaying if there are any errors
                 // $('#result').html(error);
              alert('no se pudo add los datos');
            }
        });
} 

and in the back-font part place the following code:

  <?php 

static function html($Tag,$Attr,$Html){

        $HtmlAttr = "";

        /*
        */
        if (!$Tag || !$Attr || !$Html){
            return false;
        }

        if (is_array($Attr)){

            foreach ($Attr as $id => $value ){
                $HtmlAttr .= $id . " = '" . "{$value}'";
            }

        }

        $HtmlTag = "<{$Tag} {$HtmlAttr} >{$Html}</{$Tag}>";

        echo json_encode($HtmlTag);


    }

?>
    
answered by 07.05.2018 в 18:56
0

This is how my code was:

 //AD HTML to Modal
        $html = nk_forms::html("ul",["class"=>'list-group list-group-flush'],
           nk_forms::html("li",['class'=>'list-group-item'],nk_forms::html("strong",[],'Fecha Solicitud:&nbsp;' ).date("d/m/Y", strtotime($CardInfo["DocDate"]))).
           nk_forms::html("li",['class'=>'list-group-item'],nk_forms::html("strong",[],'Nombre:&nbsp;'). $CardInfo["CardName"]).
           nk_forms::html("li",['class'=>'list-group-item'],nk_forms::html("strong",[],'Clabe:&nbsp;').$CardInfo["CardClabe"]).
           nk_forms::html("li",['class'=>'list-group-item'],nk_forms::html("strong",[],'Email:&nbsp;'). $CardInfo["CardEmail"]).
           nk_forms::html("li",['class'=>'list-group-item'],nk_forms::html("strong",[],'Banco:&nbsp;'). $CardInfo["CardBankName"]).
           nk_forms::html("li",['class'=>'list-group-item'],nk_forms::html("strong",[],'Clave de Banco:&nbsp;'). $CardInfo["CardBankCode"]).
           nk_forms::html("li",['class'=>'list-group-item'],nk_forms::html("strong",[],
               nk_forms::html("a",['class'=>'pull-left','href'=>"../{$FileInfo['FilePath']}{$FileInfo['FileName']}","download"=>"{$CardInfo['CardRequestId']}{$CardInfo['CardId']}"],
                   nk_forms::html("img",['class'=>'grow',"style"=>'max-height:150px;','src'=>"../{$FileInfo['FilePath']}{$FileInfo['FileName']}"]," ")

               ),""))
        );

        $footer = nk_forms::html("button",['type'=>"button","class"=>"btn btn-danger"],"Rechazar").
            nk_forms::html("button",['type'=>"button","class"=>"btn btn-success pull-right"],"Aceptar");

        //TODO Add JS AJAX to change status to 4

        $JS[] = nk_forms::setHTML("Modal-Basic-Body", $html);
        $JS[] = nk_forms::setHTML("Modal-Basic-Footer", $footer);
        //$JS[] = '$("#DownloadFile").on("click",function () { nk_route_post("../../../includes/download_file.php",{"FileId":$("#FileId").val()});});';
        render::modal("<i class=\"fa fa-clipboard\"></i>&nbsp;Solicitud - " . $CardInfo['CardRequestId'], $JS, false);

The function was:

static function html($Tag,$Attr,$Html){

        $HtmlAttr = "";

        if (!$Tag  || !$Html){
            return false;
        }

        if (is_array($Attr) && $Attr){

            foreach ($Attr as $id => $value ){
                $HtmlAttr .= $id . " = \"" . "{$value}\"";
            }

        }

        $HtmlTag = "<{$Tag} {$HtmlAttr} >{$Html}</{$Tag}>";

        return $HtmlTag;

    }

Save me the following line of code:

$html = '<ul class="list-group list-group-flush"><li class="list-group-item"><strong>Fecha Solicitud:&nbsp;</strong>' . date("d/m/Y", strtotime($CardInfo["DocDate"])) . '</li><li class="list-group-item"><strong>Nombre:&nbsp;</strong>' . $CardInfo["CardName"] . '</li><li class="list-group-item"><strong>Clabe:&nbsp;</strong>' . /*str_repeat('*', 14) . substr(*/
            $CardInfo["CardClabe"]/*, "14", "18")*/ . '</li><li class="list-group-item"><strong>Email:&nbsp;</strong>' . $CardInfo["CardEmail"] . '</li><li class="list-group-item"><strong>Banco:&nbsp;</strong>' . $CardInfo["CardBankName"] . '</li><li class="list-group-item"><strong>Clave de Banco:&nbsp;</strong>' . $CardInfo["CardBankCode"] . '</li><li  class="list-group-item " ><a  class="pull-left"  href="../'. $FileInfo['FilePath']. $FileInfo['FileName'].'" download="'.$CardInfo['CardRequestId'].'_'.$CardInfo['CardId'].'" ><img  class="grow" style=" max-height:150px; " src="../'. $FileInfo['FilePath']. $FileInfo['FileName'].'"></a></li></ul>'   ;


        $footer = '<button type="button" class="btn btn-danger">Rechazar</button><button type="button" class="btn btn-success pull-right">Aceptar</button>';
    
answered by 07.05.2018 в 23:34