-1

I received a array in json. How can I get values with bucle for in javascript?. If array json hasn't assign a variable name

I have a array in php which convert to json

 echo json_encode($error);

I get the json following:

json image

values in json

["El nombre del usuario no puede estar vacio","La contrase\u00f1a debe tener un m\u00ednimo de
 7 caracteres"]

How can I get data in javascript my function ajax

      function submitForm()
        {
            var dataString = $("#userForm").serialize();
            console.log(dataString);
            $.ajax({
                type: "POST",
                url: "/altausers",
                data: dataString,
                success: function(text)
                {
                   if(text==='success')
                   {

                   }
                   else
                   {
                       $("#error").removeClass('hidden'); 
#get values json here



                   }
                }
            });

    }
mangulom
  • 65
  • 6
  • Possible duplicate of [Parse JSON in JavaScript?](http://stackoverflow.com/questions/4935632/parse-json-in-javascript) – Epodax Feb 23 '16 at 11:35

2 Answers2

0

PHP has method known as json_encode and json_decode which can me used to handle json data in php, while the json data can be directly accessed in javascript so I think you should look into that

Dhananjay Gupta
  • 316
  • 2
  • 11
0

You would have to specify

dataType: 'json'

then, your data would be in a javascript array:

function submitForm()
    {
        var dataString = $("#userForm").serialize();
        console.log(dataString);
        $.ajax({
            type: "POST",
            url: "/altausers",
            data: dataString,
            dataType: 'json',
            success: function(text)
            {
               if(text.length > 0) {
               $.each(text,function(index,value) {
                    alert('Response: '+ value);
               }

            }
        });

}

However, you would have to make sure that php ALWAYS returns a json-encoded response... even if you do it manually like:

<?php echo "[success]"; ?>

In javascript, you would just test

if(text[0] == 'success') { //hurray!!
}
Valerie
  • 332
  • 2
  • 9
  • 1
    Technically you don't _have_ to specify `dataType: 'json'` if you're sending a `Content-type: application/json` header. – h2ooooooo Feb 24 '16 at 08:54
  • @h2ooooooo you're right. Additionally, other mime types can be sent which will produce a different data result (if you do not use `dataType`). see: http://api.jquery.com/jquery.ajax/ – Valerie Feb 24 '16 at 09:02