0

I am trying to parse the JSON string sent as ajax response from PHP file using jQuery / JavaScript.

Ajax call:

<script>

            $(document).ready(function(){

              var query = $("#editor").html().replace(/(<([^>]+)>)/ig,"");
                      $.ajax({
                           type: "POST",
                           url: "app/query_db.php",
                           data: "q="+query,
                           success: function(resp){    
                                if(resp)    {
                                    alert("Response : "+resp);
                                    $("#res_data").html(resp);

                                }
                                else{
                                    alert("Response: Failed")
                                }
                      });
                    return false;
                });

            });
        </script>

PHP file :

$db_conn = new db_connect();
    $conn = $db_conn->connectToDB($DBHost,$DBName,$DBUser,$DBPwd);

    $query_res = array();


    if (fill_numeric_array_with_query_assoc($query_res, $sql_query, $conn)) {   // Function to execute the query and fill the result
        //do nothing
    } else {
        echo("Error description: " . mysqli_error($conn));  // Error message to display if failed to fetch the data
        exit();
    }
$data = json_encode($query_res);
    echo $data;

Result: [{"uid":"admin","pwd":"xyz"},{"uid":"guest","pwd":"abc"}]

Whenever I try to parse the above JSON string I am ending up with 0 and 1 as keys and the other stuff as values. The strange thing is when I copy this result and assign it to a variable in JavaScript it's parsing the string correctly.

Don't know what's going wrong when trying to parse it as AJAX response.

Table format when parsed the JSON string as AJAX response:

Image attached

Response when assigned to variable in javascript :

uid     pwd

admin   xyz

guest   abc
6
  • "whenever I try to parse the above json string I am ending up with 0 and 1 as keys and the other stuff as values." Yep that's right, because it's an array with two objects in it. The first object is at index 0 in the array, the second object is at index 1. What were you expecting? Commented Aug 21, 2017 at 13:11
  • 1
    Your JSON is an array, which have numeric keys, hence the 0 and 1? Commented Aug 21, 2017 at 13:11
  • what you want to try with this object? want to append in table? Commented Aug 21, 2017 at 13:12
  • "what you want to try with this object? want to append in table? – Muhammad Akber Khan" - Yeah. I am trying to create a table out of it Commented Aug 21, 2017 at 13:14
  • "whenever I try to parse the above json string I am ending up with 0 and 1 as keys and the other stuff as values." Yep that's right, because it's an array with two objects in it. The first object is at index 0 in the array, the second object is at index 1. What were you expecting? – ADyson" - I am trying to create a table by parsing the json string and want the result similar to below Response when assigned to variable in javascript : uid pwd admin xyz guest abc Commented Aug 21, 2017 at 13:19

1 Answer 1

1

This will take the data and turn each object into a row in a table. I'm going to assume that #res_data is an empty <table> element.

$.ajax({
  type: "POST",
  url: "app/query_db.php",
  data: "q=" + query,
  dataType: "json",
  success: function(resp) {
    if (resp) {
      alert("Response : " + resp);
      $("#res_data").empty();
      if (resp.length > 0) {
        var header = "<tr>";
        for (var key in resp[0]) { 
          "<th>" + key + "</th>"; 
        }
        header += "</tr>";
        $("#res_data").append(header);
        var rows = "";
        for (var i=0; i< resp.length;i++) {
          rows += "<tr><td>" + resp[i].uid + "</td><td>" + resp[i].pwd + "</td></tr>";
        }
        $("#res_data").append(rows);
      }
      else { alert("No data returned"); }
    } else {
      alert("Response: Failed")
    }
  }
});

Note the extra ajax option: dataType: "json". This is important. Because your PHP doesn't send any header to tell the client to interpret the response as JSON, it likely interprets it as text. So you have to add dataType:"json" so jQuery knows what to do, and makes the response directly into a JS object. Then you should have no problem. If you don't, then it will see it as a string, and then loop through it one character at a time, which will result in the strange output you showed in the question.

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

11 Comments

Thanks for the reply. However I am looking to create the table header dynamically by extracting the keys from the json string.
ok well you can loop through the first object in the array and extract the keys. If you're not sure how to do that, I can create an example of that too. You'd use a for...in loop
Below is the javascript code used for creating the table : var col = []; for (var i = 0; i < resp.length; i++) { for (var key in resp[i]) { if (col.indexOf(v) === -1) { col.push(v); } } } console.log(col); // CREATE DYNAMIC TABLE. var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE. var tr = table.insertRow(-1); // TABLE ROW. for (var i = 0; i < col.length; i++) { var th = document.createElement("th"); // TABLE HEADER. th.innerHTML = col[i]; tr.appendChild(th); } // ADD JSON DATA TO THE TABLE AS ROWS. for (var i = 0; i < resp.length; i++) { tr = table.insertRow(-1); for (var j = 0; j < col.length; j++) { var tabCell = tr.insertCell(-1); tabCell.innerHTML = resp[i][col[j]]; } }
Thanks a lot Adyson adding dataType in ajax call worked like a charm
|

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.