首页 > 解决方案 > 为什么我没有通过此 AJAX 和 PHP 验证获得预期结果

问题描述

我正在尝试将 AJAX 集成到我的表单提交中。我目前有一个非常完善的提交表单的方法,但想摆脱整个提交,重新加载页面的事情。

我对 AJAX 和 JQUERY 完全陌生,所以学习曲线陡峭。我正在尝试将现有的 PHP 集成到 AJAX 表单提交中。我坚持的是能够将验证结果发送到脚本。

我目前在我的表单处理 php 中有这个

使用收到的反馈中的新代码进行了更新

$return = array();
if($validation->passed()) {
  try {
    $getPassageId = Input::get('passageId'); //Get the passage plan id passed via the form
    $latitude = convertDMSToDecimal(Input::get('lat'));
    $longitude = convertDMSToDecimal(Input::get('long'));
    $insertIntoWaypoints = DB::getInstance()->insert('ym_waypoints', array(
      'vessel_id' => $vid,
      'user_id' => $uid,
      'waypoint_num' => Input::get('waypoint'),
      'waypoint_name' => Input::get('waypointName'),
      'latitude' => $latitude,
      'longitude' => $longitude,
      'cts' => Input::get('courseToSteer'),
      'dtw' => Input::get('DistanceToWaypoint'),
      'hw_time' => Input::get('HWTime'),
      'hw_height' => Input::get('HWHeight'),
      'lw_time' => Input::get('LWTime'),
      'lw_height' => Input::get('LWHeight'),
      'chart_num' => Input::get('chartNumbers'),
      'almanac' => Input::get('almanacPages'),
      'radio_signals' => Input::get('radioPages'),
      'por' => Input::get('por'),
      'por_almanac' => Input::get('porAlmanac'),
      'por_vhf' => Input::get('porVHF'),
      'vhf' => Input::get('vhf'),
      'passage_note' => Input::get('notes')
    ));
    $recordID = $insertIntoWaypoints;
    $insertInto = DB::getInstance()->insert('ym_passageplan_route', array(
      'passageplan_id' => $getPassageId,
      'waypoint_id' => $recordID
    ));
    $return['success'] = True;
    $return['message'] = 'successful!';
    print json_encode($return);
  } catch (Exception $e) {
    $return['success'] = False;
    $return['message'] = 'fail';
    print json_encode($return);
  }
} else {
  foreach (array_combine($validation->errors(), $validation->fields()) as $error => $field) {
    // Append an array of the error data to $return.
    $return['success'] = False;
    $return['message'] .= $error;
  }
  print json_encode($return);
}

这是我用来发送数据的脚本

      $(routePlan_form).submit(function(e){
  e.preventDefault();
  $.ajax({
    type: "POST",
    url: "/pages/voyages/passageplans/createroute.php",
    dataType: 'json',
    data: $("#routePlan_form").serialize(),
    'success': function(data) {
      if(data['success']) {
        //refresh the table
        $("#table").load(location.href + " #table");
        //reset the form
        $('#routePlan_form').trigger("reset");
        //scroll to the top
        window.scrollTo({ top: 0, behavior: 'smooth' });
        //send the user a success message
        resetToastPosition();
        $.toast({
          heading: 'Success',
          text: 'Waypoint added successfully',
          textColor: 'white',
          showHideTransition: 'slide',
          hideAfter : 7000,
          icon: 'success',
          loaderBg: '#f96868',
          position: 'top-center'
        })
      } else {
        // var i;
        // for (i = 0; i < data['message'].length; i++) {
        // this.error(this.xhr, data['message']);
        // }
        this.error(this.xhr, data['message']);
      }
    },
    'error': function(jqXHR, textStatus, errorThrown) {
      console.log(textStatus);
    }
  })
})  
});

当有意提交表单时,我遗漏了应将验证错误发回的必填字段。在下面的出色帮助之后,我现在在控制台中得到了预期的错误。但是它们被列为“需要航点编号。需要航点名称。需要纬度。需要经度。”

我需要做的是将此列表拆分为单独的消息....

我假设我需要某种 foreach 或 $.each 语句,但对 JQuery 来说是新的,我不确定如何进行......

作为一个延伸目标,我还想要一种将以下内容添加到整个内容中的方法,这样我就可以提醒用户注意不正确的字段

          $("#<?php echo $field ?>").addClass("form-control-danger");
      $('<label id="<?php echo $field ?>-error" class="badge badge-danger" for="<?php echo $field ?>"><?php echo $error ?></label>').insertAfter("#<?php echo $field ?>");

任何指针都会很棒!

问候

马特

快速更新---

我越来越近了!我现在在处理 php 文件中有以下代码

foreach (array_combine($validation->errors(), $validation->fields()) as $error => $field) {
    // Append an array of the error data to $return.
    $return['success'] = False;
    $return['message'] .= [$error];
  }
  print json_encode($return);

以下循环遍历消息

else {
         var i;
         for (i = 0; i < data['message'].length; i++) {
         this.error(this.xhr, data['message']);
         }
        //this.error(this.xhr, data['message']);
      }
    },
    'error': function(jqXHR, textStatus, errorThrown) {
      //send the user a success message
      resetToastPosition();
      $.toast({
        heading: 'Error',
        text: '' + textStatus,
        textColor: 'white',
        showHideTransition: 'slide',
        hideAfter : 10000,
        icon: 'error',
        bgColor: '#f96868',
        position: 'top-center',
        loaderBg: '#405189'
      })
    }

这给了我 5 个弹出错误消息,但是文本状态为 ArrayArrayArrayArray,所以我知道它收到了 4 个错误,如我所料。我认为正在发生的事情是我将错误添加到 $return['message'] 数组中,因此我们正在输出 a、b、c、d 等。我想我需要将一个数组添加到 'message' 数组中?? 任何指向/如何获取错误消息或我哪里出错的指针?

越来越近!!!

想想正在发生的事情背后的逻辑,我想我现在又接近了。我现在只收到四条消息(正如我期望的那样),但所有消息都在每个消息框中分组在一起,所以我添加了变量“i”作为对“消息”部分的引用,现在显示消息如我所料!!呜呜呜!

只需要弄清楚如何在字段中添加一些类,我们都很好!

我正在处理页面中编辑的部分

$return = array();
$messages = array();
$return['success'] = False;
foreach (array_combine($validation->errors(), $validation->fields()) as $error => $field) {
    // Append an array of the error data to $return.
    array_push($messages, $error);
    //$return['message'] = array($error);
  }
  $return['message'] = $messages;
  echo json_encode($return);

以及表单页面上的 ajax 调用

$(document).ready(function() {
$(routePlan_form).submit(function(e){
  e.preventDefault();
  $.ajax({
    type: "POST",
    url: "/pages/voyages/passageplans/createroute.php",
    dataType: 'json',
    data: $("#routePlan_form").serialize(),
    'success': function(data) {
      if(data['success']) {
        //refresh the table
        $("#table").load(location.href + " #table");
        //reset the form
        $('#routePlan_form').trigger("reset");
        //scroll to the top
        window.scrollTo({ top: 0, behavior: 'smooth' });
        //send the user a success message
        resetToastPosition();
        $.toast({
          heading: 'Success',
          text: 'Waypoint added successfully',
          textColor: 'white',
          showHideTransition: 'slide',
          hideAfter : 7000,
          icon: 'success',
          loaderBg: '#f96868',
          position: 'top-center'
        })
      } else {
         var i;
         for (i = 0; i < data['message'].length; i++) {
         this.error(this.xhr, data['message'][i]);
         }
      }
    },
    'error': function(jqXHR, textStatus, errorThrown) {
      //send the user a success message
      resetToastPosition();
      $.toast({
        heading: 'Error',
        text: '' + textStatus,
        textColor: 'white',
        showHideTransition: 'slide',
        hideAfter : 10000,
        icon: 'error',
        bgColor: '#f96868',
        position: 'top-center',
        loaderBg: '#405189'
      })
    }
  })
})
});

标签: javascriptphpjqueryajax

解决方案


解决它!

我不得不在处理 php 中移动逻辑

$return = array();
$messages = array();
$fields = array();
$return['success'] = False;
if($validation->passed()) {
  try {
    $getPassageId = Input::get('passageId'); //Get the passage plan id passed via the form
    $latitude = convertDMSToDecimal(Input::get('lat'));
    $longitude = convertDMSToDecimal(Input::get('long'));
    $insertIntoWaypoints = DB::getInstance()->insert('ym_waypoints', array(
      'vessel_id' => $vid,
      'user_id' => $uid,
      'waypoint_num' => Input::get('waypoint'),
      'waypoint_name' => Input::get('waypointName'),
      'latitude' => $latitude,
      'longitude' => $longitude,
      'cts' => Input::get('courseToSteer'),
      'dtw' => Input::get('DistanceToWaypoint'),
      'hw_time' => Input::get('HWTime'),
      'hw_height' => Input::get('HWHeight'),
      'lw_time' => Input::get('LWTime'),
      'lw_height' => Input::get('LWHeight'),
      'chart_num' => Input::get('chartNumbers'),
      'almanac' => Input::get('almanacPages'),
      'radio_signals' => Input::get('radioPages'),
      'por' => Input::get('por'),
      'por_almanac' => Input::get('porAlmanac'),
      'por_vhf' => Input::get('porVHF'),
      'vhf' => Input::get('vhf'),
      'passage_note' => Input::get('notes')
    ));
    $recordID = $insertIntoWaypoints;
    $insertInto = DB::getInstance()->insert('ym_passageplan_route', array(
      'passageplan_id' => $getPassageId,
      'waypoint_id' => $recordID
    ));
    $return['success'] = True;
    $return['message'] = 'successful!';
    print json_encode($return);
  } catch (Exception $e) {
    $return['success'] = False;
    $return['message'] = 'Could&apos;t update the database';
    print json_encode($return);
  }
} else {
  foreach (array_combine($validation->errors(), $validation->fields()) as $error => $field) {
    // Append an array of the error data to $return.
    array_push($messages, $error);
    array_push($fields, $field);
  }
  $return['fields'] = $fields;
  $return['message'] = $messages;
  echo json_encode($return);
}
}

以及表单页面本身的 AJAX 段

$(document).ready(function() {
$(routePlan_form).submit(function(e){
  e.preventDefault();
  $.ajax({
    type: "POST",
    url: "/pages/voyages/passageplans/createroute.php",
    dataType: 'json',
    data: $("#routePlan_form").serialize(),
    'success': function(data) {
      if(data['success']) {
        //refresh the table
        $("#table").load(location.href + " #table");
        //reset the form
        $('#routePlan_form').trigger("reset");
        //scroll to the top
        window.scrollTo({ top: 0, behavior: 'smooth' });
        //send the user a success message
        resetToastPosition();
        $.toast({
          heading: 'Success',
          text: 'Waypoint added successfully',
          textColor: 'white',
          showHideTransition: 'slide',
          hideAfter : 7000,
          icon: 'success',
          loaderBg: '#f96868',
          position: 'top-center'
        })
      } else {
         var i;
         for (i = 0; i < data['message'].length; i++) {
         //scroll to the top
         window.scrollTo({ top: 0, behavior: 'smooth' });
         this.error(this.xhr, data['message'][i]);
         $("#"+data['fields'][i]).addClass("form-control-danger");
         $('<label id="'+data['fields'][i]+'"-error" class="badge badge-danger" for="'+data['fields'][i]+'">'+data['message'][i]+'</label>').insertAfter("#"+data['fields'][i]);
         }
      }
    },
    'error': function(jqXHR, textStatus, errorThrown) {
      //send the user a success message
      resetToastPosition();
      $.toast({
        heading: 'Error',
        text: '' + textStatus,
        textColor: 'white',
        showHideTransition: 'slide',
        hideAfter : 10000,
        icon: 'error',
        bgColor: '#f96868',
        position: 'top-center',
        loaderBg: '#405189'
      })
    }
  })
})
});

推荐阅读