2

I have the following script which works as expected , it retrieves an XML list and assigns some variables

$.ajax({
    type: "POST",
    url: "pgGeneral_login/validate.php",
    data: { user:user , pass:pass },
    dataType: "xml",
    success:loginval      });  

function loginval(data){
    console.log("Returned" )

    valid = $(data).find('valid').text();   
    name = $(data).find('name').text();     
    pass = $(data).find('pass').text();


    }; 

What I would like to do is instead of assigning a variable to each of the xml results (valid = $(data).find('valid').text() ) is loop through the list an assign the value to the tag name without writing a huge list of code , if it was php I would use something like

    foreach ($row as $k => $v)
            $$k = $v 

any help please ?

Mick
  • 2,840
  • 10
  • 45
  • 61

3 Answers3

3

This will directly update global variable list and is not recommended.

Here you go,

function loginval(data){
    console.log("Returned" )

    // valid = $(data).find('valid').text();   
    // name = $(data).find('name').text();     
    // pass = $(data).find('pass').text();

    $(data).children().each(function(){
        // Directly adding to the Global list
        window[this.tagName] = $(this).text();
    });

    console.log(valid);
    console.log(name);
} 
ATOzTOA
  • 34,814
  • 22
  • 96
  • 117
  • Thanks ! This works fine , it gives me all the variables I need to work with , but why do you not recommend it ? – Mick Feb 16 '13 at 16:47
  • @Mick Well, it is a variable we are talking about. Accessing it as a property of `window` is kinda odd, don't you think? Also, this always updates the global scope and will overwrite any global variables with the same name. – ATOzTOA Feb 16 '13 at 17:14
2

As an addendum to ATOzTOA's code, this will also allow you to dynamically add variables to the global scope (i.e. for use outside of your AJAX functionality). It uses the eval() function which is generally avoided in most JS development:

// Array of fields you want to traverse
var array = ['text', 'name', 'pass'];

// This is the data object you get from your AJAX function
var vals = {
    text: 'Hello',
    name: 'John',
    pass: 'Password'
};

// Loop through and assign your vars
for (var i = 0; i < array.length; ++i) {
    var key = array[i];
    eval('var ' + key + ' = "' + vals[key] + '"');
}

console.log(text);

Thought it was an interesting question, so this answer is purely to offer an alternative (if hypothetical) solution - I'd err on the side of caution if using this for production purposes.

Community
  • 1
  • 1
hohner
  • 11,498
  • 8
  • 49
  • 84
1

Thought its not quite what you could achieve with php, but I think it somewhat does what you want:

function loginval(data){
    console.log("Returned" )

    $dataList={};

    $(data).children().each(function(){
        $dataList[this.tagName]=$(this).text();
    });

    console.log($dataList )
}
luckystars
  • 1,704
  • 12
  • 12