Ajax prototype to load page then update hash - ajax

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.

Related

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!

Parse, JS Updates in Real Time

I have the following code, where I have a myBool (a boolean) in my Data Browser initially set to false,
however sometime while I'm still viewing my page I have code set to turn it to true.
How can I make a real time update that will automatically hide my #div when myBool turns to true?
var myBool = currentUser.get("myBool");
if(myBool) {
$('#div').hide();
}
I did some research and found that the Parse.Cloud.afterSave() function may be useful, but I don't see how it will update the content automatically?
Hope I've been clear!
Thanks.
Edit:
Possibly something like this in my main.js?
Parse.Cloud.afterSave("setBool", function() {
var query = new Parse.Query(Parse.Installation);
query.equalTo('myBool', true);
Parse.Push.send({
where: query,
}, {
success: function() {
$('#div').hide();
},
error: function(error) {
$('#div').show();
}
});
});
Your problem with your afterSave function is that your calling it for a function rather than a class.
AfterSave is called after an object from a certain class is saved. If your bool
Parse.Cloud.afterSave(Parse.Installation, function(request) {
// Send push here, use request to target correct user
});
Additionally your push listener should be the one modifying the divs, not the CloudCode.

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;
});

Clear IE cache when using AJAX without a cache busting querystring, but using http response header

I'm having the classic IE-caches-everything-in-Ajax issue. I have a bit of data that refreshes every minute.
Having researched the forums the solutions boil down to these options (http://stackoverflow.com/questions/5997857/grails-best-way-to-send-cache-headers-with-every-ajax-call):
add a cache-busting token to the query string (like ?time=[timestamp])
send a HTTP response header that specifically forbids IE to cache the request
use an ajax POST instead of a GET
Unfortunately the obvious querysting or "cache: false" setting will not work for me as the updated data file is hosted on Akamai Netstorage and cannot accept querystrings. I don't want to use POST either.
What I want to do is try send an HTTP response header that specifically forbids IE to cache the request or if anyone else knows another cache busting solution??
Does anyone know how this might be done? Any help would be much appreciated.
Here is my code:
(function ($) {
var timer = 0;
var Browser = {
Version: function () {
var version = 999;
if (navigator.appVersion.indexOf("MSIE") != -1) version = parseFloat(navigator.appVersion.split("MSIE")[1]);
return version;
}
}
$.fn.serviceboard = function (options) {
var settings = { "refresh": 60};
return this.each(function () {
if (options) $.extend(settings, options);
var obj = $(this);
GetLatesData(obj, settings.refresh);
if (settings.refresh > 9 && Browser.Version() > 6) {
timer = setInterval(function () { GetLatestData(obj, settings.refresh) }, settings.refresh * 1000);
}
});
};
function GetLatestData(obj, refresh) {
var _url = "/path/updated-data.htm";
$.ajax({
url: _url,
dataType: "html",
complete: function () {},
success: function (data) {
obj.empty().append(data);
}
}
});
}
})(jQuery);
Add a random number to the GET request so that IE will not identify it as "the same" in its cache. This number could be a timestamp:
new Date().getTime()
EDIT perhaps make the requested url:
var _url = "/path/updated-data.htm?" + new Date().getTime()
This shouldn't cause any errors I believe.
EDIT2 Sorry I just read your post a bit better and saw that this is not an option for you.
You say "is hosted on Akamai and cannot accept querystrings" but why not?
I've never heard of a page that won't accept an additional: "?blabla", even when it's html.
This was driving me crazy. I tried many cache busting techniques and setting cache headers. So many of these either did not work or were wild goose chases. The only solution I found which tested to work correctly was setting:
Header Pragma: no-cache
I hope it saves others with IE headaches.

Resources