0

I want to fetch data from database using PHP and Ajax, which is first encoded into JSON.

But data is not printed properly on the screen. It shows elements of four rows in single line separated by comma.

$(document).ready(function() {
  $(function()
    {
      $.ajax({
        url: 'demo2.php',
        data: "",
        dataType: 'json',
        success: function(data)
        {
          var name = data[0];
          var email = data[1];
          var msg = data[2];
          var date1 = data[3];
          $('#output').html("<div id='container'>" + name + " " + email + " " + msg + " " + date1 + "</div><br>");
        }
      });
    });
});

6
  • Please share data which you want to print and format to print Commented Feb 9, 2018 at 9:23
  • Provide your json coming from server Commented Feb 9, 2018 at 9:23
  • "four rows in single line" - How does that work? Either you get four rows or a single line Commented Feb 9, 2018 at 9:29
  • share the data which you are getting from demo2.php Commented Feb 9, 2018 at 9:35
  • try to display the data in console and check. Commented Feb 9, 2018 at 9:37

1 Answer 1

2

Try this:

$(document).ready(function() {
  $(function()
    {
      $.ajax({
        url: 'demo2.php',
        data: "",
        dataType: 'json',
        success: function(data)
        {
          console.log(JSON.stringify(data));
          var obj = JSON.parse(data);
          // Iterate object:
          my_text=''
          $.each(obj, function(index, value) {
             console.log(value);
             my_text += value
          }); 

          // var obj = JSON.parse('{ "name":"John", "email":"[email protected]", "msg":"Hello"}');
          $('#output').html("<div id='container'>" + my_text + "</div><br>");
        }
      });
    });
});

Fiddle: https://jsfiddle.net/fks3j500/

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

7 Comments

Provide additional info! Give json data, console output. Also make sure your output is in JSON format
[["fahad","[email protected]","hello!","2018-02-13"],["chris","[email protected]","hello","2018-02-04"],["robert","[email protected]","hi there","2018-02-06"]]
Your array does not have keys thats why, print(obj[1][1])
How to get keys for each values?
is there any way to make it associative array?
|

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.