0

I am making a function in Jquery that validates the date given, by accessing checkdate.php using ajax. checkdate.php uses checkdate() and returns "success" if the date is valid. Here is my jquery function.

function checkdate(sample)
  {
  $.get('checkdate.php?dateSample='+ sample, function(data){
    if(data == 'success')
      return true;
    else
      return false;
  });
  }

checkdate.php works with no error and I'm sure of that but my problem is when I use this code ->

alert(checkdate('2013-09-22'));

or

alert(checkdate('123123123iuo12'));

it always alerts "Undefined"

I need Boolean result from checkdate function. Please help me.

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
Alex Coroza
  • 1,747
  • 3
  • 23
  • 39
  • Or, it's all because ajax calls are usually "asynchronous". It does not wait for result to come back so it's undefined. – Lionel Chan Sep 22 '13 at 04:03
  • If you use the jquery-validate plugin, it has a `remote` method that makes it easy to use AJAX for validation. – Barmar Sep 22 '13 at 04:06
  • davidkonrad gave me a link that answers my question but i still cant apply that to my function. I also avoid putting so many plug ins hahha. – Alex Coroza Sep 22 '13 at 04:54

1 Answers1

0

You can try this

function checkDate(date)
{
    $.ajax({
        method: 'post', // or GET
        url: 'checkdate.php',
        data: {dateSample: date},
    }).done(function(response){
        alert(response);
        // do stuff ...
    });
}

checkDate('test');
Mina
  • 1,508
  • 1
  • 10
  • 11
  • Ok i'll try your solution. Currently I solved my problem by setting async to false, but they said it is not advisable, so i'll try this haha – Alex Coroza Sep 25 '13 at 09:41