user2180045
user2180045

Reputation: 15

Concatenate a string in ajax data call

My application has dynamically generated id's on the front end, which requires mapping back to the model in the backend. To do this I pass an index into the ajax call, which will then be used for mapping purposes in the backend, however javascript flags this as a syntax error for the data attribute in the ajax call.

function getStuff (stuffIndex,stuffType){
event.preventDefault();
        var stuffName = $('#stuffName'+ index).val();

        $.ajax({
            url : flowExecutionUrl,

            data : { 
                'stuff['+stuffIndex+'].name': stuffName,
                 ajaxSource:"StuffTypes_" + stuffIndex
            },
                success : function(html) {
         }
   });
}

The syntax error occurs on this line: 'stuff['+ 'stuffIndex'+ '].name': stuffName,

Upvotes: 1

Views: 5742

Answers (1)

softvar
softvar

Reputation: 18455

function getStuff (stuffIndex,stuffType){
event.preventDefault();

var stuffName = $('#stuffName'+ index).val(),
    data = {},
    dynamicData = 'stuff['+stuffIndex+'].name';
    data[dynamicData] = stuffName;
    data['ajaxSource'] = 'StuffTypes_' + stuffIndex;  

$.ajax({
            url : flowExecutionUrl,
            data : data,
            success : function(html) {
                alert('success');
            },
            error: function(){
                alert('failure');
            }
        });
}

Upvotes: 2

Related Questions