Display php result in HTML using AJAX

I am trying to display the result of my php in different <div>-s. My plan is that I make a request in my php and display the result in JSON format. Due to the JSON format, my result may appear different <div>. How can I achieve this, for example, "name"can be displayed between tags <div>?

Example php result:

[
    {
        "id": 0,
        "name": "example1",
        "title": "example2"
    },
    {
        "id": 0,
        "name": "example1",
        "title": "example2"
    }
]

Attempt:

 <div class="result"></div>

 <script>
 $.ajax({
    type:'GET',
    url:'foo.php',
    data:'json',
    success: function(data){
            $('.result').html(data);
    }
});
</script>
+4
source share
3 answers

Hi, try to parse the returned data into a JSON object:

<div class="result"></div>

 <script>
 $.ajax({
    type:'GET',
    url:'foo.php',
    data:'json',
    success: function(data){

            // added JSON parse
            var jsonData = JSON.parse(data);

            // iterate through every object
            $.each(jsonData, function(index, element) {

                 // do what you want with each JSON object
                 $('.result').append('<div>' + element.name + '</div>');

            });                
    }
});
</script>

// PS code not verified. // Yours faithfully

+4
source

Do it as below: -

success: function(data){
    var newhtml = ''; //newly created string variable
    $.each(data, function(i, item) {//iterate over json data
        newhtml +='<div>'+ item.name +'</div>'; // get name and wrapped inside div and append it to newly created string variable
    });
    $('.result').html(newhtml); // put value of newly created div into result element
}
+2

:

for (var i = 0; i < res.length; i++) {
  var id = $("<div></div>").html(data[i].id);
  var name = $("<div></div>").html(data[i].name);
   var title = $("<div></div>").html(data[i].title);

  $('.result').append(id).append(name).append(title);
}
+1

Source: https://habr.com/ru/post/1679151/


All Articles