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?

9
  • 1
    Use json_encode() to create a JSON response Commented Dec 12, 2018 at 17:13
  • Possible duplicate of Returning JSON from a PHP Script Commented Dec 12, 2018 at 17:15
  • but how to get it in client side? I am printing all data into $('#call-result').html(data); Commented Dec 12, 2018 at 17:15
  • miken32, this is not about returning json from server! Please take time and read question carefully Commented Dec 12, 2018 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. Commented Dec 12, 2018 at 17:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks miken32, Not funny gilbert!

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.