0

so this might be a repost, but I don't really know how to explain my second problem. I have this code:

var paragraphsArray = new Array();
function setParagraphs(offSet) 
{
    offSet = offSet * 12;
    for (var i = 1; i < 13; i++) 
    {
        var parX = i + offSet;
        var testASd = $.get('php/entryParagraphs.php', {idd: parX}).done(function(paragraph) 
        {
            //clear paragraph1 div 
            document.getElementById("paragraph1").innerHTML = "";
            //create p elements
            var pElem = document.createElement("p");
            pElem.setAttribute("id", "pEntry"+i);
            document.getElementById("paragraph1").appendChild(pElem);
            $("pEntry"+i).text(paragraph);
        });
    }
}

edited: I removed the second loop because it was unnecessary, for some reason the p element creation starts on i==13, which is the extra one that shouldn't even do.

for some reason the second loop executes first, so the paragraphArray is printed out as undefined. I managed to "fix" the order with the setTimeout() function, BUT I still get the undefined message, instead of the value. In the first loop the value is printed out fine, but if I try and put it in a $("p").text(paragraph); I also get undefined. So although I was right about the execution order, the problem is still there!

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
hahaha
  • 1,001
  • 1
  • 16
  • 32
  • 1
    This is because the first loop is sending out page requests, which are being run in parallel and take longer to complete than the rest of the Javascript. Once the `$.get` is called, the next line of Javascript code is executed as `$.get` goes out and retrieves the page. – Aiias May 04 '14 at 18:34
  • possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Bergi May 06 '14 at 10:49

3 Answers3

1

Because first is in ajax call, declare paragraphsArray in global space and use a callback function, try this:

*Updated

var paragraphsArray = [];
function setParagraphs(offSet) {
    offSet = offSet * 12;
    var request = 0;
    for (var i = 1; i < 13; i++) {
        var parX = i + offSet;
        var testASd = $.get('php/entryParagraphs.php', {idd: parX}).done(function(paragraph) {
            request++;
            paragraphsArray[request] = paragraph;
            console.log(paragraphsArray[request]);
            if (request === 12) {
                alert('first');
                callback();
            }
        });
    }
}
function callback() {
    for (var i = 1; i < 13; i++) {
        console.log(paragraphsArray[i]);
    }
    alert('second');
}
Manoj Yadav
  • 6,560
  • 1
  • 23
  • 21
  • for some reason, even though it i reaches 12 the callback function is not runned/called, is it because of the triple =?? – hahaha May 04 '14 at 19:18
  • even if it runs, for some reason the second loop returns undefined as well. its like the problem with my `settimeout()` solution – hahaha May 04 '14 at 19:28
  • works as promised with an explanation as to what caused the problem – hahaha May 04 '14 at 19:58
  • one minor problem I face here is that because (am guessing) of the delay in $.get() paragraphsArray[x] might not be the 4th item in the database but the 1st or 8th or any. is there a way to fix this? – hahaha May 05 '14 at 06:35
  • return the `id` and `paragraph` as `object data` from server, something like `paragraphsArray[data.id] = data.paragraph;` – Manoj Yadav May 05 '14 at 06:38
  • just to be sure, in the php side it would be something like class `User{public $uid; public $uPara;}` and i would `echo user($id,$para)` and in javascript i would still put it in paragraphsArray and say `paragraph.id` and `paragraph.para`?? – hahaha May 05 '14 at 06:45
  • Replace `var testASd = $.get('php/entryParagraphs.php', {idd: parX}).done(function(paragraph) {` with `var testASd = $.getJSON('php/entryParagraphs.php', {idd: parX}).done(function(data) {` and in php side you have to do someting like `header('Content-type: application/json'); echo json_encode(array('id' => 1, 'paragraph' => 'some text'));` – Manoj Yadav May 05 '14 at 06:52
0

$.get is async function. 1st cycle will just send requests and wouldn't wait for response, so 2nd cycle will start right after first, without getting response of $.get function. Thats why console.log(paragraphsArray[i]); in 2nd cycle shows undefined.

You only can handle response in first cylce.

You can use $("p").text(paragraph); only like in this example:

var testASd = $.get('php/entryParagraphs.php',  { idd: parX }).done(function(paragraph) {
    paragraphsArray[i] = paragraph;

    console.log(paragraphsArray[i]);
    alert('first');

    $("p").text(paragraph);
});

You can't use variables, which are assigned in function

function(paragraph) {
    paragraphsArray[i] = paragraph;

    console.log(paragraphsArray[i]);
    alert('first');

    $("p").text(paragraph);
}

outside of this function.

To achieve what you want you have to use another approach.

HTML will be:

<div id='paragraphs'>
</div>

JS code:

var testASd = $.get('php/entryParagraphs.php',  { idd: parX }).done(function(paragraph) {
    $("#results").append("<p>"+paragraph+"</p>")
});

You should use ~ this code. I just show you approach.

Sharikov Vladislav
  • 7,049
  • 9
  • 50
  • 87
  • I tried to use the paragraph in the first loop, because the second loop is completely unnecessary, it was a try to overcome the first problem, which is: i can print in the console, and in the alert() msg, but i cant use the value for the purpose i want to, i want to put the paragraph value in a `$("p").text(paragraph);` which didnt work, it assigned the value as undefined. – hahaha May 04 '14 at 19:31
  • @alexandros Where exactly you tried this? You can do this in first cycle. You can't do this outside of `$.get` function. – Sharikov Vladislav May 04 '14 at 19:34
  • `var paragraphsArray = new Array(); function setParagraphs(offSet) { offSet = offSet * 12; for (var i = 1; i < 13; i++) { var parX = i + offSet; var testASd = $.get('php/entryParagraphs.php', {idd: parX}).done(function(paragraph) { //clear paragraph1 div document.getElementById("paragraph1").innerHTML = ""; //create p elements var pElem = document.createElement("p"); pElem.setAttribute("id", "pEntry"+i); document.getElementById("paragraph1").appendChild(pElem); $("pEntry"+i).text('teest'); }); } }` – hahaha May 04 '14 at 19:36
  • am sorry i couldnt type my code and my msg, i removed the 2nd loop completely, because its unnececary and now its like this, the problem is that it goes immidietely to i==13, and skips everything else, because it generates only one p element, with the id of pEntry13 – hahaha May 04 '14 at 19:37
  • @alexandros You just had shown us how to not use comments in so. Updated your question. It is impossible to read code now. – Sharikov Vladislav May 04 '14 at 19:38
  • done,am sorry i thought comments would use a similar output to the question's format – hahaha May 04 '14 at 19:42
  • yes thats what i did in the first place, but for some reason, the p text area is still empty, and it also creates only 1 p element, instead of 12. the second loop was a workaround with the array but that too, didnt work – hahaha May 04 '14 at 19:46
0

Run the second loop inside of the first loop.

function setParagraphs (offSet) {
    //paragraphs
    var testing = 0;
    var paragraphsArray = new Array();
    offSet = offSet * 12;
    for (var i=1;i<13;i++) {
        var parX = i + offSet;
        var testASd = $.get('php/entryParagraphs.php',  { idd: parX }).done(function(paragraph) {
            paragraphsArray[i] = paragraph;
            console.log(paragraphsArray[i]);
            alert('first');
            for (var i=1;i<13;i++) {
                 console.log(paragraphsArray[i]);
                 alert('second');
             }
        });
    }
}
Misbah Khan
  • 372
  • 2
  • 3
  • 12