Risposta ajax -> json con php

otto9due

Utente Attivo
22 Feb 2014
591
25
28
Il mio obiettivo è quello di fare una richiesta ajax in post da "index.php" ad una pagina "richiamo.php" ( la richiesta è contenuta nel file script.js che vedete sotto ). Quello che vorrei ottenere come risultato è che fatta la richiesta la pagina richiamo.php produca un json_encode($arr); in questo caso quindi encode della mia array, che verrà poi trasmessa alla index.php.
Volendola usare con php poi, devo riuscire ricevuta quest'array codificata, decodificarla tramite php nuovamente trasformandola ed utilizzandola quindi come una normale array.
In pratica usare ajax come un semplice mezzo di trasporto dati.

Ho scritto questi file ma non ottengo ne il risultato sperato ne errori:

richiamo.php
PHP:
<?php
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
        $data = json_encode($arr);

        echo $data;
    }
?>

index.php
PHP:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="script.js"></script>
<title>Documento senza titolo</title>
</head>

<body>
    <button id="#but">Prova</button>
    <div id="out"></div>
</body>
</html>

script.js
Codice:
$(document).ready(function () {
    $("#but").click(function () {
        $.ajax({
            type: "POST",
            url: "richiamo.php",
            data: {action: 'test'},
            dataType: 'JSON',
            success: function (response) {
                var esc = JSON.stringify(response);
                console.log(esc);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    });
});

Ringrazio anticipatamente per l'aiuto.
Saluti G.G.
 
In pratica usare ajax come un semplice mezzo di trasporto dati.

- interpreto, perchè non so se ho capito bene,

- un php mi fornisce dei dati in un'array
- una pagina html con javascript, riceve l'array, codificata json, dallo script php via ajax
- converte la stringa che sta transitando, per poter usare l'array anche nella pagina html (se serve)
- invia, via ajax, la string (json) ad un secondo script php che la riceve e la usa
- oppure con "POST" (submit) passa i valori ad uno script php che li gestisce ... (non nell'esempio)

PHP:
<?php
// esempio_8_CreateArray.php

$data = array
(
    'foo'  => 123,
    'bar'  => 456,
    'rows' => array
    (
        0 => array
        (
            'column1' => 'hello',
            'column2' => 'hola',
            'column3' => 'bonjour',
        ),
        1 => array
        (
            'column1' => 'goodbye',
            'column2' => 'hasta luego',
            'column3' => 'au revoir',
        ),
        2 => array
        (
            'column1' => 'hello',
            'column2' => 'hola',
            'column3' => 'bonjour',
        ),
        3 => array
        (
            'column1' => 'goodbye',
            'column2' => 'hasta luego',
            'column3' => 'au revoir',
        ),
    ),
    'test1' => array
    (
        'test2' => array
        (
            'test3' => 'abcdef'
        )
    )
);

echo json_encode($data);
?>

HTML:
<!DOCTYPE html>
<html>
    <head>
        <!-- esempio_8__DataTransferByAjax.html -->

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>jQuery AJAX array transfer</title>

        <script type="text/javascript" src="jquery.min.js"></script>

        <script type="text/javascript">

$(document).ready(function()
{
    $('#myButton').bind("click",function()
    {
        alert( "Handler for .click() called." );

        var risultato;

        $.ajax
        ({
            type:    'post',
            cache:   false,
            url:     'esempio_8_CreateArray.php',
            success: function(response)
            {
                risultato = response;
                alert(risultato);

                var dataJ = JSON.parse(risultato);
                alert(dataJ['foo']+' - '+dataJ['test1']['test2']['test3']);

                invio_successivo();
            },
            error: function() { alert('errore esecuzione esempio_8_CreateArray.php'); }
        });

        function invio_successivo()
        {
            $.ajax
            ({
                type:    'post',
                cache:   false,
                url:     'esempio_8_DisplayArray.php',
                data:
                {
                    data : risultato
                },
                success: function(response)
                {
                    $('#myDiv').html(response);
                },
                error: function() { alert('errore esecuzione esempio_8_DisplayArray.php'); }
            });
        }
    });
});
        </script>
    </head>
    <body>
        <input id="myButton" type="button" style="width: 130px; height: 60px" value="esegui AJAX" />
        <br /> <br />
 <div id="myDiv"> </div>
    </body>
</html>

PHP:
<?php
// esempio_8_DisplayArray.php

$data = json_decode($_POST['data']);

var_dump($data);
?>
upload_2017-9-1_17-10-58.png

upload_2017-9-1_17-11-38.png

upload_2017-9-1_17-12-6.png

upload_2017-9-1_17-12-45.png
 
Innanzitutto grazie per la risposta e per la disponibilità. Non ho risposto subito poichè avevo risolto in altro modo, ma a questo punto vorrei capirci qualcosa in più, colgo l'occasione per approfondire, se non ti dispiace.
Allora, il mio dubbio è questo: le richieste ajax possono essere fare sia con javascript che tramite la sua libreria jquery giusto?
Io ho fatto come nell'esempio sotto alla fine, in pratica cosa ho fatto e cosa ho utilizzato per la richiesta?
Codice:
$( document ).ready(function() {
    $("button#but").click(function () {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
                var arr = JSON.parse(this.responseText);
                $("#out").html(arr["c"]);
            }
        };
        xmlhttp.open("post", "http://dev.miosito.com/jebo/test/richiamo.php", true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send("prova=test123&cc=prova2");
    });
});

Farò altre prove tramite $.ajax(), sperando di riuscire anche così, perchè ancora quello non mi riesce.
 
Mi sa che ho capito il problema.. In pratica quello che generava il blocco dello script era il
Codice:
dataType: "json",
Togliendo questa parte, in questo modo, funge..
Codice:
$(document).ready(function () {
    $("button#but").click(function () {
        $.ajax
            ({
                type: "POST",
                url: 'http://dev.miosito.com/jebo/test/richiamo.php',
                cache: false,
                data: "prova=test123&cc=prova2",
                success: function (response)
                {
                    var arr = JSON.parse(response);
                    $("#out").html(arr["c"]);
                },
                error: function () {
                    alert('errore esecuzione richiamo.php');
                }
            });
    });
});

Grazie per l'aiuto, ma se qualcuno mi spiegasse bene come funziona il tutto, sarebbe molto gradito.
 

Discussioni simili