简体   繁体   中英

How to get only the newest value response from Ajax?

I have the issue with AJAX response and display errors.

For example, when I submit my form, I see 1 in console, but If I write something in first input and submit again, then I see:

1

2

Ajax below read 1 and 2 as both responses, so I see 2 errors but I should see only the newest, so it should be only 2 .

Also, I getting value when I try to use search ( invite ), but Ajax skipping everything and showing only success message after Submit.

ajax.js

$(document).ready(function() {

  $('#form_create_circle').submit(function(event){

    event.preventDefault();

    $.ajax({
      url: 'form-create-circle.php',
      type: 'POST',
      data: $('#form_create_circle').serialize(),
      dataType: 'json',
      success: function(response) {

        console.log(response);

        if (response == 1) {

          $('#title').addClass('is-invalid');
          $('#invalid_title').append('<div class="invalid-feedback"><p>This field is required.</p></div>');

        } else if (response == 2) {

          $('#invite').addClass('is-invalid');
          $('#invalid_invite').append('<div class="invalid-feedback"><p>This field is required.</p></div>');

        } else if (response == 3) {

          $('#color').addClass('is-invalid');
          $('#invalid_color').append('<div class="invalid-feedback"><p>This field is required.</p></div>');

        } else {

          // success message
          $('#_noti-container').append('<div class="noti noti-success noti-top-right noti-close-on-click noti-on-leave" style="z-index:100000"><div class="noti-content-wrapper"><div class="noti-content">Circle has been created!</div><div class="noti-close">×</div></div></div>');

        }

      }
    });

    return false;

  });

});

form-create-circle.php

require_once($_SERVER['DOCUMENT_ROOT'].'/system/mysql/config.php');

$title = $db->EscapeString($_POST['title']);
$invite = $db->EscapeString($_POST['invite']);
$color = $db->EscapeString($_POST['color']);
$time = date('Y-m-d H:i:s');

$search = $db->QueryFetchArrayAll("SELECT * FROM user_about WHERE firstname LIKE '%".$invite."%' OR lastname LIKE '%".$invite."%'");

foreach ($search as $key) {
  echo "
  <div class='invite_search_cont'>
    <div class='invite_search_img'><img src='{$key['profile_image']}'></img></div>
    <div class='invite_search_name'>{$key['firstname']} {$key['lastname']}</div>
  </div>
  ";
}

if ($title == '' || (!preg_match('/^[a-zA-Z0-9]+$/', $title))) {
  echo 1;
} elseif ($search == '') {
  echo 2;
} elseif ($color == '') {
  echo 3;
} else {

  $db->Query("INSERT INTO user_circle (user_id, user_added, title, color, time_added) VALUES ('{$user['id']}', '$invite', '$title', '$color', '$time')");

}

HTML

<form method='POST' id='form_create_circle'>
  <div class='modal-body'>
    <div>
      <div class='form-group'>
        <input type='text' name='title' id='title' placeholder='Family' class='form-control'>
        <div id='invalid_title'></div>
      </div>
      <div class='form-group'>
        <input type='text' name='invite' id='invite' placeholder='Search' class='form-control'>
        <div id='invite_search_result'></div>
        <div id='invalid_invite'></div>
      </div>
      <div class='form-group'>
        <select name='color' id='color' class='form-control'>
          <option value='0'>white</option>
          <option value='1'>yellow</option>
          <option value='2'>red</option>
        </select>
        <div id='invalid_color'></div>
      </div>
    </div>
  </div>
  <button type='submit' class='btn btn-primary' id='ajax_create_circle'>Submit</button>
</form>
<div id='_noti-container' class='noti-t-right'></div>

Sounds to me you just need to add $('#invalid_...').empty() to the start of the script before the ajax or change .append to .html

Also removeClass on all the divs involved:

$('#form_create_circle').submit(function(event) {
  event.preventDefault();
  $.ajax({
    url: 'form-create-circle.php',
    type: 'POST',
    data: $('#form_create_circle').serialize(),
    dataType: 'json',
    success: function(response) {
      console.log(response);
      $('#title, #invite, #color').removeClass('is-invalid');
      $("[id^=invalid]").empty(); // empty all error divs
      if ("123".indexOf(response) > -1) {
        var type = ["", "title", "invite", "color"][response];
        $('#' + type).addClass('is-invalid');
        $('#invalid_' + type).html('<div class="invalid-feedback"><p>This field is required.</p></div>');
      } else {
        // success message
        $('#_noti-container').html('<div class="noti noti-success noti-top-right noti-close-on-click noti-on-leave" style="z-index:100000"><div class="noti-content-wrapper"><div class="noti-content">Circle has been created!</div><div class="noti-close">×</div></div></div>');
      }
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM