1

I receive a JSON-File via ajax and added it to my DOM (see: how to read information of an ajax-dialogbox)

Now i wanted to get access to this DOM-node, but the only way it worked was:

get_ajax_dialogwindow();
alert("wait for click");
alert("Test Combo" + combobox_by_name(value.ID_of_name));

this worked perfectly fine, but I don't want the user to click first. If I try only

get_ajax_dialogwindow();
alert("Test Combo" + combobox_by_name(value.ID_of_name));

I only get empty space where the data should be... I guess it's because the DOM isn't ready again. I tried $(document).ready, setTimeout, .delay(), ajax.stop, DOMContentReady but the only thing that worked was a simple alert("wait"); but i can't live with that solution because I don't want the user to click 20 times :P

any ideas?

Thank you! :)

Edit:

here is the code:

function combobox_by_name(ID_of_name){
  return $('select[name=audience\\[' + ID_of_name + '\\]\\[value\\]] option:selected').text();
}

and the ajax call I do right before the alert with the insert of the HTML-node:

function get_ajax_dialogwindow(){
var data = '__a=1&__d=1&__user='+get_userID();                              //Parameter für den Ajax Aufruf. Bestehend aus __a=1, __d=1 und der UserID
var json;
$.ajax({
    type:"GET",
    url: get_ajax_url(),                                                    //url für empfänger des Ajax Aufrufs. Lässt sich mit Firebug herausfinden, wenn man den link der das Dialogfenster öffnet analysiert
    data: data,
    dataType: "text",                                                       //eigentlich ist es json und kein text, allerdings gibt es einen Schutz von Facebook, 
                                                                            //der die Dauerschleife for(;;;) vorne heranschiebt. Deshalb wird es als Text betrachtet
    success: function(response) {           
        response = response.replace(/.*?;{/, "{");                          //Entfernt for(;;;)
        jsonFile = JSON.parse(response);                                    //Parsed den Text in ein Json file                   
        $('#globalContainer').append(jsonFile.payload.body.__html);         //Fügt das Dialogfenster ganz unten an die Seite hinzu
    },

    error: function(xhr) {                                                  //Fehlermeldung, falls der Ajax aufruf fehlschlägt
        alert('Error!  Status = ' + xhr.status);
        alert(xhr.responseText);
    }


});

}
Community
  • 1
  • 1
Weedjo
  • 335
  • 1
  • 6
  • 17

2 Answers2

1

Use a callback function.

function get_ajax_dialogwindow( CALLBACK ){
var data = '__a=1&__d=1&__user='+get_userID();                              //Parameter für den Ajax Aufruf. Bestehend aus __a=1, __d=1 und der UserID
var json;
$.ajax({
    type:"GET",
    url: get_ajax_url(),                                                    //url für empfänger des Ajax Aufrufs. Lässt sich mit Firebug herausfinden, wenn man den link der das Dialogfenster öffnet analysiert
    data: data,
    dataType: "text",                                                       //eigentlich ist es json und kein text, allerdings gibt es einen Schutz von Facebook, 
                                                                            //der die Dauerschleife for(;;;) vorne heranschiebt. Deshalb wird es als Text betrachtet
    success: function(response) {           
        response = response.replace(/.*?;{/, "{");                          //Entfernt for(;;;)
        jsonFile = JSON.parse(response);                                    //Parsed den Text in ein Json file                   
        $('#globalContainer').append(jsonFile.payload.body.__html);         //Fügt das Dialogfenster ganz unten an die Seite hinzu
        if ( CALLBACK ) CALLBACK();
    },

    error: function(xhr) {                                                  //Fehlermeldung, falls der Ajax aufruf fehlschlägt
        alert('Error!  Status = ' + xhr.status);
        alert(xhr.responseText);
    }


});

}

Then:

get_ajax_dialogwindow(function(){
   alert("Test Combo" + combobox_by_name(value.ID_of_name));
});
BGerrissen
  • 21,250
  • 3
  • 39
  • 40
  • This is working. It ruins my architecture but it worked. thanks :) – Weedjo Oct 13 '11 at 15:05
  • 1
    You should incorporate callbacks into your architecture, it's a powerful pattern and mandatory for asynchronous programming. Other patterns to solve async problems are less clean and more ambiguous. Yes, you can end up in callback hell when coding callbacks indiscriminatly, just be smart about it, I'm sure you will manage ;) – BGerrissen Oct 14 '11 at 08:40
0

I am pretty sure it's because of the asynchronous ajax call. You are trying to access a variable which has not yet been set.

If you put an alert before the actual access, it takes some time to click the ok button, so the call is being completed. When the code goes to the next line it works as expected because the value is set.

You shuld set your variable / do something with it in your coallback function. Since you didn't post any of your actual code, I'll improvise:

var yourVar;
$.get("someurl", params, function (data) {
  yourVar = data; // Let's say that you set it right here
  alert(yourVar); // will work perfectly
});
alert(yourVar); // Possibly won't work because it will most likely be called before the get is completed

EDIT: I finished writing this answer before you posted your code. It appears this is the case but I'll look into it more deeply to confirm.

success: function(response) {           
    response = response.replace(/.*?;{/, "{");                          //Entfernt for(;;;)
    jsonFile = JSON.parse(response);                                    //Parsed den Text in ein Json file                   
    $('#globalContainer').append(jsonFile.payload.body.__html);         //Fügt das Dialogfenster ganz unten an die Seite hinzu
    // Here it should work
    alert("Test Combo" + combobox_by_name(value.ID_of_name));
},

You can also look into getJSON method since it's a shorthand I think you'll find useful in your case. It returns actual JSON data so you don't need to do any black-magic parsing.

Przemek
  • 6,300
  • 12
  • 44
  • 61
  • this isn't working either. And I would like to have it in another function like I have right now – Weedjo Oct 10 '11 at 13:07
  • You can have it in another function or whatever you wish. You just have to make sure you are trying to access the element after the ajax call has been completed. – Przemek Oct 10 '11 at 13:09
  • Since it does not work, which I find really unlikely, do you use firebug? If so, when you substitute `alert()` for `console.log()`, what results does it produce? – Przemek Oct 10 '11 at 13:15
  • `console.log()` works the same way. If I put an `alert("wait")` in front of it, then it works without any problems. if I just use `console.log()` I only get empty space... – Weedjo Oct 10 '11 at 13:23