Push Array Value to Ajax [JQuery / PHP / HTML]

问题: I can't push the value of my array to my php file. Script: <script> $(document).ready(function() { var item_code = []; $('#save').click(function() { var...

问题:

I can't push the value of my array to my php file.

Script:

<script>
$(document).ready(function() {
  var item_code = [];

  $('#save').click(function() {
    var item_name = [];
    var item_value = [];
    var item_quantity = [];

    for (var i = 0; i < item_code.length; i++) {
      item_code.push($(this).val());
    }


    $('.item_name').each(function() {
      item_name.push($(this).val());
    });

    $('.item_value').each(function() {
      item_value.push($(this).val());
    });
    $('.item_quantity').each(function() {
      item_quantity.push($(this).val());
    });

    $.ajax({
      url: "insert2.php",
      method: "POST",
      data: {
        item_name: item_name,
        item_code: item_code,
        item_value: item_value,
        item_quantity: item_quantity,
      },
      success: function(data) {

      }

    });

</script>

I have a value storing at "item_code" whenever I search the item code on my search bar. And after that, I want to push the value of item_code[] on the insert2.php.

I'm not getting any error, but the system itself is frozen.


回答1:

I am guessing that "item_code" variable is also declared globally somewhere else in your code, otherwise there would be no point in iterating through it. Try using a different name instead of "item_code" to send it to "insert2.php".

   for (var i = 0; i < item_code.length; i++) {
      item_code.push($(this).val());
   }

You can't push data into the same array that you are looping because you will never reach the end of it, unless the memory limit will tell you otherwise. Declare "item_code_second" and push into that:

$(document).ready(function() {
  var item_code_second = [];

and change your loop:

   for (var i = 0; i < item_code.length; i++) {
      item_code_second.push($(this).val());
   }

also you are pushing the same value "$(this).val()" as many times as there are values in item_code, which is not making any sense and the exact same value in name, quantity and value. $(this) represents the button that was pushed, don't forget you are in an on click event.

  • 发表于 2019-03-23 18:14
  • 阅读 ( 202 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除