How to use the "Answer" of an XMLHTTPREQUEST in Cakephp (2.5)

Asked

Viewed 419 times

1

CONCLUSION: I put it up here to get a quick look, I was using onClick to get this function, but I was leaving the request(request) out of function so it wasn’t working.

I have an action in the Posts controller:

                 public function pega($id = null)
                 {                      

                 $posts = $this->Post->findById($id);

                  foreach($posts as $pok)
                  {
                            $foda = $pok['love'];
                  } 

                  $this->set('foda', $foda);

                  $this->set('_serialize', array('foda'));

                }

In my layout I try to make a request to take the data of the function "take" and put inside an html tag:

<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:81/cakephp/posts/pega/<?php echo $post['Post']['id'];?  >.json";

xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 

var out = JSON.parse(xmlhttp.responseText);
 function loap (){ 
 var arr = out[0];
document.getElementById("id01").innerHTML = arr;
}

}

}
xmlhttp.open("GET", url, true);
xmlhttp.send();

Added:

This should only occur when a button is clicked:

 <button type="button" onClick="loap()"> Checa </button>

The script became so:

<script>

var x = new XMLHttpRequest();
var url = "http://localhost:81/cakephp/posts/pega/
                  <?php echo $post['Post']['id'];?  >.json";

//Eu tenho que criar a variável url porque preciso passar um id através do link...    

x.open("GET", url, true);
x.send();

var response = null;

x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
   response = JSON.parse(x.responseText); 

}

function loap(){
       document.getElementById("id01").innerHTML = response[0];    
}

</script>
  • I’d do it this way: return $this->response->body(json_encode($meuArray))

  • I tried several ways, including similar ones, but how to know that what came out of my action turned xmlhttp.responseText there on the other side?

  • How to be sure and how to redeem the value?

  • Give a F12 on google Chrome, click on the "network" tab. Choose the XHR tab and see if any responses will appear in the url you are sending the ajax action after refreshing the page

  • 1

    Dude I went on Headers and it’s like ok (200) the request.

  • But you must look at the Preview in the abinha next to the URL that appeared in Network! There shows the JSON. If it’s empty, it’s because there’s no data to answer!

  • I looked, the preview shows the html/css code...

  • But do you want to return JSON or HTML in this query via ajax? If it is HTML, then you are another case!

  • I want to be able to use the result to display on the page, for example, within an html tag...

Show 4 more comments

1 answer

2


Let me give you a little example of how I used to use

Controller of Cakephp

class JsonController extends AppController
{


    public function teste()
    {
        $this->autoRender = false;

        $json = json_encode(array('nome' => 'StackOverflow'));

        $this->response->type('application/json');
        $this->response->body($json); // json retornado {"nome" : "StackOverflow"}          
    }


}

Javascript:

var x = new XMLHttpRequest
x.open('GET', 'json/teste', true)
x.send();

var response = null;

x.onreadystatechange = function() {
if (x.readyState == 4) {
   response = JSON.parse(x.responseText)
}

}

Updating

Based on your code, I can imagine you want the following:

 public function pega($id = null)
 {                      

    $posts = $this->Post->findById($id);

    $this->response->type('application/json');

    return $this->response->body(json_encode($posts));

}

In HTML

    var x = new XMLHttpRequest
    x.open('GET', 'json/teste', true)
    x.send();

    var response = null;

   var divQuerQueroImprimirOsValores = document.getElementById('ondeVouImprimir')

    x.onreadystatechange = function() {
    if (x.readyState == 4) {
       response = JSON.parse(x.responseText)

       for (key in response) {

           divQuerQueroImprimirOsValores.innerHTML += response[key]    

       }
    }
  • Isn’t $this->autoRender= false; ? It’s because I read about using serialize to do this, but I couldn’t put it into practice. I’ll see this example of yours and get back to you.

  • I’m going to make a small change to this part. Is that, in my case, my controller is only for JSON

  • The autoRender is now within the :) method, so only this method will not use view

  • Why didn’t you use "var" before x? I’m trying with your example but I couldn’t.

  • Wait! If you want to return HTML, it will be an error! If it is JSON, it should work.

  • I want to show the result inside an html tag...

  • I did it this way, tried to change a lot of things and nothing. Detail: this should only work if a button is clicked, so I put onClick on the button and made a function, but it went wrong.

  • Have you looked at the console to see if any errors occur?

  • I looked, there’s nothing indicating error.

  • I’m guessing it’s not programming error but some wrong configuration.

  • thanks for the help and attention! I’m forgetting to put the request as part of the function I call on onClick, so it didn’t work.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.