How $http.get should work, I always get from PHP nothing right as answer - ajax

As I wrote in the title, I can't obtain any right answer from PHP. Anyone has any idea?
Javascript
var app = angular.module("appMovies", []);
app.controller("listMovies", ["$scope", "$http", function($scope, $http){
getMovies($http);
}]);
function getMovies(_http){
_http.get("movies.php", {data:{"getList":"LISTA"}})
.success(function(data, status, header, config){
console.log( data );
})
.error(function(data, status, header, config){
//console.log(data, status, header, config);
});
}
PHP
var_dump( file_get_contents("php://input") );
So, I got it... sorry my bad. Obviously $_GET fetch the data only from URL, so I should write
$http.get("movie.php/?getList=LISTA")...

It looks like you're mixing GET and POST requests. To use GET with Angular/PHP, you'll need to use params (query string parameters) instead of data (for POST bodies), and _$GET on the server (for query string parameters) instead of file_get_contents("php://input") (which gives POST body).
So in the browser, something like
_http.get("movies.php", {params: {"getList":"LISTA"}})
and on the server
var_dump($_GET);

Try it on another way:
$http.post("movies.php", {data: {"getList": "LISTA"}}).
success(function (_data, _status) {
})
.error(function (_data, status) {
});
And in your PHP-Code you can use then:
$postData = file_get_contents("php://input");
$request = json_decode($postData);
$request->_data;

Related

How can I save a response of HTTP GET Request in variable?

Here is my API code
#GetMapping("/api/test")
public String test() {
return "hello";
}
Then I will send request to this API by using ajax.
function test() {
$.ajax({
type: "GET",
url: "/api/test",
success: function(response) {
}
})
}
I want to save the value of ajax call response (In this case "hello") in variable. Please let me know how to do it.
Several ways of doing it !
As far as only a String message is concerned you can just store it like below
`var myResponse=response;`
Alternatively, you can also access values if response is an object (JSON reponse I mean)
for e.g. `var resp=response.message; //Assuming message is a key in response JSON`
For testing, use alert(response) or console.log(response) to see how your response is coming and manipulate accordingly !
Feel free to refer this link for detailed Ajax walkthrough https://www.tutorialspoint.com/jquery/jquery-ajax.htm
Hope these helps!

ValidateAntiforgeryToken failure

I'm facing problem of AntiforgeryToken verification.
I'm sending data like this:
var data = {
__RequestVerificationToken: '#GetAntiXsrfRequestToken()',
Id: id,
ResolverGID: resolverGID
};
I'm using fetch method to send POST data
return fetch(fetchURL, JSON.stringify(data))
.then(async (response) => {
return response.json();
})
.catch(() => {
return false;
});
and sent data looks like this:
Id: 98
ResolverGID: "XXXX"
__RequestVerificationToken: "CfDJ8EaAHBfZaBJBuxJJzC77RytBbhcw-gV2E_x0mfFVVhCy0BSmE9L5w5jzIW-7CrY_pCClHed5Ez6D3vuDj5rWWyoKr90MSOu-uBMGUuoF9iIXQ9y4vUjY_sxa5fghGEo-Xcp5KC541aGD407Fz9D9itZMeID5jqRv61IRINTSwJH_2yRvgg-BC1cDAriut22Oyw"
but my method returns error 400: Bad request.
When I use [IgnoreAntiforgeryToken] instead of [ValidateAntiForgeryToken] attribute it works, but with antiforgery token validation it does not work.
When I use the same token function in modal window to send data it's ok, no problem occurs...
can somebody help me?
Thanks
Maybe I have found the solution to this.
[ValidateAntiForgeryToken] works only when FormData format is sent, so I had to send data like this:
let data = new FormData();
data.append('Id', id);
data.append('ResolverGID', resolverGID);
data.append('__RequestVerificationToken', '#GetAntiXsrfRequestToken()');
and then it works as expected.

How can I print_r an array from controller while an ajax process?

I am trying to debug my AJAX call to database.
But there is no way to see the data i am using. I have tried to do it inserting some Javascript:
I also tried to use print_r, but nothing happens.
Is there any way to see my variables? A developer tool for example, or any command i could use.
Thanks for your help.
function console_log( $data ){
echo '<script>';
echo 'console.log('. json_encode( $data ) .')';
echo '</script>';
}
This is my controller code:
public function searchEvents(){
$request = Request::createFromGlobals();
if($request->getMethod()=='POST') {
$value = $request->request->get('searchBox');
$em=$this->getDoctrine()->getManager();
$searchFor = $request->request->get('value');
$qb = $em->createQueryBuilder();
//$eventos = $em->getRepository('App:Evento')->findBy(array('title'=>'Invi Chuwi'));
$query = $em->createQuery('SELECT e FROM App:Evento e WHERE e.title LIKE :value');
$query->setParameter('value', '%'.$searchFor.'%');
$eventos = $query->getResult();
/*$qb->select('u')
->from('App:Evento','u')
->where(('u.title = '.$searchFor));
$query = $qb->getQuery();
$eventos = $query->getResult();*/
$response = [];
foreach($eventos as $evento){
array_unshift($response,[
$evento->getTitle(),
$evento->getFecha()
]);
print_r($response);
}
$respuesta = new JsonResponse();
$respuesta->setData(
array('response'=>'success',
'eventos'=>$response)
);
}
return $respuesta;
}
And my js code:
function searchForEvents(value){
$.ajax({
method:"POST",
data: value=2,
url:"{{ path('searchEvents') }}",
dataType:'json',
success: function(data){
//var results = JSON.parse(data.events);
alert(JSON.stringify(data, null, 4));
//putEvents(results);
}
})
}
I assume you use Symfony 4+ If this case you need to install Symfony Profiler and Var Dumper packages (https://symfony.com/doc/current/profiler.html - https://symfony.com/doc/current/components/var_dumper.html). When install that two bundle you need change print_r functions to dump function. After you do that profiler package record all your request. You can access profiler data to "_profiler" route (example: http://localhost:8000/_profiler/ or something like that).
Please notice that the browser will show you the direct link to profiler inside the headers of the request, here is an example:
The way you send your AJAX request is invalid. Change it to:
function searchForEvents(value){
$.ajax({
method:"POST",
data: {value: 2},
url:"{{ path('searchEvents') }}",
dataType:'json',
success: function(data){
//var results = JSON.parse(data.events);
alert(JSON.stringify(data, null, 4));
//putEvents(results);
}
})
}
This will still not pass searchbox, but hopefully this is enough to figure that out as well. If not, then please add more details.
As about debugging the data, you can always use the good old echo var_dump and see what it puts into your request response in the network tab of dev tools or you can do it the Symfony way, logging it into a file.
Not sure if I understand you question correctly, but AJAX requests have to be debugged separately using symfony developer toolbar or by peeking request in browsers dev tools → Network tab. You can also check var/log/dev.log

$http.get works, $http.post doesn't

So, I have this really simple snippet in a controller where I get data from an external file using $http.get, and it works great! But when I use $http.post, I get a "syntaxerror: unexpected token < at object.parse(native)" in my console.
I've included both versions below with the working $http.get commented out.
var blogCtrl = angular.module('blogCtrl', []);
blogCtrl.controller('articleCtrl', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
//$http.get('/angular_blog/assets/php/ajaxRequests.php?action=fetchSingleArticle&permalink='+$routeParams.articlePermaLink)
$http.post('/angular_blog/assets/php/ajaxRequests.php', {action: 'fetchSingleArticle', permalink: $routeParams.articlePermaLink})
.success(function(data) {
$scope.articleTitle = data.articleTitle;
$scope.articleAuthor = data.articleAuthor;
$scope.articleContent = data.articleContent;
$scope.publishDate = data.publishDate;
$scope.category = data.category;
$scope.categoryPermaLink = data.categoryPermaLink;
});
}]);
I already tried the suggestion in this question, but it gave the same result.
I figured it was better to make my PHP-file understand a json post request, so instead of trying to grab strings with $_POST['string'], do this:
$obj = json_decode(file_get_contents('php://input'));
and then when I want to use strings from the request:
$obj->{'string'}

Wordpress: Use AJAX to get the next post

After looking through the jQuery documentation and many stackexchange community forums, I am still faced with this problem. Taking little bits from here and there have helped me get this far, but I am stuck where I am now.
Im using an ajax request to try and load the next post after the one that is currently displayed. The only issue I run into is when I try to execute the method included in my php file:
<?php
echo getnext();
function getnext(){
$post = get_post($_POST['id']);
$prevPost = get_previous_post();
return $prevPost->post_content;
}
?>
I can echo the POST variable that is being passed in fine, but once I try to actually call the method I get a 500 internal Server Error.
My AJAX request looks like this:
setTimeout(function (){
$currid = $('#post_id').val();
$.post("wp-content/themes/stargazer/populate.php",
{
"id":$currid
},
function(data){
//$("#academiccontent").html(data);
alert (data);
});
$('#academiccontent').animate({ 'opacity': 1 });
}, 1000);
Any help would be greatly appreciated, Ive been stuck on this for a long while now.
Thanks!!
Why don't you use AJAX directly in WordPress?
The best way is add to function.php file in your theme something like this:
add_action( 'wp_ajax_getnext', 'getnext' );
function getnext() {
$post = get_post($_POST['id']);
$prevPost = get_previous_post();
return $prevPost->post_content;
die(); // this is required to return a proper result
}
And your javascript change to this:
setTimeout(function (){
$currid = $('#post_id').val();
var data = {
"action": "getnext",
"id":$currid
};
$.post(ajaxurl, data,
function(data){
alert (data);
});
$('#academiccontent').animate({ 'opacity': 1 });
}, 1000);
More info about AJAX in WordPress you can find here: http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

Resources