0

How is an array done from an each loop and then pass it on in a post with ajax? Now it is just making one array for each element, and doesn't post anything to the ajax.

$('a#export').on('click',function(){

    $('[id^="imgHolder"], [id^="textHolder"]').each(function(){

        TextElementID = $(this,'[id^="textHolder"]').attr('id');
        TextElementContent = $(this,'[id^="textHolder"]').text();   

    TextObjects = new Array(TextElementID, TextElementContent);   

        ImgSrc = $('img',this,'[id^="imgHolder"]').attr('src');
        ImgHolderID = $(this,'[id^="imgHolder"]').attr('id');
        ImgHolderClass = $(this,'[id^="imgHolder"]').attr('class');            

    ImgObjects = new Array(ImgHolderID, ImgHolderClass, ImgSrc);

        });

        $.ajax({
            url: "post.php",
            type: "post",
            data: { 
                ExportObjects: ImgObjects
            },
            success: function(){
               alert("success");
            },
            error: function(){
                alert("failure");
            }   
              });

    });

1 Answer 1

1

There are a couple of problems with this. You are initializing the array in the each and will end up overwriting the values. Also you are doing an each on the text and images are are collecting the values of both text and images in the loop and will end up with duplicates. Here's a working version of the fiddle.

var ImgObjects = new Array();
$('[id^="imgHolder"]').each(function(){
    ImgSrc = $('img',this,'[id^="imgHolder"]').attr('src');
    ImgHolderID = $(this,'[id^="imgHolder"]').attr('id');
    ImgHolderClass = $(this,'[id^="imgHolder"]').attr('class');            
ImgObjects.push(ImgHolderID, ImgHolderClass, ImgSrc);
    });

var TextObjects = new Array();
$('[id^="textHolder"]').each(function(){
    TextElementID = $(this,'[id^="textHolder"]').attr('id');
    TextElementContent = $(this,'[id^="textHolder"]').text();   
    TextObjects.push(TextElementID); 
    TextObjects.push(TextElementContent);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Worked exactly as I would hope!! + for you!

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.