0

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
                });
            });
        });
Djester808
  • 25
  • 4
  • 1
    Have you tried `console.log(id, title, img_url)` inside your loop to ensure the loop is working properly and retrieving the correct arguments to pass to the PHP script? Have you confirmed the PHP script is working and properly parsing its arguments? – kmoser Apr 03 '22 at 03:09
  • I have confirmed that the loop is working properly using alert(). The PHP script works as well. – Djester808 Apr 03 '22 at 03:12
  • You use `.load()` inside `.each()` that means any URL loaded using ajax `.load()` will be overwrite contents into `#elementToLoadPhpFile` element. [See the document](https://api.jquery.com/load/). To append, I recommend to use something else such as [`.insertAdjacentHTML()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML) – vee Apr 03 '22 at 03:24
  • jQuery's `.load()` function is asynchronous by nature, meaning the different calls you're making will finish in an indeterminate order. Does this answer your question? [jQuery .load(function) synchronous](https://stackoverflow.com/questions/15975331/jquery-loadfunction-synchronous) – kmoser Apr 03 '22 at 03:25
  • @vee You're right, but that's not the problem. OP was complaining about the sequence, i.e. the first element loaded but was not overwritten by the 2nd or 3rd. – kmoser Apr 03 '22 at 03:27
  • @kmoser after some more testing, I updated my question in the post. It seems that the .load() is overwriting the previous php file that is loaded in there while looping. – Djester808 Apr 03 '22 at 03:31
  • @kmoser I see that OP said _I need it to append multiple children_. So, I think replace `.load()` with something else should work. Or maybe I'm wrong. – vee Apr 03 '22 at 03:31
  • @vee does .insertAdjacentHTIM() allow me to add a PHP script? – Djester808 Apr 03 '22 at 03:32
  • @Djester808 `.insertAdjacentHTML('beforeend', '

    your HTML here.

    ');` work the same as jQuery `.append('

    your HTML here.

    ');`.
    – vee Apr 03 '22 at 03:33
  • @Djester808 `.insertAdjacentHTML()` adds whatever contents was returned by the server. It doesn't matter whether that contents was generated by PHP. – kmoser Apr 03 '22 at 03:34
  • 1
    @vee Given OP's clarification about appending multiple children, you are correct: `.load()` will replace, which will not work. – kmoser Apr 03 '22 at 03:36

1 Answers1

1

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.

Twisty
  • 30,304
  • 2
  • 26
  • 45
  • I believe the asynchronous nature of `.get()` will cause the three callbacks to be executed in an indeterminate sequence. If you want them to happen in sequence you'll need to nest them (which leads to [Callback Hell](http://callbackhell.com/)). Also see [How to make Javascript fetch synchronous?](https://stackoverflow.com/questions/44735669/how-to-make-javascript-fetch-synchronous) – kmoser Apr 03 '22 at 03:33