简体   繁体   中英

trouble with json response from php in jQuery.ajax call

I am using $.ajax to get a JSON response from a php script. if i log the data variable from the $.ajax success function it outputs a properly formatted JSON object, however when I try to access properties of the data var it's undefined. here is the php the is being sent back:

echo json_encode(array("status"=>true, "success"=>"Login Success", "message"=>"You have been logged in successfully."));

and here is my ajax call:

$.ajax({
        type: "POST",
        data: {
            login: true,
            username: $('#login-username').val(),
            password: $('#login-password').val()
        },
        async: false,
        url: "./php/client-login.php",
        success: function (data) {
            console.log(data.status);
            if (data.status) {
                console.log(data.success);
                displayModal(data.success, data.message, "./js/login-modal-code.js");
            } else if (!data.status) {

                displayModal(data.error, data.message, "./js/login-modal-code.js");
            }
        },
        error: function (jqXHR, status, responseText) {
            console.log(status);
        }
});

if i add the dataType: "json" option to the $.ajax call I get a parse error and if i try to do $.parseJSON(data); to access the data in the data var I get and unexpected token error. I'm not really sure what I'm doing wrong, I've used this setup before and it always has worked before but for some reason it isn't now. anyone see where i've gone wrong?

EDIT: forgot to mention here is the response from the php script:

{"status":true,"success":"Login Success","message":"You have been logged in successfully."}

EDIT 2: Here is a screen of my console. the top .length call is the json that was logged from console.log(data) and the bottom one is from the response in chrome dev tools network tab for the response from the php script. they line up perfectly yet the second is showing a length of 93, how can i fix this? 控制台映像

I was reading on jQuery Docs and found that "dataType: jsonp" does not work with sync request, and you're making this kind of request since you have async: false . Turning it on may solve your problem.

Also, give a look at the docs.

Good luck!

So I figured out a workaround for this problem, first I did JSON.stringify on the data followed by JSON.parse and lastly $.parseJSON() to get a javascript object to work with. Not sure why there are 2 invisible characters being added between when it leaves the php script and reaches the $.ajax call so if anyone knows why let me know

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