javascript - PHP / JQUERY - display each sub array of json -


i have post script below, current script output this.

["error1","error2","error3"]

["good1","good2","good3"]

i want output each error in separate paragraph , each in paragraph

php script

        $error[] = "error1";         $error[] = "error2";         $error[] = "error3";          $good[] = "good1";         $good[] = "good2";         $good[] = "good3";          $data["error"] = json_encode($error);         $data["good"] = json_encode($good);          die(json_encode($data)); 

jquery script

    function _request()     {         $("form").submit(function(e)         {             e.preventdefault();              $.ajax(             {                 url: $(this).attr("action"),                 type: "post",                 data: $(this).serializearray(),                 datatype: 'json',                 success: function(result)                 {                     var data = "";                      $.each(result, function(index, item)                     {                         data += "<p>" + item + "</p>";                     });                      $("#result").html(data);                 }             });         });     } 

don't json encode arrays individually, encode complete data structure @ end, otherwise when decoding on client-side, nested json treated string.

so this:

    $error[] = "error1";     $error[] = "error2";     $error[] = "error3";      $good[] = "good1";     $good[] = "good2";     $good[] = "good3";      $data["error"] = $error;     $data["good"] = $good;      echo json_encode($data); 

you work data on client side this:

        $.ajax(         {             url: $(this).attr("action"),             type: "post",             data: $(this).serializearray(),             datatype: 'json',             success: function(data)             {                 var $result = $('#result');                 $result.empty();                  $.each(data.error, function(idx, item) {                     $result.append('<p class="error">' + item + '</p>');                 });                  $.each(data.good, function(idx, item) {                     $result.append('<p class="good">' + item + '</p>');                 });             }         }); 

note added class names paragraphs in case wanting control css display of them via convenient classes.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -