I am trying to make an AJAX request in my Magento 2.1.8 custom module.

The Http Post Request is returning all of the data i expect it to in JSON format, However it is also adding on some of my html code after it.

What could be causing this?

returning JSON object:

if ($result->num_rows > 0) {
            $return = [];
             while($row = $result->fetch_assoc()) {
                 $return[] = [
                    'id' => $row['id'],
                    'name' => $row['name'],
                    'created' => $row['created'],
                    'posts' => $row['posts']

             header('Content-type: application/json');
             echo json_encode($return);

HTTP Post Request:

     function(data, status){

The data being returned is correctly formatted JSON object and then goes straight into html:

[{"id":"1","name":"Tanks - Sub Ohm","created":"15-01-18","posts":"1"}]<!doctype html>
<html lang="en-GB" dir="ltr" class="ltr">
    <head >

How can i remove the HTML part?


  • share your controller file too Commented Jan 16, 2018 at 16:47

2 Answers 2


use exit will solve the problem for you

echo json_encode($return); exit;

and use proper magento 2 way for json response. Example

  • Thanks for your answer Qaisar, I found the solution to my problem. but I will also start using the way to return json response from the link you posted.
    – user61783
    Commented Jan 17, 2018 at 10:59

I found the solution to my problem by deleting:


From the execute() function inside my controller.

  • It was already mention in my last answer. Commented Jan 17, 2018 at 11:40
  • That was regarding a 404 error occuring when trying to send a http request. It was also not the correct answer as when i fixed the controller, I could still send requests even with the above code
    – user61783
    Commented Jan 17, 2018 at 11:45
  • Then your question was not clear enough. also i seen the hardcode the url simple use this <?php echo $block->getUrl('forum/get/categories'); ?> to get url Commented Jan 17, 2018 at 11:47
  • The Question clearly states that the problem I was facing was regarding the 404 error and at no point did it mention html being added to the end of the http response. The two questions I asked are different and required different solutions. Thanks for the php getUrl method, I will use that in future.
    – user61783
    Commented Jan 17, 2018 at 11:55
  • 1
    No problem dear I are not here to give correct answer everytime some wrong answer's too. Commented Jan 17, 2018 at 11:59

Your Answer

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