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));
1

2 Answers 2

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!
});
Sign up to request clarification or add additional context in comments.

3 Comments

Passing a callback is the only option
@PaulFacklam -- Yup, saw that, edited the answer and added a possible solution
Hi @tymeJV i tried your solution but dont works. i dont know if i did something wrong on pass array to var mystates.
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.

7 Comments

This won't work because of the async task. The code will end before $.get finishes.
@PaulFacklam - true you would want to use a callback or a globally scoped variable and callback to handle it correctly. Thanks for catching that.
Hi @Spdermn02 your solution returns nothing.. any way thanks.
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
@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.
|

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.