lundi 27 juin 2016

JQuery confirmation dialog after AJAX request

I need to validate, on server side, if a person with a given registration number is already on the database. If this person is already registered, then I proceed with the program flow normally. But, if the number is not already registered, then I'd like to show a confirmation dialog asking if the operator wants to register a new person with the number entered and, if the operator answers yes, then the person will be registered with the number informed on the form on it's submission.

I've tried

Server side(PHP):

if (!$exists_person) {
  $resp['success'] = false;
  $resp['msg'] = 'Do you want to register a new person?';
  echo json_encode($resp);
}

Client side:

function submit(){
  var data = $('#myForm').serialize();

  $.ajax({
      type: 'POST'
      ,dataType: 'json'
      ,url: 'myPHP.php'
      ,async: 'true'
      ,data: data
      ,error: function(response){
        alert('response');
      }
  });
  return false;
}

I can't even see the alert, that's where I wanted to put my confirmation dialog, with the message written on server side. Other problem, how do I resubmit the entire form appended with the operator's answer, so the server can check if the answer was yes to register this new person?

EDIT

I was able to solve the problem this way:

Server side(PHP):

$person = find($_POST['regNo']);
if ($_POST['register_new'] === 'false' && !$person) {
    $resp['exists'] = false;
    $resp['msg'] = 'Do you want to register a new person?';
    die(json_encode($resp)); //send response to AJAX request on the client side
} else if ($_POST['register_new'] === 'true' && !$person) {
    //register new person
    $person = find($_POST['regNo']);
}

if($person){
    //proceed normal program flow
}

Client side:

function submit(e) {
    e.preventDefault();
    var data = $('#myForm').serialize();
    var ajax1 = $.ajax({
        type: 'POST'
        , dataType: 'json'
        , async: 'true'
        , url: 'myPHP.php'
        , data: data
        , success: function (response) {
            if (!response.exists && confirm(response.msg)) {
                document.getElementById('register_new').value = 'true'; //hidden input
                dados = $('#myForm').serialize(); //reserialize with new data
                var ajax2 = $.ajax({
                    type: 'POST'
                    , dataType: 'json'
                    , async: 'true'
                    , url: 'myPHP.php'
                    , data: data
                    , success: function () {
                        document.getElementById('register_new').value = 'false';
                        $('#myForm').unbind('submit').submit();
                    }
                });
            } else if (response.success) {
                alert(response.msg);
                $('#myForm').unbind('submit').submit();
            }
        }
    });
}

Aucun commentaire:

Enregistrer un commentaire