0

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'?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Fix your `searchProduct` page so that it gives you proper JSON in return. There are workarounds, like using a regular expression, but they'd be far less preferable to fixing the source of the essentially broken format of the data – CertainPerformance Jan 11 '20 at 23:42

2 Answers2

2

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?

  • No that gives a parse Error: ```JSON.parse: unexpected non-whitespace character after JSON data``` How can I avoid that? –  Jan 11 '20 at 23:38
  • @MyNameisKev it means the data you are returning is not valid JSON data. You likely need to convert the data to a JSON Array in PHP. See my updated answer. – James Martin-Davies Jan 11 '20 at 23:45
  • ```echo json_encode(['message' => $productCheck['product']]);``` This is how I encode the data in php. ```$productCheck['product']``` is an array containing the 3 data strings. And no matter what I do, there is always an Error. –  Jan 11 '20 at 23:49
  • @MyNameisKev Try the following? `$json = array( 'products' => $productCheck['product'] ); $response = json_encode($json); return $response;` - Just to clarify, are you `return`-ing the data or just `echo`'ing it out? – James Martin-Davies Jan 11 '20 at 23:57
  • 1
    Also worth mentioning you can use `$.parseJSON(data);` seems as you're using jQuery. – James Martin-Davies Jan 12 '20 at 00:01
  • Im not really sure how I can insert that in my Code. i found another solution with ```array_values()```, but Im still stuck at the output. But the output is different: ```{"message":["Beer 0,33l","Beer 0,5l"]}{"message":"no matching articles"}``` –  Jan 12 '20 at 00:07
  • parseJSON also works, now that php returns only one json object. I accidently returned 2. But I'm still stuck with the output. Nothing seems to work. –  Jan 12 '20 at 00:17
  • 1
    See this response: https://stackoverflow.com/questions/19381111/how-do-i-encode-json-in-php-via-jquery-ajax-post-data – James Martin-Davies Jan 12 '20 at 00:19
-1

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);
    }
});
Abhishek Honrao
  • 780
  • 5
  • 28
  • He isn't, though. He's _already_ said this doesn't work. PHP `json_encode` will send a serialised string back. You cannot access the data directly without parsing the response. – James Martin-Davies Jan 12 '20 at 00:08