1

I want get a json array from PHP with jQuery, but it is not working.

PHP

$json[] = array(
  'status' => 'no',
  'xxx' => $myhtml
);

echo json_encode($json);

$myhtml is HTML source.

jQuery

$.post('server.php', {'work' : work , 'view_id' : view_id } , function(data){
    var json = JSON.parse(data);
    $('#main-show').html(json.xxx);         
});

I have array json in console, but json.xxx is undefined.

3
  • What does it say, when you access server.php via browser? Is JSON data there? Commented Apr 17, 2017 at 0:16
  • yes i have JSON data in console browser Commented Apr 17, 2017 at 0:24
  • Where's the rest of the jQuery code? Like variables work and view_id? is jQuery includes correct ? Commented Apr 17, 2017 at 0:39

2 Answers 2

1

Use JSON.stringify(), the php code is also modified, i.e.:

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>

<div id="main-show"></div>
<script>
    work = "test";
    view_id = "test2";
    $.post('json.php', {'work' : work , 'view_id' : view_id } , function(data){
        var json = JSON.parse(JSON.stringify(data));
        $('#main-show').html(json.xxx);
    });
</script>
</body>
</html>

php:

<?php
header('Content-Type: application/json');
$myhtml = '<p> TEST </p>';
$json = array(
    'status' => 'no',
    'xxx' => $myhtml
);
echo json_encode($json);
Sign up to request clarification or add additional context in comments.

Comments

1

You are creating an extra outer array.

Your current JSON would look like:

[
   {"status" : "no",  "xxx" : "html string"}
]

So to access that would need

$('#main-show').html(json[0].xxx);

But it would probably be easier to change php to:

$json = array(
  'status' => 'no',
  'xxx' => $myhtml
);

which when json encoded would produce:

{"status" : "no",  "xxx" : "html string"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.