0

I am trying to pass array through ajax request

<input type="text" name="item_name[]">
<input type="text" name="address">

 $(document).on('click', '#save_info', function () {
        var address = $("#address").val();
        var item_name = $("[name^='item_name']");

       $.ajax({
            url: '/save_information',
            dataType: "json",
            type: 'POST',
            data: {
                _token: '{{ csrf_token() }}',
                address: address,
                item_name: item_name,
          }
        });
    });

In my controller

    $item_name = $request->item_name;
    $array_count = count($item_name);

It makes error. How can i save array value using loop. Thanks in advance

1
  • Use $("[name^='item_name']").val() instead of just $("[name^='item_name']") Commented Nov 1, 2019 at 19:09

2 Answers 2

1

@Mujahidur Rahman Mithun IUB you can write this more shortly by using serializeArray.

    $(document).on('click', '#save_info', function () {
      var serializeData = $("[name^='item_name']").serializeArray();
      serializeData.push(
        {
          name: "address", value: $("#address").val()
        },
        {
          name: "_token", value: '{{ csrf_token() }}'
        },
      );
      $.ajax({
        url: '/save_information',
        dataType: "json",
        type: 'POST',
        data: serializeData
      });
    });

Or if you use <form>, then you can use with very few line code :

  $(document).on('click', '#save_info', function () {
      $.ajax({
        url: '/save_information',
        dataType: "json",
        type: 'POST',
        data: $('form#myform').serialize(),
      });
    });
`
Sign up to request clarification or add additional context in comments.

Comments

0

The variable item_name holds DOM Node instead of input values. You'd have to make it either var item_name = $("[name^='item_name']").val() or var item_name = $("[name^='item_name']").value

4 Comments

Thanks for your feedback but still it says count(): Parameter must be an array or an object that implements Countable
@MujahidurRahmanMithunIUB Do you have multiple inputs that match this [name^='item_name'] selector ? If not, you can simply use var item_name = [$("[name^='item_name']").val()];
var item_name = [$("[name^='item_name']").val()]; I used this but it contains only one value. 1st value
@MujahidurRahmanMithunIUB That is why I've asked if you have multiple elements that match the selector because the solution will be different in that case, you'll have to use something like var item_name = $("[name^='item_name']").map(function() { return $(this).val() }).get()

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.