1

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:

$.post("https://www.mywebsite.co.uk/forum/get/categories",
     function(data, status){
       console.log(data);
     });

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 >
        <script>............

How can i remove the HTML part?

Thanks.

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

2 Answers 2

0

use exit will solve the problem for you

echo json_encode($return); exit;

and use proper magento 2 way for json response. Example

1
  • 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
    Jan 17, 2018 at 10:59
0

I found the solution to my problem by deleting:

        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();

From the execute() function inside my controller.

5
  • It was already mention in my last answer. 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
    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 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
    Jan 17, 2018 at 11:55
  • 1
    No problem dear I are not here to give correct answer everytime some wrong answer's too. Jan 17, 2018 at 11:59

Your Answer

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