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))
– Wallace Maxters
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?
– I Wanna Know
How to be sure and how to redeem the value?
– I Wanna Know
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
– Wallace Maxters
Dude I went on Headers and it’s like ok (200) the request.
– I Wanna Know
But you must look at the
Preview
in the abinha next to the URL that appeared in Network! There shows theJSON
. If it’s empty, it’s because there’s no data to answer!– Wallace Maxters
I looked, the preview shows the html/css code...
– I Wanna Know
But do you want to return JSON or HTML in this query via ajax? If it is HTML, then you are another case!
– Wallace Maxters
I want to be able to use the result to display on the page, for example, within an html tag...
– I Wanna Know