IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

jQuery Discussion :

Peupler un array avec divers appels Ajax : problème de synchronicité


Sujet :

jQuery

  1. #1
    Nouveau membre du Club
    Homme Profil pro
    Architecte sys d'info géographique
    Inscrit en
    Juin 2011
    Messages
    64
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : Architecte sys d'info géographique
    Secteur : Transports

    Informations forums :
    Inscription : Juin 2011
    Messages : 64
    Points : 30
    Points
    30
    Par défaut Peupler un array avec divers appels Ajax : problème de synchronicité
    Bonjour,

    le code suivant récupère 3 arrays mais on dirait qu'il n'a pas le temps d'attendre qu'un des array soit fini pour continuer. au niveau de [I] photosB.arraycomments.push({ dans le code suivant, j'ai l'erreur :

    Uncaught TypeError: photosB[i] is undefined
    Je ne maîtrise pas du tout ni ne comprends les questions d'attente, de synchronicité (async, await) alors j'avais crée pour un array photosBbis, qui avait fonctionné tant que je les fusionnais, beaucoup plus tard.

    Ici, j'ai voulu inserer dans photosB je resultat de mes commentaires, mais ca ne marche pas. J'essaye d'éviter de créer un photosBter.

    Je voudrais que le resultat des commentaires (read_photocomments, appelé par ajax) entre bien dans l'array photosB.

    J'aimerai pour ça utiliser des await et async pour peut etre que l'array photosB soit rempli une fois que j'ai le resultat de l'appel ajax vers read_photocomments.


    J'essaye de ne pas vous envoyer un 'wall of code'. Vous avez 3 appels ajax dans cette fonction.

    merci d'avance


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
     
        $.ajax({
            url: 'https://website/imagesInCat_ajax.php?catID=' + catconfirm + '&minLat=' + SWlat + '&maxLat=' + NElat + '&minLng=' + SWlng + '&maxLng=' + NElng,
            type: 'post',
            dataType: 'json',
            success: function(response) {
     
                $("#slider").empty();
                photosB = [];
                photosBbis = [];
     
                var i;
     
                for (i = 0; i < response.length; i++) {
                    console.log(i);
                    photounit = response[i];
                    var url = photounit.imgurl;
     
                    //  var url = 'https://website/subsite/picture.php?/' + photounit.imgurl;
                    let split = url.split('/');
                    let imageid = photounit.id;
                    if (photounit) {
     
                        $.ajax({
                            url: 'https://website/subsite/ws.php?format=json&method=pwg.images.getInfo&recursive=true&image_id=' + imageid,
                            type: 'post',
                            dataType: 'json',
                            success: function(response) {
     
     
                                photosBbis.push({
                                    id: imageid,
                                    cats: response.result.categories[0].uppercats,
                                    date: response.result.date_available
     
                                });
                            }
                        });
     
     
                        photosB.push({
                            id: imageid,
                            lat: photounit.latitude,
                            lng: photounit.longitude,
                            url: url,
                            //    photo: photounit.linkurl,
     
                            photo: photounit.linkurl.replace("sq", "sq"),
                            caption: photounit.name,
                            comment: photounit.comment,
                            author: photounit.author,
                            thumbnail: photounit.linkurl.replace("sq", "2s"),
                            arraycomments: [],
                            // cat: cats2
                        });
     
                        var arraycomments = [];
     
                        $.ajax({
                            url: "../callfiles/services/read_photocomments.php",
                            method: "GET",
                            dataType: "json",
                            data: {
                                image_id: imageid
     
                                  },                        xhrFields: {
                                withCredentials: true
                            },
                            success: function(response) {
                                console.log(response);
     
     
                                for (let r = 0; r < response.length; r++) {
                                    photosB[i].arraycomments.push({        
                                       content: response[r][0],
                                       author: response[r][1],
     
                                });
     
     
                                }
     
                            },
                            error: function (response) {
                                console.log(response);
                                arraycomments = response;
                                console.log('comments error')
                              },
                            username: null,
                            password: null
                        });
     
                    }
                };

  2. #2
    Futur Membre du Club Avatar de langocha
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2024
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Santé

    Informations forums :
    Inscription : Avril 2024
    Messages : 3
    Points : 6
    Points
    6
    Par défaut $.ajax().then()
    Bonsoir,

    Je vois qu'il y a une méthode "$.ajax().then()" qui est plus propre pour gérer les promesses au lieu de la propriété "success", je te conseil de l'utiliser. Tu auras plus d'infos à ce sujet sur le site jquery ... désolé je ne peux pas mettre le lien car le site m'empêche de valider mon message pour cause de ... spam

    Ensuite ton problème vient du fait que "tu n'attends pas" que tes infos concernant tes images soient arrivées pour les mettre à jour avec ta requête concernant les commentaires. Pour cela je te conseil la logique suivante:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    $.ajax('https://website/imagesInCat_ajax.php?catID=...')
        .then(data => {
            // data = infos images 1
            return $.ajax('https://website/subsite/ws.php?format=...');
        })
        .then(data => {
            // data = infos images 2
            return $.ajax('../callfiles/services/read_photocomments.php');
        })
        .then(data => {
            //  data = infos commentaires
        });
    Ainsi les requêtes s'enchaîneront les unes après les autres, en attendant à chaque fois le résultat de la précédente.

  3. #3
    Nouveau membre du Club
    Homme Profil pro
    Architecte sys d'info géographique
    Inscrit en
    Juin 2011
    Messages
    64
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : Architecte sys d'info géographique
    Secteur : Transports

    Informations forums :
    Inscription : Juin 2011
    Messages : 64
    Points : 30
    Points
    30
    Par défaut
    Bonjour langocha,

    merci beaucoup de ton conseil.

    J'essaye d'adapter à mon cas, et je te dirai si ça à marché...

  4. #4
    Nouveau membre du Club
    Homme Profil pro
    Architecte sys d'info géographique
    Inscrit en
    Juin 2011
    Messages
    64
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : Architecte sys d'info géographique
    Secteur : Transports

    Informations forums :
    Inscription : Juin 2011
    Messages : 64
    Points : 30
    Points
    30
    Par défaut
    Voilà, j'ai utilisé les then.

    mais j'ai ca comme erreur pour la ligne 107 de ce code :

    Uncaught TypeError: transferdata[ip] is undefined
    je pensais mais je ne maitrise pas ces boucles liées à des éléments d'array... pour recuperer ce chiffre et reinjecter des données dans un array

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
        // bloc b : appel principal des photos.
     
        $.ajax({
            url: 'https://website/images/imagesInCat_ajax.php?catID=' + catconfirm + '&minLat=' + SWlat + '&maxLat=' + NElat + '&minLng=' + SWlng + '&maxLng=' + NElng,
            type: 'post',
            dataType: 'json',
            success: function(response) {
     
                $("#slider").empty();
                photosB = [];
                photosBbis = [];
                photosBter = [];
     
                var ik;
     
                for (ik = 0; ik < response.length; ik++) {
                    console.log(ik);
                    photounit = response[ik];
                    var url = photounit.imgurl;
                    var pauthor; var pcontent;
     
                    //  var url = 'https://website/images/picture.php?/' + photounit.imgurl;
                    let split = url.split('/');
                    let imageid = photounit.id;
                    if (photounit) {
     
     
                        $.ajax({
                            url: 'https://website/images/ws.php?format=json&method=pwg.images.getInfo&recursive=true&image_id=' + imageid,
                            type: 'post',
                            dataType: 'json',
                            success: function(response) {
     
     
                                photosBbis.push({
                                    id: imageid,
                                    cats: response.result.categories[0].uppercats,
                                    date: response.result.date_available,
     
                                });
                            }
                        });
     
                        photosB.push({
                            id: imageid,
                            lat: photounit.latitude,
                            lng: photounit.longitude,
                            url: url,
                            comm: [],
                            //    photo: photounit.linkurl,
     
                            photo: photounit.linkurl.replace("sq", "sq"),
                            caption: photounit.name,
                            comment: photounit.comment,
                            author: photounit.author,
                            thumbnail: photounit.linkurl.replace("sq", "2s"),
                            // cat: cats2
                        });               }
                };
     
     
     
            },
     
            error: function(response) {
     
            },
     
        }).then(data => {
            // data = infos images 1
     
     
    console.log(data);
    transferdata = data;
     
    for (ip = 0; ip < transferdata.length; ip++) {
     
     
    $.ajax({
        url: "../services/read_photocomments.php",
        method: "GET",
        dataType: "json",
        data: {
            image_id: transferdata[ip].id
     
              },                        xhrFields: {
            withCredentials: true
        },
        success: function(response) {
            console.log(response);
     
            console.log(i);
            var commentspw = "";
     
            for (let r = 0; r < response.length; r++) {
     
                console.log(response[r][1]);
     
                console.log(response[r][0]);
                commentspw = commentspw + response[r][1] + '-_-_-' + response[r][0] + '/_/_'
     
     
            }
     
            photosBter.push({
                comma: commentspw,
                ident: transferdata[ip].id,   // Erreur ICI
            });
        },
     
     
        error: function (response) {
            console.log(response);
            arraycomments = response;
            console.log('comments error')
          },
        username: null,
        password: null
    }).then(data => {
     
           // photosBter.push(commentspw);
     
     
           result = photosB.map(obj => {
            let data = photosBbis.find(item => item.id === obj.id);
            return {
                ...obj,
                ...data
            }
        });
     
        function shuffle(array) {
            let currentIndex = array.length,
                randomIndex;
            while (currentIndex != 0) {
                randomIndex = Math.floor(Math.random() * currentIndex);
                currentIndex--;
                [array[currentIndex], array[randomIndex]] = [
                    array[randomIndex], array[currentIndex]
                ];
            }
            return array;
        };
     
        const photosBmerge = {};
        for (let elem in photosB) {
            let hasBis = Object.values(photosBbis).filter(bis => bis.id == photosB[elem].id)[0];
            if (hasBis) {
                photosBmerge[elem] = {};
                Object.assign(photosBmerge[elem], photosB[elem], hasBis);
            }
        };
     
        sorted_photosB = photosB.sort(function(a, b) {
            return a.id - b.id;
        });
     
        sorted_photosBbis = photosBbis.sort(function(a, b) {
            return a.id - b.id;
        });
     
     
        for (var i = 0; i < photosB.length; i++) {
            mergedB.push({
                lat: sorted_photosB[i].lat,
            });
        };
     
     
        setTimeout(() => {
            buildHtml();
        }, "1000");
     
     
        })

Discussions similaires

  1. Imprimer le résultat d'un appel Ajax avec jQuery
    Par redah75 dans le forum jQuery
    Réponses: 5
    Dernier message: 14/05/2012, 09h03
  2. Appel Ajax avec jQuery : $.ajax is not a function
    Par Grulf dans le forum jQuery
    Réponses: 2
    Dernier message: 18/02/2011, 11h47
  3. [AJAX] Appel Ajax dans un appel Ajax avec JS et PHP
    Par Gajilidd dans le forum AJAX
    Réponses: 10
    Dernier message: 27/08/2010, 12h36
  4. 2 appels $.ajax avec jQuery
    Par Sam457 dans le forum jQuery
    Réponses: 4
    Dernier message: 26/11/2009, 23h25
  5. [DOM] Utilisation d'une bibliothèque de tri avec appel AJAX
    Par GreatDeveloperOnizuka dans le forum Général JavaScript
    Réponses: 4
    Dernier message: 08/02/2008, 11h09

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo