2

Using this function

  function readPinMode(callback,pin){
     $.ajax({
        type: 'GET',
        url: path,
        data: {
        'funct': "readPinMode", //function included and working ou of loops
        'pin': pin,
        'php': 0
     },
     success: function (result) {
        //console.log(result);
        callback(result);
     },
        error: function (xhr, textStatus, error) {
        console.log(xhr);
        console.log(textStatus);
        console.log(error);
    }
   });
 };

in this way, simply does not do nothing:

      $( document ).ready(function() {
  <?php
  $js_array = json_encode($GLOBALS['gpio']); // got from included file, working
  echo "var pins = ". $js_array . ";\n";
  ?>
  console.log( "Document ready." );
  for (i = 0; i < pins.length; i++) {
        var mode = "m" + pins[i];
        function initMode(){
        readPinMode(function(ret){
        console.log(ret);
        $(mode).text(ret);
        console.log(mode);
      }, pins[i]);
    };
  }

It enters the for loop (I can log in console mode and pins[i], they are working) but the function seems to not be called. Console does not show anything.

Is there a way to solve this? Thanks

7
  • Never ajax in a loop. Commented Feb 25, 2016 at 11:59
  • ret is the result of the ajax success methos Commented Feb 25, 2016 at 12:02
  • 2
    what is function initMode() doing there ?? you are just defining a function. and not executing it.. as it has the logic to call AJAX and receive the results Commented Feb 25, 2016 at 12:03
  • First of all, add var before i. And you don't need that function initMode() {}, it just declares function inside of loop and nothing happens. Commented Feb 25, 2016 at 12:07
  • what is mode suppose to be? is it an HTML element ID? and what are pins exactly? Commented Feb 25, 2016 at 12:29

3 Answers 3

3

I suggest to not use a real loop which needs a proper closure, but instead run again in the success

<?php
  $js_array = json_encode($GLOBALS['gpio']); // got from included file,  working
  echo "var pins = ". $js_array . ";\n";
?>
var cnt = 0;
function readPinMode(){
  if (cnt>=pins.length) return;      
  $.ajax({
    type: 'GET',
    url: path,
    data: {
    'funct': "readPinMode", //function included and working ou of loops
    'pin': pins[cnt],
    'php': 0
   },
   success: function (result) {
      //console.log(result);
      $("#mode").append(result)
      cnt++;
      readPinMode();
   },
   error: function (xhr, textStatus, error) {
    console.log(xhr);
    console.log(textStatus);
    console.log(error);
   }
 });
}
$(function() { readPinMode(); }); 

Proof of concept:

var pins = ["pin1", "pin2", "pin3"];
var cnt = 0;

function readPinMode() {
  if (cnt >= pins.length) return;

  document.write('<br/>pin:' + pins[cnt]); // your Ajax

  cnt++;
  readPinMode();
}
$(function() {
  readPinMode();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

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

6 Comments

Show me how much you like it ;)
Nice approach, but this works only for first element!
I like it so much that did +1 :)
@Ghesio - I need more detail as to how it only worked for the first element. Did the script stop? was there console messages? how does the rendering of the pins array look? Please see the proof of concepts. I had a typo in the pin/pins
@mplungjan The script got executed, the array is fine. It logs only the first element of array (console.log(result); from ajax) and no other errors in console.
|
1

There's nothing wrong with using callback functions, however you did miss a couple of things. You are forgetting to call your initMode function and mode should be an ID like you mentioned:

<script>
    function readPinMode(callback, pin) {
        $.ajax({
            type: 'GET',
            url: 'SGWEB/header.php',
            data: {
                'funct': "readPinMode", //function included and working ou of loops
                'pin': pin,
                'php': 0
            },
            success: function (result) {
                callback(result);
            },
            error: function (xhr, textStatus, error) {
                console.log(error);
            }
        });
    }

    function initMode(mode, pin) {
        readPinMode(function (ret) {
            $(mode).text(ret);
        }, pin);
    }

    $(document).ready(function () {
        var pins = <?= json_encode($GLOBALS['gpio']) ?>;
        for (i = 0; i < pins.length; i++) {
            var mode = "#m" + pins[i];
            initMode(mode, pins[i]);
        }
    });
</script>

Here's a FIDDLE I created so that you can see how it works.

1 Comment

Now it has a proper closure. +1
0

I think its syntax error, Try this code

console.log( "Document ready." );
  for (i = 0; i < pins.length; i++) {
        var mode = "m" + pins[i];       
        readPinMode(function(ret){
        console.log(ret);
        $(mode).text(ret);
        console.log(mode);
      }, pins[i]);       
  }

I removed the function initMode() as it creates same function definition over and over again which overrides the exiting function, and its all messy. You should not define a function inisde a loop as the final function will be of the last loop. Also there is no need for you to define the function inside a loop in this scenario.

Here is a Working Prototype Fiddle

4 Comments

Tried this code, it only works for last iteration of for
what do you get in console??
I get only the last console.log(result); from for loop
@Ghesio The code is working 100% as expected.. it is looping correctly and the console has the output for all the loops.. check this fiddle. jsfiddle.net/RajReddy/u4fvw7Lg

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.