Home > other >  JQuery loop load php template into HTML
JQuery loop load php template into HTML

Time:04-03

I have an API call that I'm using to get data. This data is an array of arrays and I need to loop through them. For each value, I want to 'load' a php template I created with those values. The very first loop works and displays properly, but after the initial value, it stops. I need all values to be looped through and displated.

Example of what is happening: [a, b, c] => JQuery loop => load => Only 'a' shows up.

EDIT - Every time load is called, it loads the script into 'elementToLoadPhpFile'. I noticed that it seems to be overwriting the previous values that are loaded there. I need it to append multiple children, not override the same child.

$.ajax({
            type: 'GET',
            dataType: "json",
            url: 'apiUrl.com'
        }).done(function(data) {
            var result = data['data'];
            jQuery.each(result, function(key, value) {
                var id = value['id'];
                var title = value['title'];
                var img_url = value['images']['jpg']['image_url']
                $("#elementToLoadPhpFile").load("phpFile.php", {
                    id: id,
                    title: title,
                    img_url: img_url
                });
            });
        });

CodePudding user response:

Consider the following.

jQuery(function($) {
  $.getJSON('apiUrl.com', function(response) {
    $.each(response.data, function(key, val) {
      $.get("phpFile.php", {
        id: val.id,
        title: val.title,
        img_url: val.images.jpg.image_url
      }, function(html) {
        $("#elementToLoadPhpFile").append(html);
      });
    });
  });
});

If .load() is working, but is replacing the content, as expected, then you may want to just GET the content so you can Append it. See here:

This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched elements to the returned data.

Objects are better written in dot notation.

  • Related