-2

Hi I'm having trouble on how can I send my array objects data from jsp to servlet,

var i = 1;
var a; 
$(document).ready(function(){

$('#add').click(function(){
    i++;
    $('#dynamic_field').append('<tr id="row'+i+'"><td><select name="txtProduct'+i+'" id="txtProduct'+i+'" class="form-control name_list" ><option value="">- Product -</option><%=obj.getProductOpt("")%></select></td><td><input type="text" name="txtQty'+i+'" id="txtQty'+i+'" class="form-control"/></td><td><input type="button" name="remove" value="X" id="'+i+'" class="btn btn-danger btn_remove"/> </td></tr>');
    var b = i - 1;
    $( "[id^="+b+"]" ).prop( "disabled", true );
    $( "[id^="+i+"]" ).prop( "disabled", false );
});
$(document).on('click', '.btn_remove', function(){
    i--;
    var button_id = $(this).attr("id");
    $('#row'+button_id+'').remove();
    var b = i;
    $( "[id^="+b+"]" ).prop( "disabled", false );
});

$('#addButton').click(function(){
    var data = [];
    var n = 0;
    var c = 0;
    for (a = 1; a <= i; a++) { 
        var txtProduct = document.getElementById("txtProduct"+a+"").value;
        var txtQty = document.getElementById("txtQty"+a+"").value;
        var val = {"pname": txtProduct, "qty": txtQty};
        data.push(val);

    }
    for(ii = 0; ii < a; ii++){
            var pname = [];
            var qty = [];
            pname[ii] = data[ii].pname;
            qty[ii] = data[ii].qty;
        }
});
});

The thing is I have put the values in the variable but my problem is I don't know how to send it to servlet via ajax or what, I tried watching tutorials about ajax but it does not make sense to me since they all have different approuches, I hope someone can help me, thanks

Marvs.M
  • 13
  • 7
  • Convert your data to send in [json](https://stackoverflow.com/questions/15009448/creating-a-json-dynamically-with-each-input-value-using-jquery) format and parse it at your [servlet](https://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax). – Swati Aug 06 '19 at 12:09

1 Answers1

0

It can done by using setAttributes in jsp: First you need to convert your array in the form of array list then execute the below code: request.getSession().setAttribute("Array List Name", Array List Name Object); ArrayList list=request.getParameter("Array List Name");

Arun Das
  • 63
  • 1
  • 4