0

I'm trying to pass multiple input values through Ajax jquery but for some unknown reason, it is not working.

For example

<input type="text" class="form-control invoice_item_name" name="invoice_item_name">
<input type="text" class="form-control invoice_item_name" name="invoice_item_name">

jQuery and Ajax

    $('.invoice_item_name').each(function(){
        var invoice_item_name = $(this).val();
    });

    $.ajax({
        url: 'includes/some-php.php',
        type: 'POST',
        data: {invoice_item_name:invoice_item_name) {
            $('.error_message').html(add_invoice_result);
        }
    });

some-php.php file

$invoice_item_name = mysqli_real_escape_string($connection, $_POST['invoice_item_name']);

$insert_order_item = "insert into invoice_order_item(order_item_name) values('$invoice_item_name')";
        
$insert_order_item_query = mysqli_query($connection,$insert_order_item);

Can anyone tell me what am I doing wrong? and I wrapped the "INSERT INTO" query in "for loop". So each item_name stored in the new row.

Crezzur
  • 1,303
  • 2
  • 18
  • 37
shakky
  • 434
  • 5
  • 20
  • `var invoice_item_name = $(this).val();` simply overwrites the variable each time and will only hold the last value. – El_Vanja May 01 '21 at 10:27
  • Please note that the way you're writing your query is unsafe, as it's still open to SQL injection, because [escaping](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe enough. You should switch to [prepared statements](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) to prevent it. – El_Vanja May 01 '21 at 10:29
  • So what is the solution? By the way, it is also throwing this error "Maximum call stack size exceeded" @El_Vanja – shakky May 01 '21 at 11:02
  • Yeah, I know! This is just for practice! @El_Vanja – shakky May 01 '21 at 11:04
  • 1
    The solution would be to build an array. – El_Vanja May 01 '21 at 11:09
  • var invoice_item_name = new Array(); $('.invoice_item_name').each(function() { invoice_item_name.push($(this).val()); }); @El_Vanja – shakky May 01 '21 at 11:14
  • I think this would do the job! @El_Vanja – shakky May 01 '21 at 11:15
  • It should, yes. – El_Vanja May 01 '21 at 11:17
  • The issue has been resloved! Thank you @El_Vanja – shakky May 01 '21 at 11:33

1 Answers1

0

As @EL_vanja mentioned in the comment section that, var invoice_item_name = $(this).val(); simply overwrites the variable each time and will only hold the last value.

The solution was to build an array.

var invoice_item_name = new Array(); $('.invoice_item_name').each(function() { invoice_item_name.push($(this).val()); });

shakky
  • 434
  • 5
  • 20