user10214015
user10214015

Reputation:

JSON gives weird formatted result in js, how can I access the data?

This is the output in JavaScript totally unchanged:

{"message":"Beer 0,33l"}
{"message":"Beer 0,5l"}
{"message":"No matching articles"}

This comes from an Array from php, with > json_encode() encoded. And this is the output in JS:

$.ajax({
    url: '/Workers/backEnd/searchProduct.php',
    data: $('#warenInput'),
    type: 'post',
    success: function(data) {

        console.log(data);
    }
});

Now, I dont know how to get the strings. I tried everything coming to my mind. Neither data[0] nor data['message'] works.

How can I output the strings stored in 'message'?

Upvotes: 0

Views: 759

Answers (2)

Abhishek Honrao
Abhishek Honrao

Reputation: 835

If your getting values in json format on success. Then -

$.ajax({
    url: '/Workers/backEnd/searchProduct.php',
    data: $('#warenInput'),
    type: 'post',
    success: function(data) {

        console.log(data.message);
    }
});

Upvotes: -1

James Martin-Davies
James Martin-Davies

Reputation: 651

You need to parse the JSON response.

Update: What data are you sending via data in the POST request? It looks to me as if you're sending the HTML element, not the actual data. This likely should be $('#warenInput').val(), but your question is poorly formatted.

Try:

    $.ajax({
        url: '/Workers/backEnd/searchProduct.php',
        data: $('#warenInput'),
        type: 'post',
        success: function(data) {
            var res = JSON.parse(data);
            // or...
            var res = $.parseJSON(data);
            // If the response is an array...
            console.log(res[0].message);
            // If the response is an object...
            // console.log(res.message);
        }
    });

Read about JSON.parse() on MDN.

You need to turn the data in to an array in PHP, like so, for JSON.parse() to work.

$json = json_encode(array($data));

You could also wrap the data response in brackets, like

var res = JSON.parse('[' + data + ']');

However, I would strongly suggest you format it correctly on the back-end properly. Without seeing your PHP script in a little more detail, I have to assume it's the formatting that is incorrect. Maybe update your question to show how you are formatting your response?

Upvotes: 2

Related Questions