1

I'm having a problem with something that is likely a simple error.

As you will notice below, I have a check for duplicate function that references external PHP checking a database. The PHP is working, and returning data.

When I use duplicationCheck.done() and parse the data, my if statement responds correctly (i.e., if the user has entered a duplicate, this checks that. HERE'S the issue: Despite my if statement below functioning correctly, when isDuplicate is set to true, it appears as undefined when the console.log command is called below the done() function. I can't figure out why. With my research, I think that it is a problem with the async nature of the AJAX call?

Thank you for your time. Any ideas?

$("#username_submit").click(function() {

  function checkForDuplication(username) {
    return $.ajax({
      url: 'static/experiments/computerized_handwriting/random_assignment.php',
      type: 'POST',
      data: {userName: username}
    });
  }

var duplicationCheck = checkForDuplication($('input:text').val());


  var isDuplicate;
  duplicationCheck.done(function(data){
        var response = JSON.parse(data);
        if(response.data['json_array'] == "duplicate"){
          isDuplicate = true;
          alert("dup");
        } else {
         isDuplicate = false;
        }
    });

  console.log(isDuplicate);

....
  • You might want to fire events on specific elements using [`.change()`](https://api.jquery.com/change/) instead of doing it all in 1 go. – Xorifelse Jan 25 '17 at 00:27
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jacob Jan 25 '17 at 00:32
  • @Jacob I've read that a few times, but I can't figure out which part is relevant to my specific problem. Can you help? – Derek Stoeckenius Jan 25 '17 at 00:35

1 Answers1

1

This is due to the asynchronous nature of ajax.

You need to check for the duplication once it returns from the server in the done function. But your duplicationCheck variable is not a reference to the function, but what it is returning.

The proper way would be like this:

$("#username_submit").click(function() {
  $.ajax({
    url: 'static/experiments/computerized_handwriting/random_assignment.php',
    type: 'POST',
    data: { userName: $('input:text').val()}
  }).done(function() {
    var response = JSON.parse(data);
    if (response.data['json_array'] == "duplicate") {
      isDuplicate = true;
      alert("dup");
    }
    else {
     isDuplicate = false;
    }
    console.log(isDuplicate);
  });//done
});//submit click

....
Daniel Tome
  • 228
  • 1
  • 4
  • Thank you! In order to achieve the functionality I wanted, I had to change this to a synchronous call (I know, kind of silly, but I usually use traditional calls). Your code really helped, appreciate it! – Derek Stoeckenius Jan 25 '17 at 00:49