How do I change the default behavior of my WordPress single post URL's? - ajax

I'm trying to figure out a way to change the behavior of wordpress single post url's so that instead of loading the page using the single.php file, I can instead load the post contents into the index.php page via ajax. The site is a wordpress site, but uses ajax to load all of the content into one page. Essentially the actual php file being read never changes, and instead any time a user clicks a new page, the page content is loaded via on ajax request.
Is there any way that I could perhaps edit my .htaccess file so that when someone goes to www.mysite.com/blog/post-name that it loads index.php and tells a script to load the requested post contents into the index.php page via ajax?
Thanks!

If you already have AJAX working in your index.php file, then:
A couple of thoughts. On your server, you could delete the single.php file and create a symlink to the index.php file:
for *nix (including os x):
ln -s index.php single.php
or within the single.php file, you could delete everything and include index.php:
<?php include('index.php'); ?>
Controlling whether or not this loads via AJAX would need to be done on your client.
Or do you not have AJAX working at all yet? If not, then the answer would be slightly more complex. Here's how I setup AJAX with my wordpress sites:
On the server, I use the JSON API wordpress plugin to easily be able to provide content via AJAX (in JSON format).
On the client, you can use jQuery to capture any links to wordpress and run them through AJAX instead. I am copying some code here that retrieves a list of recent posts from a server in a different domain (so I'm using JSONP instead of straight JSON). You can see the JSON API documentation on how to modify this to just get a single post.
jQuery(function($) {
$('a').click(function(event) {
$('body').css('cursor', 'wait');
event.preventDefault(); // this prevents the regular behavior of clicking a link
$.ajax({
type:'GET',
url:url,
async:false,
jsonpCallback:'jsonCallback',
contentType:"application/json",
data: {
json: 'get_recent_posts',
count: 10,
page: page + 1
},
dataType:'jsonp'
}).always(function(){
jQuery('body').css('cursor', 'auto');
}).done(function(json) {
$.each(json.posts, function(index, value) {
tags = [];
$.each(value.tags, function(index, value) {
tags.push('' + value.title + '');
});
html =
'<div>' +
'<header class="entry-header">' +
value.title +
'<br>' +
value.date +
'</header>' +
'<div class="entry-content">' +
value.content +
'</div>' +
'</div>' +
'<span class="labels_label">'+
'Labels: ' +
'</span>' +
'<span class="labels">' +
tags.join(', ') +
'</span>' +
'<hr>';
$('.full-width .content').append(html);
});
});
});

Related

How to get content with ajax from an admin page to all content pages?

I want to get content using ajax from an admin page and append it to all content pages on right hand side.
I have this script:
$.ajax({
url: '/Quicklinks-Content-Admin',
type: 'GET',
success: function(data) {
var quicklinks_list = [];
$('.content-inner .blogentries ul li').each(function (i, v) {
v = $(v);
quicklinks_list.push({
text: $('.blogBody a', v).text().trim(),
href: $('.blogBody a', v).attr("href"),
bg: $(v).find('.sws-inline-content img').attr('src')
});
console.log(i);
console.log(quicklinks_list[i].text);
console.log(quicklinks_list[i].href);
console.log(quicklinks_list[i].bg);
$(".quicklinks-inner").append('<div class="right-quicklink ql' + i + '"><div class="quicklink-inner"><div class="quicklink-title">' + quicklinks_list[i].text + '</div><div class="background-cover"></div></div></div>');
$('.ql'+ i +' .background-cover').css("background-image", 'url("' + quicklinks_list[i].bg + '")');
$(".quicklink-title a").html(function(index, old) {
return old.replace(/(\b\w+)$/, '<span class="lastWord">$1</span>');
});
});
}
});
With this script I extract the content from a blog list from "/Quicklinks-Content-Admin" page which is a link in two variable (text and href) and one more variable for the image. After this I want to insert the content from variables to all content pages.
Actually, that script insert the content just for that admin page, instead to put it on every single page.
Why does it happen and how to solve the problem ?
AJAX is just a procedure for sending data from/to the current webpage to a back-end PHP (or aspx etc) file.
If the transmitted data should be remembered (for example, to update other pages), then you can store it in a database and refactor the other pages to read from the database for data when constructing each of those pages.
If you require the AJAX data to be added to other areas on the same page as the AJAX routine, for example in sidebar sections that are $.load()ed when the page is constructed, just use javascript to update those areas. Or, use javascript to call another $.load() of the data into that div.
Regardless how you do it, you will either use javascript to update an area on the page you are on, or you will store the data on the server (usually using a database, but you can also use a server-side file) and make the other PHP pages read that stored information when building their pages.

Ajax call locally in jQueryMobile and Phonegap, JSON objects

I have very simple jQueryMobile application. I want to submit a form and to call ajax. On my desktop PC this works fine and looks like this:
application on my PC
When i press the button "Save" the text below appers. The HTML code for the interface is in the script accountAdd.html. At my PC It works as expected, but i need this app for my mobile device. Here is the screenshot from my device when i try to do the same thing that is showed at the first figure.
application on my mobile device
So here is the part of the script that calls ajax.
accountAdd.html
<script>
$( document ).ready(function() {
$(document).on('submit', '#formDetails', function() {
var theName = $("#accountName").val();
if($('#accountName').val().length > 0) {
$.ajax({
url: 'accountAdd.php',
data: $('#formDetails').serialize(),
type: 'post',
dataType: 'json',
timeout: 5000,
success: function (result, status) {
$("#resultLog").html("accountName: " + result.accountName);
},
error: function (request,error) {
alert('Network error has occurred please try again! Error: ' + error);
}
});
} else {
alert('Please fill all necessary fields');
}
return false;
});
});
</script>
.
.
.
HTML code
Here is my other script that contains code that is executed in back-end.
accountAdd.php
<?php
header('Access-Control-Allow-Origin: *');
$return['accountName'] = $_POST['accountName'];
$return['accountType'] = $_POST['accountType'];
$return['accountBalance'] = $_POST['accountBalance'];
$return['accountDate'] = $_POST['accountDate'];
echo json_encode($return);
?>
So the ajax call on my mobile device is not working as expected and as you can see at the second figure is giving parseerror. The code is completely the same at both devices. I'am converting the scripts with phonegap. I think that the problem is related with JSON objects (I think that ajax call in phonegap need to pass JSON obejects but I'm not sure). I need help, how to modify the code, so that can work at the PC and at my mobile device at the same time.
Ok, you have <access origin="*"/> so it is not a CORS issue.
I think maybe your problem is that you do not set the datatype to json in your php but expect it in the javascript side. Try adding the following line in your php file :
header('Content-Type: application/json');
Edit
I see the url to your php uses local path (should have noticed earlier but didn't know if you removed the server address on purpose), so it seems you put the .php files in the phonegap app.
That is not how it works. Either you need to do things locally and you do it in javascript, or you want to communicate with a server and you
do not put any php page in the www folder of your local page
provide the url of your server to each ajax calls.
Make sure your config.xml file is in the same folder as your index.html file and then use the (Or whatever domain you are on)

Ajax username and date Instagram API

Currently, I'm trying to create a page using instagram's api, showing recent pictures with a specific tag, as well as the user who posted it and the date posted. I'm also trying to have the infinite loading functionality, with ajax loading in more instagram posts as the page reaches the bottom.
Heres a link to the live site http://www.laithazzam.com/work/nukes/indexnew.php
Clicking the red yes will skip the video, and go straight to the instagram feed.
I'm currently using Christian Metz's solution found here, https://gist.github.com/cosenary/2961185
I am also having an issue with posting the date, in the first initial load, as well in the ajax loads. I was previously able to use this following code, before trying to implement Christian's php/ajax solution.
var date = new Date(parseInt(data.data[i].created_time) * 1000);
<p class='date'>"+(date.getMonth()+1)+"/"+date.getDate()+"/"+date.getFullYear()+"</p>
I guess what I don't understand, is how the ajax loading function, is actually functioning. How would I also pull the name, and date through the ajax loading success function as well?
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
tag: tag,
max_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$("#instafeed").append('<img src="' + src + '">');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
The data parameter of the success handler function is populated from whatever JSON ajax.php returns and the structure will match accordingly. It looks like the images attribute of that object only has an array of URLs for the images and no other data.
You'll need to update this section of the PHP script to return more than just the array of URLs for the images and also include the additional data retrieved from the Instagram API.
Try updating the last part to this:
echo json_encode(array(
'next_id' => $media->pagination->next_max_id,
'images' => $media->data
));
Then you'll have full access to all the media data, not just the URL.

jQuery Ajax Request - Lose Method

I have a page index.php that uses a modal to upload files. After those have uploaded I use the following to update my database and load in the new images to a list.
$('#sortableImages').load('../includes/sortImages.php?edit=' + edit);
Executes:
<script type="text/javascript">
$(document).ready(function(){
$(function() {
$("#sortableImages ul").sortable({
opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable("serialize") + '&action=updateRecordsListings';
$.post("../albumUploader/queries/sort.php", order);
}
});
});
});
</script>
echo "<ul class='revisionList'>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sortImageName = $row['OrgImageName'];
$sortPath = "../data/gallery/" . $getGalleryID . "/images/album/" . $sortImageName;
echo "<li class='sortPhotos' id='recordsArray_{$row['id']}' >";
echo '<img src="'. $sortPath .'"/>';
echo "</li>";
}
echo "</ul>";
The images populate in a div #sortableImages on the index page. However it seems that I lose my method of sortable() from the js file that was originally loaded in the index.php or after the ajax request it's not reading the js. What am I missing here?
Thanks a million.
When you load script from a remote page using ajax, it is important to realize that the ready event has already occured in page you are loading into.
This means that code wrapped in $(function(){}) will fire as soon as it is received. If that code preceeds the html it refers to, it will not find that html, as it doesn't exist yet.
If you move the same code below the html it refers to, it will fire after the html exists and therefore will find it.
EDIT: My answer presumes that all the code shown after "Executes:" in OP is contained in remote page
You have no handler for the result of the sort.php. Invoking this will only load the data into cache.
You need a complete handler function to refresh the data, not to mention add it to the dom. You should clarify your question and make it obvious that those are two different pages.
$.post("../albumUploader/queries/sort.php", order).complete = func...

Issue with wrong controller being called in jquery ajax call

My issue is for some strange reason it seems stuck in the page controller so instead of getting out and going into the ajax controller I have it trying to go down that route in the page controller
1st try
http://localhost:2185/Alpha/Ajax/GetBlah_Name/?lname=Ge&fname=He
2nd try
http://localhost:2185/Patient/~/Ajax/GetBlah_Name/?lname=Ge&fname=He
Objective
http://localhost:2185/Ajax/GetBlah_Name/?lname=Ge&fname=He
Page button to call jquery
<a style="margin-left: 310px;" href="javascript:void(0)" onclick="getBlah()"
class="button"><span>Lookup</span></a>
Jquery code
1st try
{
$.getJSON(callbackURL + 'Ajax/GetBlah_Name/?lname=' + $('#Surname').val() + '&fname=' + $('#FirstName').val(), null, GetResults)
}
2nd try
{
$.getJSON(callbackURL + '~/Ajax/GetBlah_Name/?lname=' + $('#Surname').val() + '&fname=' + $('#FirstName').val(), null, GetResults)
}
In summary I don't know why it won't break out of the controller and go into the Ajax controller like it has done so in all the other projects I've done this in using the 1st try solution.
It seems you want to cal a controller at ~/Ajax. Is it? If yes, you should use this code:
$.getJSON(callbackURL + '/Ajax/GetBlah_Name/?lname=' + $('#Surname').val() + '&fname=' + $('#FirstName').val(), null, GetResults)
UPDATE:
This will work for your Q, but the complete solution is #Darin Dimitrov's answer. I suggest you to use that also.
UPDATE2
~ is a special character that just ASP.NET works with it! So http doesn't understand it. and if you start your url with a word -such as Ajax-, the url will be referenced from where are you now (my english is not good and I can't explain good, see example plz). For example, you are here:
http://localhost:2222/SomeController/SomeAction
when you create a link in this page, with this href:
href="Ajax/SomeAction"
that will be rendered as
http://localhost:2222/SomeController/Ajax/SomeAction
But, when url starts with /, you are referring it to root of site:
href="/Ajax/SomeAction"
will be:
http://localhost:2222/Ajax/SomeAction
Regards
There are a couple of issues with your AJAX call:
You are hardcoding routes
You are not encoding query string parameters
Here's how I would recommend you to improve your code:
// Always use url helpers when dealing with urls in an ASP.NET MVC application
var url = '#Url.Action("GetBlah_Name", "Ajax")';
// Always make sure that your values are properly encoded by using the data hash.
var data = { lname: $('#Surname').val(), fname: $('#FirstName').val() };
$.getJSON(url, data, GetResults);
Or even better. Replace your hardcoded anchor with one which will already contain the lookup url in its href property (which would of course be generated by an url helper):
<a id="lookup" href="Url.Action("GetBlah_Name", "Ajax")" class="button">
<span>Lookup</span>
</a>
and then in a separate javascript file unobtrusively AJAXify it:
$(function() {
$('#lookup').click(function() {
var data = { lname: $('#Surname').val(), fname: $('#FirstName').val() };
$.getJSON(this.href, data, GetResults);
return false;
});
});
Now how your urls will look like will totally depend on how you setup your routes in the Application_Start method. Your views and javascripts are now totally agnostic and if you decide to change your route patterns you won't need to touch jaavscript or views.

Resources