0

I'm trying to display the output from the database using JSON Encode function and Ajax. But, I'm getting difficult on how to pass the html element "" and the php "eg." variable that show data from the server.I want the output to be displayed using json and ajax request.Thanks.

Here's my codes

 //js
  function mpo() 
 {
     $.ajax({
         url: "main.php",
         cache: false,
         success: function(html){
             $("#show_div").html(html);
         }
     });
 }


//php

$bu = "<div class='main' style='margin-left:" .($level*60). "px'>";     
$bu = "<div class='main_one'>";
$bu = "<div class='main_User'>" .($same[2]) . "</div>";
$bu = "<div class='main_Msg'>" .($same[3]) . "</div>";
$bu = "<div class='main_Date'>" . ($same[4]) . "</div>";
$json  =array('bu'=>$bu);
echo json_encode($json);        

2 Answers 2

3

You can use dataType : 'html' with this you don't requied to json encode

//js
  function mpo() 
 {
     $.ajax({
         url: "main.php",
         cache: false,
         dataType : 'html'
         success: function(html){
             $("#show_div").html(html);
         }
     });
 }

//php

$bu = "<div class='main' style='margin-left:" .($level*60). "px'>";     
$bu = "<div class='main_one'>";
$bu = "<div class='main_User'>" .($same[2]) . "</div>";
$bu = "<div class='main_Msg'>" .($same[3]) . "</div>";
$bu = "<div class='main_Date'>" . ($same[4]) . "</div>";

echo $json;die;
Sign up to request clarification or add additional context in comments.

1 Comment

I am also agree with jeroen. If you want to do it only json encode way then jeroen way is perfect
0

You are missing 2 things:

  1. You (probably...) need to parse the json.
  2. You need to get the right element from the parsed object.

To have jQuery parse the json automatically, you can set the dataType:

 $.ajax({
     url: "main.php",
     dataType: 'json',
     ^^^^^^^^^^^^^^^^ set the data type of the returned data
     cache: false,
     success: function(html){
         $("#show_div").html(html.bu);
                             ^^^^^^^ get the correct element
     }
 });

1 Comment

How can I do In this way? eg "success:function(data){ var content = ''; var data = $.parseJSON(data); $.each(data, function(i, post) { content += '<div>' + post.post_title + '</div>'; }); $(content).appendTo("#results"); }, "

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.