JSON массив хранит предыдущий результат данных - PullRequest
0 голосов
/ 03 октября 2018

Так что моя проблема во время первой попытки обновить мой профиль, все в порядке.Он выводит одно сообщение и только один результат.Однако со второй попытки выводятся два сообщения и два результата.Я уже очистил свой массив, думая, что он был тем, в котором был сохранен предыдущий результат, но он ничего не сделал.

в моем файле js выглядит следующим образом:

$('#edit_my_profile').on('submit', function(e){
  e.preventDefault();

  var fname = $('#my_profile_fname').val(),
      mname = $('#my_profile_mname').val(),
      lname = $('#my_profile_lname').val(),
      user_number = $('#my_profile_user_number').val(),
      parent_number = $('#my_profile_parent_number').val(),
      department = $('#my_profile_department').val(),
      course = $('#my_profile_course').val(),
      year_level = $('#my_profile_year').val(),
      section = $('#my_profile_section').val(),
      username = $('#my_profile_username').val(),
      password = $('#my_profile_password').val(),
      alert = $('#my_profile_message_board');

  if(!validate([fname, mname, lname, user_number, parent_number, department, course, year_level, section, username, password])){
    notify('<i class="fas fa-times fa-lg mr-2"></i> <b>Error!</b> Cannot leave empty fields!', 'danger');
  } else if(password == 'password12345ddd'){
    notify('<i class="fas fa-times fa-lg mr-2"></i> <b>Error!</b> Please change the default password!', 'danger');
  } else{
    var modal = $('#modal_confirm_update_profile');

    modal.modal('show');

    $('#btn_update_profile').on('click', function(){
      modal.modal('hide')
      var data = $('#edit_my_profile').serializeArray();
      data[data.length] = {name : "edit_my_profile", value : 1};

      $.ajax({
        url : controllers('ProfilesController'),
        method : 'POST',
        data : data,
        dataType : 'JSON',
        success : function(e){
          // notify(e.message, e.alert);
          // my_profile_information();
          console.log(e)
        }
      })
    })
  }
})

и вотmy ProfilesController.php:

if(isset($_POST['edit_my_profile'])){
    $fname = $init->post('my_profile_fname');
    $mname = $init->post('my_profile_mname');
    $lname = $init->post('my_profile_lname');
    $user_number = $init->post('my_profile_user_number');
    $parent_number = $init->post('my_profile_parent_number');
    $section = $init->post('my_profile_section');
    $username = $init->post('my_profile_username');
    $password = encrypt($init->post('my_profile_password'));
    $updated_at = Carbon::parse($user_updated_at);

    $validate = validate([$fname, $mname, $lname, $user_number, $parent_number, $section, $username, $password]);

    $now = Carbon::now()->toDayDateTimeString();
    $length_in_days = $updated_at->diffInMinutes($now);

    if($length_in_days < 7){
        $json['bool'] = false;
        $json['alert'] = 'danger';
        $json['message'] = "<b>Error!</b> Calm down officer! You have recently updated your profile $length_in_days ago!";
    } else{
        if(!$validate){
            $json['bool'] = false;
            $json['alert'] = 'danger';
            $json['message'] = '<b>Error!</b> Cannot leave empty fields!';
        } else{
            $sql = $init->query("UPDATE users SET fname = '$fname', mname = '$mname', lname = '$lname', user_number = '$user_number', parent_number = '$parent_number', section_id = '$section', username = '$username', password = '$password' WHERE student_id = {$_SESSION['student_id']}");

            if($sql){
                $json['bool'] = true;
                $json['alert'] = 'primary';
                $json['message'] = '<i class="fas fa-thumbs-up fa-lg fa-spin"></i> Successfully updated your profile!';
            } else{
                $json['bool'] = false;
                $json['alert'] = 'danger';
                $json['message'] = '<b>Error!</b> Something went wrong!';
            }
        }
    }

    $json['error'] = $init->error();
    echo json_encode($json);
}

и результат во время второй попытки: (консоль chrome):

{bool: false, alert: "danger", message: "<b>Error!</b> Calm down officer! You have recently updated your profile 5 ago!", error: ""}
{bool: false, alert: "danger", message: "<b>Error!</b> Calm down officer! You have recently updated your profile 5 ago!", error: ""}
{bool: false, alert: "danger", message: "<b>Error!</b> Calm down officer! You have recently updated your profile 5 ago!", error: ""}

Должен выводиться только один.

Ответы [ 2 ]

0 голосов
/ 03 октября 2018

Каждый раз, когда вызывается $('#edit_my_profile').on('submit',...), он будет повторять вызов JSON n раз.Просто возьмите $('#btn_update_profile').on('click',...) из него, вот так:

var modal = $('#modal_confirm_update_profile');
$('#edit_my_profile').on('submit', function(e) {
  e.preventDefault();

  var fname = $('#my_profile_fname').val(),
      mname = $('#my_profile_mname').val(),
      lname = $('#my_profile_lname').val(),
      user_number = $('#my_profile_user_number').val(),
      parent_number = $('#my_profile_parent_number').val(),
      department = $('#my_profile_department').val(),
      course = $('#my_profile_course').val(),
      year_level = $('#my_profile_year').val(),
      section = $('#my_profile_section').val(),
      username = $('#my_profile_username').val(),
      password = $('#my_profile_password').val(),
      alert = $('#my_profile_message_board');

  if(!validate([fname, mname, lname, user_number, parent_number, department, course, year_level, section, username, password])){
    notify('<i class="fas fa-times fa-lg mr-2"></i> <b>Error!</b> Cannot leave empty fields!', 'danger');
  } else if(password == 'password12345ddd'){
    notify('<i class="fas fa-times fa-lg mr-2"></i> <b>Error!</b> Please change the default password!', 'danger');
  } else {
    modal.modal('show');
  }
});
$('#btn_update_profile').on('click', function() {
  modal.modal('hide')
  var data = $('#edit_my_profile').serializeArray();
  data[data.length] = {name : "edit_my_profile", value : 1};
  $.ajax({
    url : controllers('ProfilesController'),
    method : 'POST',
    data : data,
    dataType : 'JSON',
    success : function(e){
      // notify(e.message, e.alert);
      // my_profile_information();
      console.log(e)
    }
  });
});
0 голосов
/ 03 октября 2018

Проблема связана с добавлением click слушателя к #btn_update_profile внутри вашего submit слушателя.Каждый раз, когда форма отправляется, кнопка получает запрос на вызов новой функции при нажатии, поэтому вторая отправка отправляет запрос POST дважды и почему вы видите два журнала в консоли.

Предполагается, чточто #btn_update_profile находится внутри вашего модального окна, измените код так, чтобы вы добавляли click слушатель только один раз, а внутри этого слушателя вы можете проверить переменную, чтобы увидеть, была ли отправлена ​​форма.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...