Return json value from mvc controller method in php

I would like to get a json type value from the mvc controller method. everything is correct, but an error occurs. "

my jquery ajax function:

function user_login(uname,pass){
    $.ajax({
        url: 'http://localhost/s/login_request',
        type:'POST',
        data:{uname:uname,pass:pass},
        dataType:"json",
        cache: false,
    })
    .done(function(response){
         //do something   
         alert('1234');
    })
    .fail(function(jqXHR,textStatus){
        alert(JSON.stringify(jqXHR));
    });
}

and here is my php code (mvc controller method):

function login_request(){
        header('Content-Type: application/json');
        echo json_encode(array('testvalue'));   
}

when I run the code, the .fail section is executed and the following value is returned:

{"readyState":4,"responseText":"[\"testvalue\"]","status":200,"statusText":"OK"}

how can i solve this? thanks...

+4
source share
1 answer

Try using

$.ajax({
    url: 'http://localhost/s/login_request',
    type:'POST',
    data:{uname:uname,pass:pass},
    dataType:"json",
    cache: false,
    success: function(data) { },
    fail: function(xhr, status) { alert(JSON.stringify(xhr)) },
    error: function() { },
    complete: function() { alert('1234') }
});
0
source

Source: https://habr.com/ru/post/1624881/


All Articles