like passing an array by js to php [duplicated]

0

I have the following code

<a style="cursor: pointer;" onclick="verMatch2(this,'<?php echo base64_encode($datosSolicitud['id']);?>','<?php print_r($datosSolicitud); ?>');">

I want to pass $datosSolicitud which is an array to a js file

function verMatch2(elemento,solicitudEmpleo,datosSolicitud){
    $("tr.tmp").remove();
    tmp = $(elemento); fila = tmp.closest('tr');
    $.ajax({
    data: {solicitudEmpleo : solicitudEmpleo,datosSolicitud : datosSolicitud},
        url:   'index.php?accion=verMatch2',
            type:  'post',
        success:  function (data) {
            fila.after("<tr class='tmp'><td colspan='6'>"+data+"</td></tr>");
            $(".loader").fadeOut("fast");
            $('.selectpicker').selectpicker(parametros);
        },
    });
}

then receive it in the controller but how do I send it? if it was not fix I use echo to print it in the javascript function.

    
asked by Carlos Enrique Gil Gil 21.04.2018 в 00:32
source

2 answers

2

To solve this you could use:

  • json_encode : This function will convert the array PHP into a string equivalent to a% object JS .
  • htmlspecialchars : This function takes a string and escapes only those characters that can cause the string to break HTML when printing the value within the attribute of an element.

Solution

<a style="cursor: pointer;" onclick="verMatch2(this,'<?php echo base64_encode($datosSolicitud['id']);?>',<?php echo htmlspecialchars(json_encode($datosSolicitud)); ?>);">texto</a>

Example

<?php
$datosSolicitud = [
    'id'=> 1,
    'algo'=> 'Texto con \'asd\' "dsa"'
];

$json = json_encode($datosSolicitud);
// $json == {"id":1,"algo":"Texto con 'asd' \"dsa\""}

$html = htmlspecialchars($json);
// $html == {&quot;id&quot;:1,&quot;algo&quot;:&quot;Texto con 'asd' \&quot;dsa\&quot;&quot;}

Demo

function verMatch2(el, id, data) {
  console.log(data);
}
<a style="cursor: pointer;" onclick="verMatch2(this,'MQ==',{&quot;id&quot;:1,&quot;algo&quot;:&quot;Texto con 'asd' \&quot;dsa\&quot;&quot;});">Hacer click aqui</a>
    
answered by 21.04.2018 / 01:40
source
2
<a style="cursor: pointer;" onclick="verMatch2(this,'<?php echo base64_encode($datosSolicitud['id']);?>','<?= array_implode(',', $datosSolicitud) ?>');">

index.php

$datosSolicitud = array_explode(',', $_POST['datosSolicitud']);
    
answered by 21.04.2018 в 01:22