Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery post returns no response data

I have this code

$(document).delegate('#login', 'pageinit', function(event) {

console.log('inside login page')
$('#loginform').submit(function() {

    // Get the value of the username and password
    var myusername = $("#username").val();
    var mypassword = $("#password").val();

    // Post to the login route
    $.post(global_urlstub + '/customer_login', {username: myusername, password: mypassword}, function(data) {

        alert(data);
        console.log(data);
        if (data.flag == true) {
            alert('123');
            console.log(data);
            jQuery.mobile.changePage('#page1');
        }
        else {
            alert('12345');
            console.log(data);
            $('#errmsg_login').html(data.msg);
        }

    }, "json" );

    return false;

});

});

My server returns hash with key flag. However this code returns me no data to console or alert , while post request is successful. What am i doing wrong?

like image 231
Avdept Avatar asked Aug 08 '13 08:08

Avdept


2 Answers

It happens when you server is not returning a valid JSON

try it without datatype first like below..

$.post(global_urlstub + '/customer_login', {username: myusername, password: mypassword}, function(data) {

            alert(data);
            console.log(data);
            if (data.flag == true) {
                alert('123');
                console.log(data);
                jQuery.mobile.changePage('#page1');
            }
            else {
                alert('12345');
                console.log(data);
                $('#errmsg_login').html(data.msg);
            }

        });
like image 196
Hemant_Negi Avatar answered Oct 04 '22 02:10

Hemant_Negi


I would agree with Hemant_Negi that this is a problem with you server not returning valid JSON. The following code based on yours works fine (change of URL in there too which returns valid JSON):

var myusername = 'a', mypassword = 'b';
$.post('http://ip.jsontest.com', {username: myusername, password: mypassword}, function(data) {
    alert(data.ip);
    console.log(data);
    if (data.flag == true) {
        alert('123');
        console.log(data);
        jQuery.mobile.changePage('#page1');
    }
    else {
        alert('12345');
        console.log(data);
        $('#errmsg_login').html(data.msg);
    }
}, "json" ).fail( function(jqXHR, textStatus, errorThrown) {
    alert(textStatus);
});

If you change that URL, the call to fail() should alert an error message.

like image 36
Barrie Avatar answered Oct 04 '22 04:10

Barrie