简体   繁体   中英

ajax post returning string instead of json object

My code returns dataType object in PHP but when I am calling the same function using AJAX it returns the datatype to me as string. I want the data type to be a JSON object.

PHP code :

$result = $manualRequest->getUser($_POST['phonenumber']);

print_r($result);

This is actually a parsed database object

AJAX code :

function getCustomer() {
        var callerNumber = $('#caller_number').val();
        var data = {
            'phonenumber': callerNumber
        };
        var url = "customerRequest.php";

    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        dataType: 'JSON',
        success: function (result) {
            console.log(result);
        }
    });
}

I am getting the desired result but I want the JSON object and not the string.

print_r doesn't generally return valid JSON, you want to do

$result = $manualRequest->getUser($_POST['phonenumber']);
echo json_encode( $result );

As long as it's valid JSON, and the dataType is set to json , jQuery will parse it as such, anything else should result in a "parse error" in your ajax request.

In javascript you can use JSON.parse method to parse your string JSON to JSON object.

The documentation of this method: https://www.w3schools.com/js/js_json_parse.asp

In php file add:

header('Content-type:application/json;charset=utf-8');
echo json_encode($result);

instead of print_r($result);

If you want pretty JSON

$result = $manualRequest->getUser($_POST['phonenumber']);
echo json_encode($result , JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT );

Edit

    $.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    data: data,
    success:function(response){
        console.log(response);
    }
})
.done(function() {
    console.log("success");
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});

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