Как исправить значение 0, вставленное в базу данных во втором запросе на Ajax? - PullRequest
0 голосов
/ 20 апреля 2019

У меня проблема с вставкой последнего идентификатора вставки во второй запрос Ajax, когда я просматриваю столбец, все вставленные элементы имеют значение 0.Итак, теперь я хочу вставить каждую строку таблицы с собственным уникальным идентификатором

У меня есть две таблицы:

  1. wish_list_menu_order
  2. wish_list_menu_belong_condiments

Первая вставка была на wish_list_menu_order, поэтому в функции успеха первой вставки у меня есть второй запрос, URL которого был wish_list_menu_belong_condiments.

Первый запрос:

public function insert_wish_list_menu_order(Request $request)
{
    $customer_id = $request->get('customer_id');
    $append_customer_noun_order = $request->get('append_customer_noun_order');
    $append_customer_noun_order_price = $request->get('append_customer_noun_order_price');
    $now = new DateTime();

    for ($count = 0; $count < count($append_customer_noun_order); $count++) {

        DB::insert('INSERT INTO wish_list_menu_order (customer_id,wish_list_menu_name,wish_list_total_price,wish_created_at) 
        VALUES(?,?,?,?) ', [

            $customer_id,
            $append_customer_noun_order[$count],
            $append_customer_noun_order_price[$count],
            $now,
        ]);
    }
}

Второй запрос:

public function insert_wish_list_menu_belong_condiments(Request $request)
{
    $Qty = $request->get('Qty');
    $Item = $request->get('Item');
    $Cost = $request->get('Cost');

    $now = new DateTime();

    $last_id_insert = DB::select('SELECT LAST_INSERT_ID() as id FROM wish_list_menu_order');

    foreach ($last_id_insert as $result) {
        $id_last_inserted = $result->id;
    }

    for ($count = 0; $count < count($Item); $count++) {

        DB::insert('INSERT INTO wish_list_menu_belong_condiments (wish_menu_id,belong_condi_name,belong_condi_qty,belong_condi_price,belong_condi_created) 
        VALUES(?,?,?,?,?) ', [

            $id_last_inserted,
            $Item[$count],
            $Qty[$count],
            $Cost[$count],
            $now,
        ]);
    }

    return response()->json('Successfully Inserted');
}

Мой Ajax:

$('button#add_to_cart').on('click', function () {

    var customer_id = $('#hidden_customer_id').val();

    var parent_item = [];
    var parent_amount = [];

    //child
    var child_item = [];
    var child_quantity = [];
    var child_amount = [];

    //this is for parent item and amount
    $('#noun_chaining_order').find('tr.condimentParent td.parent_item').each(function () {
        parent_item.push($(this).text());
    });

    $('#noun_chaining_order').find('tr.condimentParent td.total').each(function () {
        parent_amount.push($(this).text());
    });

    //end

    //this is for child item,amount and quantity
    $('#noun_chaining_order').find('tr.editCondiments td.child_item').each(function () {
        child_item.push($(this).text())
    });

    $('#noun_chaining_order').find('tr.editCondiments td.total').each(function () {
        child_amount.push($(this).text());
    });

    $('#noun_chaining_order').find('tr.editCondiments td.condiments_order_quantity').each(function () {
        child_quantity.push($(this).text());
    });

    $.ajax({

        url: '/insert_wish_list_menu_order',
        type: 'post',

        data: {
            customer_id: customer_id,
            append_customer_noun_order: parent_item,
            append_customer_noun_order_price: parent_amount,
            Qty: child_quantity,
            Item: child_item,
            Cost: child_amount
        },

        success: function (response) {
            console.log(response);

            $.ajax({

                url: '/insert_wish_list_menu_belong_condiments',
                type: 'post',

                data: {
                    Qty: child_quantity,
                    Item: child_item,
                    Cost: child_amount
                },

                success: function (response) {
                    console.log(response);
                },

                error: function (response) {
                    console.log(response);
                }
            });
        },
        error: function (response) {
            console.log(response);
        }
    });
});

Так я добавляю пункты меню в таблицу.

$("tr#productClicked").click(function () {

      var menu_name = $(this).closest("tr").find(".menu_name").text();
      var menu_price = $(this).closest("tr").find(".menu_price").text();
      var chain_id =  $(this).closest("tr").find(".chain_id").text();
      var menu_image = $(this).closest("tr").find(".menu_image").attr('src');
      var menu_cat_id =  $(this).closest("tr").find(".menu_id").text();
      var customer_id = $('#hidden_customer_id').val();

      if(chain_id == 0)
      {
         $("tbody#tbody_noun_chaining_order").
          append("<tr class='condimentParent' style='background-color:'black !important',color:'white !important' '>\
          <td></td><td class='parent_item'>"+menu_name+"</td><td class='total'>"+menu_price+"</td>\
          <td><button class='removeorderWithOutCondi btn btn-danger form-control'>\
          <i class='far fa-trash-alt'></i></button></td></tr>");

          //computation of total click without chain
          var sum_sub_total_price = 0;
          $('td.total').each(function () {
            sum_sub_total_price += parseFloat($(this).text());
          });
          var with_decimal_subprice = parseFloat(sum_sub_total_price).toFixed(2);
          $('.append_customer_noun_order_price').text(with_decimal_subprice);
      }
      else
      {
          $("tbody#tbody_noun_chaining_order").
          append("<tr class='condimentParent' style='background-color:'black !important',color:'white !important' '>\
          <td></td><td class='parent_item'>"+menu_name+"</td><td class='total'>"+menu_price+"</td>\
          <td><button class='removeorderWithOutCondi btn btn-danger form-control'>\
          <i class='far fa-trash-alt'></i></button></td></tr>");

          //after displaying the parent item get the condiments
          $.ajax({
            url:'/get_noun_group_combination',
            type:'get',
            data:{chain_id:chain_id},
            success:function(response){

              var noun_chaining = response[0].noun_chaining;
              $.each(noun_chaining, function (index, el) {

                var stringify_noun_chaining = jQuery.parseJSON(JSON.stringify(el)); 

                var Qty = stringify_noun_chaining['Qty'];
                var Condiments = stringify_noun_chaining['Condiments'];
                var Price = stringify_noun_chaining['Price'];
                var allow_to_open_condiments = stringify_noun_chaining['allow_to_open_condiments'];
                var condiments_section_id = stringify_noun_chaining['condiments_section_id'];

                $("tbody#tbody_noun_chaining_order").
                append("<tr class='editCondiments'>\
                <td class='condiments_order_quantity'>"+Qty+"</td>\
                <td class='child_item'>*"+Condiments+"</td><td class='total'>"+Price+"</td>\
                <td class='allow_to_open_condiments_conditional' style='display:none;'>"+allow_to_open_condiments+"</td>\
                <td class='condi_section_id' style='display:none;'>"+condiments_section_id+"</td>\
                </tr>");

              });

            }
          });
      }


});

Таблица 1. table 1

Таблица 2. Table 2

$('button#add_to_cart').on('click',function () {

    var customer_id = $('#hidden_customer_id').val();

    
    var parent_item =[];
    var parent_amount =[];
    

    //child
    var child_item =[];
    var child_quantity =[];
    var child_amount = [];



    //this is for parent item and amount
    $('#noun_chaining_order').find('tr.condimentParent td.parent_item').each(function(){
        parent_item.push($(this).text());
        
    });

    $('#noun_chaining_order').find('tr.condimentParent td.total').each(function(){
        parent_amount.push($(this).text());
        
    });

    //end

    //this is for child item,amount and quantity
    $('#noun_chaining_order').find('tr.editCondiments td.child_item').each(function(){
        child_item.push($(this).text());
        
    });

    $('#noun_chaining_order').find('tr.editCondiments td.total').each(function(){
        child_amount.push($(this).text());
     
    });

    $('#noun_chaining_order').find('tr.editCondiments td.condiments_order_quantity').each(function(){
        child_quantity.push($(this).text());
        
    });



    $.ajax({

      url: '/insert_wish_list_menu_order',
      type: 'post',

      data: {
        customer_id: customer_id,
        append_customer_noun_order: parent_item,
        append_customer_noun_order_price: parent_amount,
        Qty: child_quantity,
        Item: child_item,
        Cost: child_amount
      },

      success:function(response){
        console.log(response);

        $.ajax({

          url: '/insert_wish_list_menu_belong_condiments',
          type: 'post',

          data: {
            Qty: child_quantity,
            Item: child_item,
            Cost: child_amount
          },

          success:function(response){
            console.log(response);

          },
          error:function(response) {
              console.log(response);
          }

        });

      },
      error:function(response) {
          console.log(response);
      }

    });
    


});
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <title></title>
</head>

<body>

  <table class="table table-hover upsize_check" id="noun_chaining_order" style="border:none;">
    <input type="hidden" name="" value="" id="hidden_customer_id">
    <thead>
      <tr style="font-size: 15px;  color:white;">
        <th scope="col">Qty</th>
        <th scope="col">Items</th>
        <th scope="col">Price</th>
        <th>Action</th>
      </tr>
    </thead>

    <tbody style="font-size:14px;" id="tbody_noun_chaining_order">
      <tr class="condimentParent">
        <td></td>
        <td class="parent_item">$5.00 Extra Crispy 2 Piece Box</td>
        <td class="total">5.00</td>
        <td><button class="removeorderWithCondi btn btn-danger form-control">Delete</button></td>
      </tr>
      <tr class="editCondiments">
        <td class="condiments_order_quantity">2</td>
        <td class='child_item'>*Standard</td>
        <td class="total">0.00</td>
        <td class="allow_to_open_condiments_conditional" style="display:none;">Yes</td>
        <td class="condi_section_id" style="display:none;">3</td>
      </tr>
      <tr class="editCondiments">
        <td class="condiments_order_quantity">2</td>
        <td class='child_item'>*Individual Fries</td>
        <td class="total">0.00</td>
        <td class="allow_to_open_condiments_conditional" style="display:none;">Yes</td>
        <td class="condi_section_id" style="display:none;">2</td>
      </tr>
      <tr class="editCondiments">
        <td class="condiments_order_quantity">1</td>
        <td class='child_item'>*Buttery Bread</td>
        <td class="total">0.00</td>
        <td class="allow_to_open_condiments_conditional" style="display:none;">No</td>
        <td class="condi_section_id" style="display:none;">4</td>
      </tr>
      <tr class="editCondiments">
        <td class="condiments_order_quantity">1</td>
        <td class='child_item'>*Chocolate Chip Cookie</td>
        <td class="total">0.00</td>
        <td class="allow_to_open_condiments_conditional" style="display:none;">No</td>
        <td class="condi_section_id" style="display:none;">5</td>
      </tr>
      <tr class="editCondiments">
        <td class="condiments_order_quantity">1</td>
        <td class='child_item'>*355ml Pepsi</td>
        <td class="total">0.00</td>
        <td class="allow_to_open_condiments_conditional" style="display:none;">No</td>
        <td class="condi_section_id" style="display:none;">6</td>
      </tr>
      
      <tr class="condimentParent" style="background-color:" black="" !important',color:'white="" !important'="" '="">              <td></td><td class="parent_item">BIG CRUNCH Sandwich</td><td class="total">7.29</td>              <td><button class="removeorderWithOutCondi btn btn-danger form-control">              <i class="far fa-trash-alt"></i></button></td></tr>

    </tbody>

  </table>
  <center>
    <button type="button" class="btn btn-primary" style="background-color:#3D0081; border-color:#3D0081;" id="add_to_cart">Click to process the order</button>
  </center>

  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>

</html>

1 Ответ

2 голосов
/ 20 апреля 2019

Взято из документации MySQL :

"Сгенерированный идентификатор сохраняется на сервере для каждого подключения."

В вашем коде два запроса - первый, вставляющий родительскую запись в wish_list_menu_order, второй, вставляющий дочерние записи в wish_list_menu_belong_condiments, могут выполняться на разных соединениях MySQL, которые необязательно выполняются последовательно. Вместо того, чтобы запрашивать LAST_INSERT_ID() во втором вызове, вы должны вызвать его после вставки записи в базу данных и вернуть ее как часть ответа AJAX.

В вашем текущем коде все записи будут добавлены в wish_list_menu_order последовательно, и после его завершения будут добавлены дочерние элементы. В вашем лучшем случае - только если используется только одно соединение MySQL - вы можете получить последний вставленный идентификатор родительской таблицы и использовать этот идентификатор для всех вставок в wish_list_menu_belong_condiments.

Возможное решение

  1. для каждой вставки в wish_list_menu_order, выполните один вызов AJAX и верните LAST_INSERT_ID().
  2. для каждого дочернего элемента выполните еще один вызов AJAX во внешнем «родительском» цикле, предоставив в качестве параметра результат предыдущего вызова AJAX.

Код сервера:

Вставляет в wish_list_menu_order:

public function insert_wish_list_menu_order(Request $request)
{
    $customer_id = $request->get('customer_id');
    $append_customer_noun_order = $request->get('append_customer_noun_order');
    $append_customer_noun_order_price = $request->get('append_customer_noun_order_price');
    $now = new DateTime();


    DB::insert('INSERT INTO wish_list_menu_order (customer_id,wish_list_menu_name,wish_list_total_price,wish_created_at) 
    VALUES(?,?,?,?) ', [

        $customer_id,
        $append_customer_noun_order,
        $append_customer_noun_order_price,
        $now,
    ]);

    $last_id_insert = DB::select('SELECT LAST_INSERT_ID() as id FROM wish_list_menu_order');
    return response()->json($last_id_insert);   
}

Вставить в wish_list_menu_belong_condiments:

public function insert_wish_list_menu_belong_condiments(Request $request)
{
    $Qty = $request->get('Qty');
    $Item = $request->get('Item');
    $Cost = $request->get('Cost');
    $ParentId= $request->get('ParentId');

    for ($count = 0; $count < count($Item); $count++) {

        DB::insert('INSERT INTO wish_list_menu_belong_condiments (wish_menu_id,belong_condi_name,belong_condi_qty,belong_condi_price,belong_condi_created) 
        VALUES(?,?,?,?,?) ', [

            $ParentId,
            $Item[$count],
            $Qty[$count],
            $Cost[$count],
            $now,
        ]);
    }

    return response()->json('Successfully Inserted');
}

Код переднего конца:

// just for fiddle demo
var orderNumber = 358;
var customer_id = $('#hidden_customer_id').val();

$('#add_to_cart').on('click', function() {

  // reset 
  var orders = [];
  var menu;

  $('#tbody_noun_chaining_order').children('tr').each(function() {
    $row = $(this);
    if ($row.hasClass('condimentParent')) {

      // store a previous menu to the orders array if exists.
      if (menu !== undefined) {
        orders.push(menu);
      }
      menu = {
        'total': $row.find('.total').text(),
        'name': $row.find('.parent_item').text(),
        'condiments': {
          'Item': [],
          'Qty': [],
          'Total': []
        }
      };

    } else if ($row.hasClass('editCondiments')) {
      // row is a condiment, append elements to the previous "menu" variable
      menu.condiments.Item.push($row.find('.child_item').text());
      menu.condiments.Qty.push($row.find('.condiments_order_quantity').text());
      menu.condiments.Total.push($row.find('.total').text());
    }
  });
  if (menu) {
    orders.push(menu);
  }
  storeOrder(orders);
});

function storeOrder(orders) {

  for (var num in orders) {

    // simulate storing the order
    $.ajax('/echo/json', {
      type: 'POST',
      // as the call is asynchronous, make sure to provide all required reference data along with the call.
      context: orders[num].condiments,
      data: {
        'json': '"' + (orderNumber++) + '"',
        'customer_id': customer_id,
        'append_customer_noun_order_price': orders[num].total,
        'append_customer_noun_order': orders[num].name,
      },
      success: function(orderNumber) {
        if (!isNaN(orderNumber)) {
          $.ajax('/echo/json', {
            context: orderNumber,
            type: 'POST',
            data: {
              'ParentId': orderNumber,
              'Item': this.Item,
              'Qty': this.Qty,
              'Total': this.Total,
              'json': '{"condimentsCount": ' + this.Item.length + '}'
            },
            success: function(result) {
              $('#result').append('Stored ' + result.condimentsCount + ' condiments for order ' +
                this + '<br />');
            }
          }); // End of condiments save procedure
        }
      }
    }); // End of menu save procedure
  }
}

Скрипка, показывающая макетированную переднюю часть:

https://jsfiddle.net/Moonbird_IT/qbhnctre/

Общие рекомендации:

  • не доверяйте никаким данным, которые вы получаете от пользователя: умный пользователь может просто изменить цену на приправы или меню в HTML, прежде чем отправлять их на сервер. Вместо этого загрузите цены для каждого элемента на стороне сервера.
  • проверьте консоль инструментов вашего разработчика в браузере. Это даст вам раннее предупреждение, если у вас есть ошибки JS
  • также используйте Инструменты разработчика для сканирования HTML-кода, который создает ваш JavaScript.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...