user2129623
user2129623

Reputation: 2257

Getting value from file called by ajax request using json

This file is called by ajax request. And result coming here I want to place into two different in calling function.

<?php


//Some processing gives $text 
$s=nl2br($text);

        $data['x'] = $p;
        $data['y'] = $q;

//Start from here

    echo "<b>Positive count : $x with $p % </b>";  echo "</br>";
    echo "<b>Negative count  : $y with $q % </b>"; echo "</br>";
    echo "</br>";
    echo "Page content : ";
    echo "</br>";
    echo "</br>";
    echo $s;
//End. This content should be place in <div1>. Want to send this as a json string

and

//Start from here
    echo "First 5 post";
    $result = mysqli_query($con,"select post from facebook_posts where p_id >  (select MAX(p_id) - 5 from facebook_posts)");
    while ($row = $result->fetch_array(MYSQLI_ASSOC))
    {
      echo $row['post'];
      echo '<br/>';
    }
//End. This content should be placed in <div2> Want to send this as a json string

If there is single variable then we can easily do it using :

$resultArray = array("resultOne" => $result1,"resultTwo" => $result2);
echo json_encode($resultArray);

at receiving end:

document.getElementById("myFirstDiv").innerHTML=xmlhttp.responseText.resultOne;
document.getElementById("mySecondDiv").innerHTML=xmlhttp.responseText.resultTwo;

But how above complex result could be place into to json variable?

Upvotes: 1

Views: 92

Answers (1)

Aletheios
Aletheios

Reputation: 4020

You could use output buffering in PHP:

ob_start();
// Generate content for div 1...
$div1 = ob_get_clean();

ob_start();
// Generate content for div 2...
$div2 = ob_get_clean();

$result = array("div1" => $div1, "div2" => $div2);
echo json_encode($result);

Upvotes: 1

Related Questions