Wordpress: Use AJAX to get the next post - ajax

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)

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

Updating documents of mongodb using react nodejs and ajax

Hii I started practicing react and mongodb with nodejs.
By using react I get the data with the help of nodejs...
Now I am trying to update or delete documents of mongodb with the help of nodejs....
I wrote services for them in nodejs but I am not getting any clue of how to connect it with React.
Plz help me to overcome this problem.
Thanks in advance...
If you go to the react website, and look at their tutorial they have a great example of a ajax call done.
Basically you write your ajax function first so it might look something like this if it is a GET request :
your nodejs code:
//the route we get our users at is allUsers
app.get('/allUsers, function(req, res) {
User.find({}, function(err, userarray) { //we grab all users from our mongo collection, and that array of users is called userarray
res.json(userarray); //we return the json with it
});
});
Now for the react part:
var Users = React.createClass({
getUsers : function() { //we define a function for getting our users
$.ajax({ //call ajax like we would in jquery
url: '/allUsers', //this is the url/route we stored our users on
dataType: 'json',
success: function(data) { //if we get a Success for our http get then..
this.setState({user:data}); //set the state of our user array to whatever the url returned, in this case the json with all our users
}.bind(this),
error: function(xhr, status, err) { //error logging and err tells us some idea what to debug if something went wrong.
console.log("error");
console.error(this.props.url,status, err.toString());
}.bind(this)
});
},
getInitialState: function() { //setting our initial state for our user array we want to use in our react code
return {
users: [], //initialize it empty, or with whatever you want
}
},
componentDidMount : function() {
this.getUsers(); //we are invoking our getUsers function here, therefore performing the ajax call
},
render : function() {
return(
//do what we want to do with our array here I guess!
<div>
<PrintArray users = {this.state.users} />
</div>
)
}
});
//Our new Class called Printarray
var PrintArray = React.createClass({
render : function() {
//Psuedocode
return(
ul {
this.props.users.map(function(user){ //we are mapping all our users to a list, this.props.users is inheritance what we passed down from our Users class
return (
<li key = user.id> user.name </li>
)
})
)
}
</ul>
});
And then finally just call our main class,
React.render(<Users />,
document.getElementById(domnNode)); //your div's id goes here
I commented out the code, if you have anymore questions feel free to ask! I don't know if you wanted to do a post method either, but its similar. You just change the GET to a POST, and instead of the function having no parameters, you most likely want a parameter for it, so it might be something like :
sendNewUser : function(data) {
//do ajax post stuff here
}
and in render:
render : function(){
sendNewUser(blah);
}
except you would probably have a form or something or even another class that deals with adding a new user. The question seemed really broad so I just gave a general overview of how I would do it!

How get something from Parse.com database?

How show something from parse.com data base ? Give me code please. I just only sturted learning js. For example how show all users. Or how show information about one user. Help please )
Hi I would suggest you to start learning parse ans JS with all the proper documentation provided. Documentations
If you are looking for a simple example using Parse and JS, take a look at the below code,
myObject.fetch({
success: function(myObject) {
// The object was refreshed successfully.
},
error: function(myObject, error) {
// The object was not refreshed successfully.
// error is a Parse.Error with an error code and message.
}
});
Or you can refer to the below example also, where we can make use of handlebar.js to display each blog object.
$(function() {
Parse.$ = jQuery;
// Replace this line with the one on your Quickstart Guide Page
Parse.initialize("KEYS", "KEYS");
// Your Parse application key
var Blog = Parse.Object.extend("Blog");
var Blogs = Parse.Collection.extend({
model: Blog
});
var blogs = new Blogs();
blogs.fetch({
success: function(blogs){
console.log(blogs);
var blogsView = new BlogsView({ collection: blogs });
blogsView.render();
$('.main-container').html(blogsView.el);
},
error: function(blog, error){
console.log(error);_
}
});
var BlogsView = Parse.View.extend({
template: Handlebars.compile($('#blogs-tpl').html()),
render: function(){
var collection = { blog: this.collection.toJSON() };
this.$el.html(this.template(collection));
}
});
});

NodeJS unable to response.write to the browser when there is delay in callbacks

i'm using simple MVC structure by Nathan Broslawsky. i have these code below.
ArticleProviderDBController.prototype.Show = function(data) {
//Init Model
var res = this.Response;
var model = this.getModel();
var view = this.getView("ArticleProviderDB");
model.findAll(function(error, article_collections){
if( error ) console.log(error);
view.renderGH(res, data, article_collections); //this will actually call the renderGH function to serve a html file with data from DB but it is not working.
res.write('inside callback'); //this will not.
//res.end();
});
//console.log(_self.Response);
res.write('outside callback'); //this will be shown on my browser.
//res.end();
}
actually i try to follow what people have done using expressjs
app.get('/', function(req, res){
articleProvider.findAll( function(error,docs){
res.render('index.jade', {
locals: {
title: 'Blog',
articles:docs
}
});
})
});
but seems like it is not working.
i also saw a post NodeJS response.write not working within callback posted recently but his solution is not working for me. My main objective is to use simple MVC structure created with Nodejs without the use of other templates such as expressjs to serve html with DB query. thank you.

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