Skip to content

Ajax .post() does not return results right away

Question:

The code runs correctly but only when I click the second time on button save of the form. Apparently, the first time does nothing.

The scriptcode is:
<script type="text/javascript">

function validacion(value, colname) {
        $mivariable = value;
        $.post('foo.php', {
                num_oferta: $mivariable
            },
            function(data) {
                $resultado = data;

            });
        if ($resultado == 1) {
            return [false, "Número de oferta ya existe"];
        } else {
            return [false, "Número de Oferta Nuevo"];
        }
    }

Solution:

Ajax is asynchronous. The value of $resultado is not guaranteed returned exactly after the $post. That's why the 2nd time it works. Sometimes, the 1st time works too if you give it enough time to test.

Here's a lengthy discussion on this issue:

Feedback and Knowledge Base