0

Hi i have a jquery script to load the states on a svg map.

the map uses this var to get results

var mystates = ["NY","NJ"];

if i put the states manually works fine, but i m try to load this dinamically

i tried this

var url = "/php/actions.php";
    $.get(url,{
        Action: "107"
    },function(data){


    var mystates = data;
        //alert(mystates);
    });

the alert return the values correctly but then i cant pass the result.

i tried something like this

var url = "/php/actions.php";
        $.get(url,{
            Action: "107"
        },function(data){


        var mystates = data;
            //alert(mystates);
        });

var getstates = mystates;

dont works

the problem is after get tre result i need to pass here on last IF

xhr.onreadystatechange = function(){
            if ( xhr.readyState === 4 ){
                var data = JSON.parse(xhr.responseText);
                $.each(Object.keys(data), function(key, i) {
                    var estado = r.path(data[i].coordMap).attr(attr).data("capital", data[i].capital).data("nome", data[i].nome).data("sigla", data[i].sigla);
                    if (contains(mystates, estado.data("sigla"))){

thanks for any help.

/* COMPLETE JQUERY */

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

;(function($, w, d, u){

    function getMyData(callback) {
    var url = "/php/acoes.php";
    $.get(url,{
        Acao: "107"
    }, callback );
}

    getMyData(function(data) {
    var resultado = data; //array ok!  returns ["NY","NJ"]
    //alert(resultado);
    });




    var estadosAtivos = ["NY","NJ"];  // array manually i m try to load the array here


    /*var r = Raphael('maps', 550, 550),*/
    var r = new ScaleRaphael('maps', 550, 550),
        attr = {
            cursor: 'pointer',
            fill : '#0077b0',
            stroke: '#fff',
            'stroke-width': 2,
            'stroke-linejoin':'round'
        },
        xhr = new XMLHttpRequest();

        var estadoAtual;
        var anterior;
        xhr.onreadystatechange = function(){
            if ( xhr.readyState === 4 ){
                var data = JSON.parse(xhr.responseText);
                $.each(Object.keys(data), function(key, i) {
                    var estado = r.path(data[i].coordMap).attr(attr).data("capital", data[i].capital).data("nome", data[i].nome).data("sigla", data[i].sigla);
                    if (contains(estadosAtivos, estado.data("sigla"))){
                        estado.animate({
                            fill: '#ffda1f'
                        }, 150);
                        estado.click(function(){
                            this.animate({
                                fill: '#333'
                            }, 150);

                            if (anterior != null) {
                                anterior.animate({
                                    fill : '#ffda1f',
                                    stroke: '#fff',
                                    'stroke-width': 2,
                                    'stroke-linejoin':'round'
                                }, 150);
                            }

                            anterior = this;

                            if (document.getElementById(estadoAtual) != null)
                                document.getElementById(estadoAtual).style.display = 'none';

                            estadoAtual = this.data("sigla");

                            if (document.getElementById(estadoAtual) != null)
                                document.getElementById(estadoAtual).style.display = 'block';
                        }).mouseover(function(evt) {
                            var x = evt.pageX;
                            var y = evt.pageY;
                            $('#regiaoLegenda').html(this.data("nome")).css({
                                top: y,
                                left: x+20,
                                position: 'absolute',
                                display: 'block'
                            });

                            this.animate({
                                fill: '#333'
                            }, 150);
                        }).mouseout(function() {
                            $('#regiaoLegenda').css({
                                display: 'none'
                            });

                            if (estadoAtual != this.data("sigla")) {
                                this.animate({
                                    fill: '#ffda1f'
                                }, 150);
                            }
                        });
                    }
                });
            }
        };
        xhr.open("get", "/js/mapa/estados.json", false);
        xhr.send(null);
    /* resize do mapa */    
    r.changeSize(325, 327, true, false);            
}(jQuery, this, this.document));
Alvaro Louzada
  • 433
  • 1
  • 6
  • 23
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – m59 Jan 24 '14 at 20:19

2 Answers2

1

You're declaring the variable mystates inside the callback of your AJAX, meaning that variables scope is limited to that function.

AJAX is also asynchronous, so simply assigning the variable right after the call like you're trying won't work, that call will still be in progress. Use a callback function!

function getMyData(callback) {
    $.get(url,{
        Action: "107"
    }, callback );
}

And use this like:

getMyData(function(data) {
    console.log(data); //theres your array!
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

The issue is you have a locally scoped variable mystates. You would need to do this.

var url = "/php/actions.php";
var mystates;
$.get(url,{
    Action: "107"
},function(data){
    mystates = data;
});

This way the variable mystates is at the scope you need it.

Updated:

Okay after seeing the code it looks like you just need to string to 2 calls together.

var mystates;
function doXHRRequest()
{
    //xhr declaration and processing goes here
}
var url = "/php/actions.php";
$.get(url,{Action: "107"},
function(data){
    mystates = data;
    doXHRRequest();
});

Doing it this way will require the get to finish before the XHR request is processed. Hope this helps. You should be able to do that xhr request as a $.get(url,function(){}) jQuery based call instead of doing it the way you are, but you may have a necessity to do it the way you have it coded.

Spdermn02
  • 179
  • 4
  • This won't work because of the async task. The code will end before $.get finishes. – Paul Facklam Jan 24 '14 at 20:22
  • @PaulFacklam - true you would want to use a callback or a globally scoped variable and callback to handle it correctly. Thanks for catching that. – Spdermn02 Jan 24 '14 at 20:26
  • Hi @Spdermn02 your solution returns nothing.. any way thanks. – Alvaro Louzada Jan 24 '14 at 20:35
  • As mentioned by @PaulFacklam the issue is that the $.get is an asynchronous call so the script will keep running after the $.get is executed, and even though it will fill mystates with the data returned from the ajax call, your xhr.onreadystatechange function may have already fired and thus lost the opportunity to utilize the mystates variable after data is populated into it – Spdermn02 Jan 24 '14 at 21:00
  • 1
    @AlvaroLouzada - it may help if you could provide us with a more complete example of what you have coded. Going off of fractions of the code is harder to give valuable responses. – Spdermn02 Jan 24 '14 at 21:03
  • Hi @Spdermn02 i posted the complete javascript code, with comments.. thanks for any help. – Alvaro Louzada Jan 24 '14 at 21:10
  • Were you able to try this out? – Spdermn02 Feb 02 '14 at 02:03