在Laravel Blade中无法显示Jquery和Ajax错误消息

时间:2017-06-23 05:11:19

标签: php jquery laravel laravel-5.4

我在Laravel中使用Ajax和Jquery插入Ledger Record。成功消息已正确显示但错误自定义消息无法在刀片视图中显示。什么是我的错误请提及。

Jquery:

mydata <- structure(list(V1 = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("Salmon", 
"Trout"), class = "factor"), V2 = c(6L, 4L, 7L, 2L, 3L, 2L)), .Names = c("V1", 
"V2"), class = "data.frame", row.names = c(NA, -6L))

控制器:

$("#add").click(function(event) {
  event.preventDefault();

  $.ajax({
    type: 'post',
    url: $("#add").attr('data-url'),
    data: {
      '_token': $("input[name=_token]").val(),
      'form_data': $('#Form').serialize(),
    },
    success: function(data) {
      $('#ledger_name').val('');
      $('#openning_balance').val('');
      $('#ob_type').val('');
      $('#under').val('');
      $('#ledger_address').val('');
      $("#newLedger .close").click();

      $(".result").html(data.success).css({
        'color': 'green',
        'text-align': 'center'
      }).delay(5000).fadeOut();
    },
    error: function(data) {
      $('#response').show().html(data.error).css({
        'color': 'red',
        'text-align': 'center'
      }).delay(5000).fadeOut();
    }
  });
});

2 个答案:

答案 0 :(得分:2)

试试这个:

<?php
use Validator;

class SomeController extends Controller {

  public function SomeFunction(Request $request) {
    $values = array();
    parse_str($_POST['form_data'], $values);

    $validation = Validator::make($values, true);

    if($validation->fails()){
      $errors = $validation->errors();
      return response()->json(['error' => 'Please Fill all Mandatory Fields'], 500);
    }

    $insertledgers=Ledger::create(['ledger_name'=>$values['ledger_name'],'openning_balance'=>$values['openning_balance'],'ob_type'=>$values['ob_type'],'under'=>$values['under'],'ledger_address'=>$values['ledger_address'],'company_id'=>$companyids,'user_id'=>$usersid,'created_by'=>$usersid]);

    $ledgerinsertids=$insertledgers->id;

    if($values['ob_type'] == 'Cr'){

      $creditamts=$values['openning_balance'];
      $debitamts= 0;

    } else {

      $creditamts=0;
      $debitamts= $values['openning_balance'];

    }

    $insertledgeropenningbalance=Openningbalance::create(['ledgerid'=>$ledgerinsertids,'opening_credit'=>$creditamts,'opening_debit'=>$debitamts,'company_id'
    => $companyids,'user_id' => $usersid,'created_by' => $usersid,]);

    return response()->json(['success' => 'Ledger Details Added Successfully',],200);

并且在视野中:

error: function(data)
{
$('#response').html(data.error).css({'color': 'red', 'text-align': 'center'})
$('#response').show().delay(5000).fadeOut();
}

答案 1 :(得分:0)

您只需要修改错误回调函数,如下所示:

error : function (data) {
    $('#response').show().html(data.responseJSON.error).css({
        'color': 'red',
        'text-align': 'center'
    }).delay(5000).fadeOut();
}

谢谢@ voodoo417