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

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.

Related

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.

dynamicly fill table using zpt and ajax as update

I'm creating a webproject in pyramid where I'd like to update a table every few secondes. I already decided to use ajax, but I'm stuck on something.
On the client side I'm using the following code:
function update()
{
var variable = 'variable ';
$.ajax({
type: "POST",
url: "/diagnose_voorstel_get_data/${DosierID}",
dataType: "text",
data: variable ,
success: function (msg) {
alert(JSON.stringify(msg));
},
error: function(){
alert(msg + 'error');
}
});
}
Pyramid side:
#view_config(route_name='diagnose_voorstel_get_data', xhr=True, renderer='string')
def diagnose_voorstel_get_data(request):
dosierid = request.matchdict['dosierid']
dosieridsplit = dosierid.split
Diagnoses = DBSession.query(Diagnose).filter(and_(Diagnose.code_arg == str(dosieridsplit[0]), Diagnose.year_registr == str(dosieridsplit[1]), Diagnose.period_registr == str(dosieridsplit[2]), Diagnose.staynum == str(dosieridsplit[3]), Diagnose.order_spec == str(dosieridsplit[4])))
return {'Diagnoses ' : Diagnoses }
Now I want to put this data inside a table with zpt using the tal:repeat statement.
I know how to use put this data in the table when the page loads, but I don't know how to combine this with ajax.
Can anny1 help me with this problem ? thanks in adance.
You can do just about anything with AJAX, what do you mean "there's no possibility"? Things become much cleaner once you clearly see what runs where and in what order - as Martijn Pieters points out, there's no ZPT in the browser and there's no AJAX on the server, so the title of the question does not make much sense.
Some of the options are:
clent sends an AJAX request, server does its server-side stuff, in the AJAX call success handler the client reloads the whole page using something like window.location.search='ts=' + some_timestamp_to_invalidate_cache. The whole page will reload with the new data - although it works almost exactly like a normal form submit, not much sense using AJAX like this at all.
client sends an AJAX request, server returns an HTML fragment rendered with ZPT which client then appends to some element on your page in the AJAX success handler:
function update()
{
var variable = 'variable ';
$.post("/diagnose_voorstel_get_data/${DosierID}")
.done(function (data) {'
$('#mytable tbody').append(data);
});
}
client sends an AJAX request, server returns a JSON object which you then render on the client using one of the client-side templating engines. This probably only make sense if you render your whole application on the client and the server provides all data as JSON.

Opencart addToCart receives empty response

I have opencart. function addToCart() that adds products to cart works normal on normal pages.
I made custom page where I have just button that triggers function addtoCart(). Just normal button..
On normal page(where it works) I get normal response.
Please look at this link of images:
http://imgur.com/7M1AR1B,FKjiU05,9ggmiMR#2
Third image is actually post that works OK, second picture is RESPONSE that works OK.
First picture is empty response which I get in custom page in open cart.
Do you have an idea why is this happening?
I use function addToCart() and use hard variable FOR TEST in that custom page, which means variables are always there to pass. I use hard variables so I don't have to explain how do I pass variables back in code(it works the same, it passes everything in debug). Problem is I get that "empty" response back only on custom made page. Response: [] ...
function addToCart() {
var product_id = 79;
var quantity = 1;
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + quantity,
dataType: 'json',
success: function (json) {
$('.success, .warning, .attention, .information, .error').remove();
if (json['redirect']) {
location = json['redirect'];
}
if (json['success']) {
$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('.success').fadeIn('slow');
$('#cart-total').html(json['total']);
$('html, body').animate({
scrollTop: 0
}, 'slow');
}
}
});
}
Possibilities to try
Using HTTPS to NON HTTPS or vice versa
Using www to non www domain or vice versa
Using a domain that isn't the same one as the one you're using to render the page
If none of the above are the issue, you'll need to work out what the exact differences are between the requests, though my guess is it's one of the three possibilities I've listed
The problem was, that I was adding a product without 1 needed attribute, therefore I always got empty response. There is an attribute in opencart where you have to setup to which store your product belongs. If you don't set that attribute if you are programatically adding a product into the store, you will add product, but you won't be able to add it to cart.

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

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

auto refresh jsp page when data changes

I have a JSP page which shows items included in an Array (Just a very simple list).
In the background the Array might change i.e. adds a new Item or remove one.
How can I auto refresh the page when the Array changes?
There are 2 ways that are most popular to perform such operation
pool a method that would send 1 or 0 to see if you refresh the page or not
keep asking for that data array and populate it through javascript
Option 1
create a .jsp page and call it, for example, updateList.jsp
add a single method that will check if there is more data to be filled and output 1 or 0 like: out.println(1)
in your page, and using jQuery to simplify things
$.get("updateList.jsp", function(data) {
if(data !== null && data.length > 0 && data === 1) {
// refresh this page
document.location = document.location.href;
}
});
Option 2
create a .jsp page and call it, for example, data.jsp
add a single method that will output a JSON string containing all data you need to populate the list
in your page, and using jQuery and JsRender to simplify things
$.get("updateList.jsp", function(data) {
if(data !== null && data.length > 0) {
$("#my-list").html(
$("#my-template").render(data);
);
}
});
and in your HTML you will have:
<ul id="my-list"></ul>
<script id="my-template" type="text/x-jsrender">
{{for items}}
<li>{{:name}}</li>
{{/for}}
</script>
assuming your JSON would be something like:
item: [
{ name: "Name A" },
{ name: "Name B" },
{ name: "Name C" },
]
Once the JSP has been executed, the HTML code that it has generated has been sent to the browser, and there is no connection between the browser and the JSP anymore. If you want to refresh some part of the page, you need to poll the server using AJAX, or use WebSockets to maintain a connection between the page and the server.
To refresh page silently use AJAX. Below are some examples
Example 1
Example 2
Google Search

Resources