2

I have a PHP file which is responding to a jQuery Ajax call with dataType: 'HTML',. The PHP looks like

if( $result->num_rows > 0 ){
    ....
    echo '<p>There are some user already </p>';
} 
else{
    echo '<p>List is empty </p>';
}

this is working fine on my JS side like

ajaxcall.done(function(data) {  
  $('#call-result').html(data);
});

but I also need to add some business logic on client side to the page by passing a Boolean flag from the server to the JS. How can I pass the true false along with HTML snippet from the server to client?

halfer
  • 18,701
  • 13
  • 79
  • 158
Mona Coder
  • 5,750
  • 15
  • 55
  • 103
  • 1
    Use `json_encode()` to create a JSON response – miken32 Dec 12 '18 at 17:13
  • Possible duplicate of [Returning JSON from a PHP Script](https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script) – miken32 Dec 12 '18 at 17:15
  • but how to get it in client side? I am printing all `data` into `$('#call-result').html(data);` – Mona Coder Dec 12 '18 at 17:15
  • miken32, this is not about returning json from server! Please take time and read question carefully – Mona Coder Dec 12 '18 at 17:16
  • 1
    Just parse it in your callback function. `data.result` can be your boolean and `data.html` can be your HTML, for example. I believe jQuery will automatically parse the JSON response into an object. – miken32 Dec 12 '18 at 17:16
  • @MonaCoder yes it is....if you want more data returned create an array and send as json as already mentioned. Your html can be in that array – charlietfl Dec 12 '18 at 17:17
  • but they are HTML – Mona Coder Dec 12 '18 at 17:18
  • And I read the question quite carefully enough. A duplicate is a question that has the same answer, not a question that's the same. The answer to your question is to respond with JSON. – miken32 Dec 12 '18 at 17:18
  • So what?...the html is just a string that can be manipupated just like any other string in an array or object – charlietfl Dec 12 '18 at 17:18

1 Answers1

1

Just use JSON to respond:

<?php
if ($result->num_rows > 0) {
    $html = '<p>There are some user already </p>';
    $result = false;
} else{
    $html = '<p>List is empty </p>';
    $result = true;
}
$response = ["html"=>$html, "result"=>$result];
header("Content-Type: application/json");
echo json_encode($response);

Then, in your JS:

ajaxcall.done(function(data) {
    var result = data.result;
    $('#call-result').html(data.html);
});

jQuery will automatically parse a response of type json into a JavaScript object so you can access the elements directly.

miken32
  • 35,483
  • 13
  • 81
  • 108