Pregunta

I have the following code:

function check_email() {
    var email = $('#email').val();
    $.post(
        "inc/check.php", 
        { email: email },
        function(result) {
            if (result == 0) {
                // Do Stuff
            }
            else {
                // Do Stuff
            }
        }
    );
}

In my browser in the development environment this tests fine. However in other environments with the same browser the request does not seem to fire. I tested this by doing the following:

function check_email() {
    alert('test1');
    var email = $('#email').val();
    $.post(
        "inc/check.php", 
        { email: email }, 
        function(result) {
            alert('test2');
            if (result == 0) {
                // Do Stuff
            }
            else {
                // Do Stuff
            }
        }
    );
}

The first test1 alert fires but the second alert test2 doesn't. Remember this is only in certain environments. Has anybody got any ideas why?

¿Fue útil?

Solución

The first test1 alert fires but the second alert test2 doesn't. Remember this is only in certain environments. Has anybody got any ideas why?

Because something is going wrong in the environments where it doesn't work, and so the success handler isn't getting called.

You can find out what went wrong by

  1. Looking at your browser's development tools, and in particular the network tab, and

  2. Using the error handler and inspecting the information it gives you.

Option #2 will require rewriting your $.post using $.ajax (it's just a shortcut/wrapper around $.ajax anyway), like this:

$.ajax({
    type:    'POST',
    url:     "inc/check.php",
    data:    {email: email},
    success: function(result) {
        alert('test2');
        if (result == 0) {
            // Do Stuff
        }
        else {
            // Do Stuff
        }
    },
    error:   function(jqXHR, status, errThrown) {
        // Look at what went wrong here
    }
});

As a side note, alert-style debugging is incredibly inefficient, and there's no need for it in 2013. Instead, use the debugger built into your browser. Set breakpoints and step through the code. All major browsers have a debugger built in, including IE8 and above. Firefox's built-in one is still fairly basic, but there's the Firebug plug-in. The tools built into Chrome are excellent, but again, they all have them to a greater or lesser degree. There's even Visual Studio if you absolutely, positively have to debug something on IE7 or IE6.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top