1

I'm trying to build an array of data that will then be ajax using post to php - below is my code:

$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
    var profilePhotoArray = [];
    $('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
        var action = '';
        alert( this.id );

        if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
            alert('attractive...');
            action = 'attractive';
        }
        else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
            alert('delete...');
            action = 'delete';
        }else{
            alert('normal...');
            action = 'normal';
        }
        profilePhotoArray[this.id+'_'+this.id] = action;
    });

    alert(profilePhotoArray.length);

    for (i=0;i<profilePhotoArray.length;i++) {
        console.log("Key is "+i+" and Value is "+array[i]);
    }


    $.post('scripts/ajax/ajax_approval_functions.php', {
    'approvalProfilePhotos': '1',
    'approvalProfilePhotosData': profilePhotoArray},
    function(data) {
        alert(data);
    });
});

The if, else if, else section works fine as I can see the alerts.

When I try to alert the array length 'profilePhotoArray' it says 0 so I'm not populating the array correctly. Do I need to use .push()? I thought this format was ok?

Also do I need to do anything to the array before sending to php via ajax?

thankyou

** edit - I'm adding "profilePhotoArray[this.id+'_'+this.id] = action;" this.id twice just to prove this words as I will pass a second variable like this... am I better to use JSON for this?

3
  • An array should be indexed by integers but you are using a string (this.id+'_'+this.id). Commented Jul 9, 2013 at 4:13
  • I thought I could use this as an associate array... maybe I'm thinking to much like PHP... should I use an index and add the value as a JSON string instead? Commented Jul 9, 2013 at 4:22
  • DevZer0 below has the right explanation. If you just change profilePhotoArray to be an object literal (var profilePhotos = {};) you should be all set. Commented Jul 9, 2013 at 4:25

1 Answer 1

3

Javascript arrays use numerical index, therefore your storage is failing. Use a javascript Object to store string based keys.

var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";
Sign up to request clarification or add additional context in comments.

Comments

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.