简体   繁体   中英

JQuery AJAX unable to Parse response from PHP PDO method

I am trying to fill a drop down list using JQuery AJAX and PHP. I have created a method in PHP which echo es a json_encoded() array . However, when the document is loaded it fails to get the result because of some JSON parsing error.

I am using a callable stored procedure in PHP and verified that it returns the correct result set when I tested the stored procedure in MySQL Workbench.

What could be causing this?

Error:

Parsing JSON Request Failed

RoleDaoImpl.php

function getAllRoles()
{
    $roleList[] = "";
    try {
        $SQL = "CALL getAllRoles()";
        $sp_getAllRoles = $this->connection->prepare($SQL);
        $sp_getAllRoles->execute();

        $resultSet = $sp_getAllRoles->fetchAll(PDO::FETCH_ASSOC);
        foreach ($resultSet as $row) {
            $roleId = $row['role_id'];
            $roleName = $row['role_name'];

            $roleList[] = array("roleId" => $roleId, "roleName" => $roleName);
        }
        echo json_encode($roleList);
    } catch (PDOException $e) {
        die($e->getMessage());
    }
}

get_all_roles.php

require_once '../../core/init.php';
$roleDaoImpl = new RoleDaoImpl($pdo);

$roleDaoImpl->getAllRoles();

JS file

$(document).ready(function(){
    loadRolesToDropDown();
});

function loadRolesToDropDown(){
    var url = 'get_all_roles.php';
    $.ajax({
        url: url,
        type: 'post',
        dataType: 'json',
        success: function(response){
            var len = response.length;
            alert(response);
            $("#roledropdown").empty();
            for(var i = 0; i < len; i++){
                var roleId = response[i]['roleId'];
                var roleName = response[i]['roleName'];
                $("#roledropdown").append("<option value='"+roleId+"'>"+roleName+"</option>");
            }
        },
        error : function(x,e){
            if (x.status==0) {
                alert('You are offline!!\n Please Check Your Network.');
            } else if(x.status==404) {
                alert('Requested URL not found.');
            } else if(x.status==500) {
                alert('Internal Server Error.');
            } else if(e=='parsererror') {
                alert('Error.\nParsing JSON Request failed.');
            } else if(e=='timeout'){
                alert('Request Time out.');
            } else {
                alert('Unknown Error.\n'+x.responseText);
            }
        }
    });
}

I can't think of other ways to identify the cause. I'm fairly new with using AJAX with PHP. I'm using AJAX to avoid refreshing the page. Recently, I tried to follow some tutorials and still trying to get a grasp of how JQuery Ajax and PHP work together.

What other troubleshooting can I do?

I'd appreciate any suggestion.

Thank you.

***** EDIT ******

I tried printing log using console.log() as in:

success: function(response){
    var len = response.length;
    alert(response);
    console.log(response);
    $("#roledropdown").empty();
    for(var i = 0; i < len; i++){
        var roleId = response[i]['roleId'];
        var roleName = response[i]['roleName'];
        $("#roledropdown").append("<option value='"+roleId+"'>"+roleName+"</option>");
    }
}

I get the ff on Google Chrome's console window.

jquery-3.3.1.js:9488 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/ .

在此处输入图片说明

Then, I inspected the this line ajax @jquery-3.3.1.js:9206 . And I get the ff. ( I don't know if it has something to do with parsing )

try {
    completed = false;
    transport.send( requestHeaders, done );
    } catch ( e ) {
    // Rethrow post-completion exceptions
    if ( completed ) {
        throw e;
    }

    // Propagate others as results
    done( -1, e );
}

By the way, the drop down list is contained in a modal div . I'm not sure if it has anything to do with the error. Something seemed to be deprecated as per the message shown in console window.

****** END OF EDIT ******

如果怀疑json_encode()问题,则必须检查该函数是否返回false,然后使用json_last_error()了解原因。

I cannot speak to your PHP output, but using placeholder data, I can easily confirm your JS does what you expect it to do. Below is your JS implemented using data from https://jsonplaceholder.typicode.com/users . It works as expected.

This indicates the output from your server is incorrect. You can use the browser's developer tools to determine precisely what is being sent back from the server using the network tab. The image demonstrates this on this snippet.

在此处输入图片说明

 $(document).ready(function(){ loadRolesToDropDown(); }); function loadRolesToDropDown(){ var url = 'https://jsonplaceholder.typicode.com/users'; $.ajax({ url: url, type: 'get', dataType: 'json', success: function(response){ var len = response.length; $("#roledropdown").empty(); for(var i = 0; i < len; i++){ var id = response[i]['id']; var name = response[i]['name']; $("#roledropdown").append("<option value='"+id+"'>"+name+"</option>"); } }, error : function(x,e){ if (x.status==0) { alert('You are offline!!\\n Please Check Your Network.'); } else if(x.status==404) { alert('Requested URL not found.'); } else if(x.status==500) { alert('Internal Server Error.'); } else if(e=='parsererror') { alert('Error.\\nParsing JSON Request failed.'); } else if(e=='timeout'){ alert('Request Time out.'); } else { alert('Unknown Error.\\n'+x.responseText); } } }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="roledropdown"></select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM