0

I'm having a problem with converting data sended from "naloga3.php" . How can i convert from JSON to array.

JAVASCRIPT

<script>
function shrani(){

    var formData = {naslov: document.getElementById("naslov").value,
                    besedilo: document.getElementById("besedilo").value,
                    datum:0
                    };


    $.ajax({
        url : "naloga3.php",
        type: "POST",
        data : formData,
        success: function(data, textStatus, jqXHR)
        {
            $('#zapisi').append('<a>'+data+'</a></br>');
            var x = eval("(" + data + ")");
            for(var i=0;i<x.length;i++)
            {
                $('#zapisi').append('<a>'+x.length+'</a></br>');
            }

        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            $('#zapisi').append('<a>Napaka</a></br>');
        }

    });

}


</script>

naloga3.php

<?php

$file="podatki.txt";
$podatki=file_get_contents($file);

$izpolje=array();
$izpolje= json_decode($podatki,true);
$polje=$_POST;
$polje['datum']=date('H:i:s');
if($izpolje!=null)
{
    array_unshift($izpolje,$polje);
    file_put_contents($file,json_encode($izpolje));
}else
{
    $tr=array();
    array_unshift($tr,$polje);
    file_put_contents($file,json_encode($tr));
}


$podatki=file_get_contents($file);
echo json_encode($izpolje);

?>

My output

[{"naslov":"d","besedilo":"d","datum":"16:07:05"},{"naslov":"dddd","besedilo":"d","datum":"15:51:41"},{"naslov":"d","besedilo":"d","datum":"15:51:33"},{"naslov":"d","besedilo":"d","datum":"15:51:30"},{"naslov":"d","besedilo":"d","datum":"15:51:26"}]

1 Answer 1

0

What you need to do is set the dataType of your ajax response to json, then you need to iterate the returned object and append within the $.each() loop.

$.ajax({
    url : "naloga3.php",
    type: "POST",
    data : formData,
    dataType: "json", // jQuery will now parse the returned data and return an object
    success: function(data, textStatus, jqXHR)
    {

        $.each(data, function(i,obj){
            //now you can acess navlos, besedilo and datum
            $('#zapisi').append(obj.naslov+'</br>');
            $('#zapisi').append(obj.besedilo+'</br>');
            $('#zapisi').append(obj.datum+'</br>');
        });
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        $('#zapisi').append('<a>Napaka</a></br>');
    }

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.