Debug School

rakesh kumar
rakesh kumar

Posted on

Json and Javascript :How to display Api data in li tag using for loop

js_arrays

My Api data

  var address = response.success;
console.log('repsonse me kya aa rha hai' + response.success);
amit lodha,amitabh bachchan,amit shah,amity university,amitabh bachchan age,amity university ranchi,amit jain,amity university noida
Enter fullscreen mode Exit fullscreen mode

Requirement

Image description

Solution

<script type="text/javascript">
        $(document).ready(function(e) {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $('#google_keyword').submit(function(e) {
                e.preventDefault();
                var formData = new FormData(this);
                $.ajax({
                    type: 'POST',
                    url: "{{ route('google_keyword') }}",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(response) {
                        console.log('repsonse me kya aa rha hai' + response.success);
                        var address = response.success;
                        var myJSON = JSON.stringify(address);
                        console.log('my json me kya aa rha hai' + myJSON);
                        var separatedArray = myJSON.split(', ');
                        var myStringArray = response.success;
                        const amits = myStringArray;
                        let fLen = amits.length;
                        console.log('length me kya aa rha hai' + fLen);
                        let text = "<ul>";
                        for (let i = 0; i < fLen; i++) {
                            text += "<li>" + amits[i] + "</li>";
                            // text += "<li>" + amits[i] + "</li>";
                        }
                        text += "</ul>";
                        document.getElementById("demo").innerHTML = text;
                    },
                    error: function(data) {}
                });
            });
        });
    </script>
Enter fullscreen mode Exit fullscreen mode
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>The best way to loop through an array is using a standard for loop:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;

let text = "<ul>";
for (let i = 0; i < fLen; i++) {
  text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)