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

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'}

Related

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

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

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;

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)

jQuery Ajax - Cant parse json?

I got a very strange problem, I thought this worked before but it doesn't any more. I dont even remember changing anything. I tried with an older jQuery library.
I got an error that says: http://i.imgur.com/H51wG4G.png on row 68: (anonymous function). which refer to row 68:
var jsondata = $.parseJSON(data);
This is my ajax function
I can't get my alert to work either because of this error. this script by the way is for logging in, so if I refresh my website I will be logged in, so that work. I also return my json object good as you can see in the image. {"success":false,"msg":"Fel anv\u00e4ndarnamn eller l\u00f6senord.","redirect":""}
When I got this, I will check in login.success if I got success == true and get the login panel from logged-in.php.
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.success(function(data)
{
var jsondata = $.parseJSON(data);
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});
Thank you.
If the response you have showed in the attached screenshot is something to go by, you have a problem in your PHP script that's generating the JSON response. Make sure that thePHP script that's generating this response (or any other script included in that file) is not using a constant named SITE_TITLE. If any of those PHP files need to use that constant, make sure that that SITE_TILE is defined somewhere and included in those files.
What might have happened is that one of the PHP files involved in the JSON response generation might have changed somehow and started using the SITE_TITLE costant without defining it first, or without including the file that contains that constant.
Or, maybe none of the files involved in the JSON generation have changed, but rather, your error_reporting settings might have changed and now that PHP interpreter is outputting the notice level texts when it sees some undefined constant.
Solving the problem
If the SITE_TITLE constant is undefined, define it.
If the SITE_TITLE constant is defined in some other file, include that file in the PHP script that's generating the response.
Otherwise, and I am not recommending this, set up your error_reporting settings to ignore the Notice.
Your response is not a valid JSON. You see: "unexpected token <".
It means that your response contains an unexpected "<" and it cannot be converted into JSON format.
Put a console.log(data) before converting it into JSON.
You shoud use login.done() , not login.success() :)
Success is used inside the ajax() funciton only! The success object function is deprecated, you can set success only as Ajax() param!
And there is no need to Parse the data because its in Json format already!
jQuery Ajax
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.done(function(data)
{
var jsondata = data;
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});

Ajax prototype to load page then update hash

I have 3 page with different concept/layout/animation.
I'm using prototype & script.aculo.us
I have this in my navigation:
<ul>
<li>PAGE1</li>
<li>PAGE2</li>
</ul>
and this is in my js:
windows.location.hash: 'web';
function showPage() {
startloading();
var url: '/localhost/page2'+web;
new Ajax.Updater('maincontent', 'page2', { method: 'get' });
finishloading();
}
the question & problem is:
Why in windows location hash is still: /localhost/page1/#page2 with or without if I use var url?
All the animation in page 2 doesn't work, because I didn't put the header, but if put I it, I got double header and still the animation won't work either.
Can anybody give me the solution?
Thank you very much.
In your code
var url: '/localhost/page2'+web;
line throws error so hash cannot be changed. Fix it to
var url = '/localhost/page2'+web;
then it should work.
The correct way to update your hash is:
window.location.hash = '#'+yourValue;
Hard to tell what exactly you're trying to do with your function but there's a few things that are clearly a bit wrong.
function showPage(var) {
startloading();
var url: '/localhost/page'+var;
new Ajax.Updater('maincontent', url, { method: 'get' });
finishloading();
}
depending on what you're actually doing its fairly likely you would probably want something more like this:
function showPage(var) {
var url = '/localhost/page'+var;
new Ajax.Updater('maincontent', url, { method: 'get' ,
onCreate: function(){
startloading();
},
onComplete: function(){
finishloading();
}
});
}
Thats complete guesswork though, if you can provide more detail i can help more.

Resources