Почему я не получаю ожидаемый результат с помощью этой проверки AJAX и PHP - PullRequest
1 голос
/ 05 марта 2019

Я пытаюсь интегрировать 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» в качестве ссылки на часть «сообщений», в ней теперь отображаетсясообщения, как я ожидал!Woop woop!

Просто нужно разобраться, как добавить некоторые классы в поля, и мы все хороши!

части, которые я редактирую на странице обработки

$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'
      })
    }
  })
})
});

Ответы [ 2 ]

0 голосов
/ 05 марта 2019

Исправлено!

Мне пришлось передвинуть логику в обработке 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'
      })
    }
  })
})
});
0 голосов
/ 05 марта 2019

В настоящее время похоже, что вы переопределяете $return каждую итерацию, а не добавляя к ней : $return = array('success' => 'False'); вместо $return["success"] = false;. Следующее может быть шагом в правильном направлении:

<?php
    // Declare an empty $return array.
    $return = array();

    // Iterate through the errors and populate the $return array.
    foreach (array_combine($validation->errors(), $validation->fields()) as $error => $field) {

        // Append an array of the error data to $return.
        $return[] = [
            "success" => false,
            "message" => $error,
            "field"   => $field,
        ];
    }

    // Output JSON-encoded array to front-end.
    echo json_encode($return);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...