I am trying to implement a hit counter within a news archive system.
The articles are displayed with a lightbox style jQuery plugin. This means that all the articles are loaded with the rest of the page, but are set to have display:hidden, until the relevant entry has been clicked on.
So, I can't have the PHP to increment the counter simply embedded in the page, and in a search to find something to trigger the counter, all I could think of was this change to display:block.
I am open to any suggestions, although I am more experienced with simple jQuery, I have a hunch AJAX may be needed here?
Thanks in advance for any help anyone can offer, and let me know if any other information would be useful.
Sorry, but the restrictions where I am currently working mean I only have IE6 at my disposal. So I can't comment on anyone's answers...this is the only way I think I can reply.
Response:
Thanks for everyone's fast responses. I don't think I can use plain jQuery as the system will be on an intranet and need to record the total number of visits across the network, therefore I don't think cookies would be sufficient.
I am going to attempt the load() function suggested by Bradley - a lot simpler than I thought it would be...feeling a little silly now.
Will update as to how I get on :)
Update:
I am trying to implement the load() function, with no success. The lack of firebug is also hindering by debugging.
Can anyone see what might be wrong with this code:
<script type="text/javascript">
$('#<?php echo $row->articleid; ?>link').click(function() {
alert("some encouraging text<?php echo $row->articleid; ?>");
$('#<?php echo trim($row->articleid); ?>target').load("/hitcount.php?articleid=<?php echo $row->articleid; ?>");
});
</script>
<div id="<?php echo trim($row->articleid); ?>link">Click2</div><br />
<div id="<?php echo trim($row->articleid); ?>target"></div>
Embarrassing Update:
...all that was wrong was the file path.
Just a simple hit counter? No feedback on user info?
$('#result').load('ajax/counter.php');
Edit
$('#somediv').click(function() {
$('#result').load('ajax/counter.php');
});
You don't really need Ajax, Just a javascript variable that gets incremented on any onchange event you place on each html input / dropdown / etc..., Then onsubmit, pass that javascript variable.
Yeah, ajax would help you here. You can bind to the click event on whatever navigation item switches the article to block display, and have it dispatch something to a click counter script.
<a href='#article-1' class='display-article'>display article 1</a>
<a href='#article-2' class='display-article'>display article 2</a>
<div id='article-1' style='display:none;'>article 1</div>
<div id='article-2' style='display:none;'>article 2</div>
<script>
$(function() {
$('a.display-article').on('click', function(event) {
var article_id = $(this).attr('href');
$(article_id).show(); // show the actual article
// and send the ajax request to the processor
$.get('/scripts/track-click.php', { article_id: article_id }, function(data) {
alert('article tracking complete!'
});
});
});
Related
The problem is this:
I have a simple, two fields form which I submit with Ajax.
Upon completion I reload two div's to reflect the changes.
Everything is working perfect except a jQuery plugin. It's a simple plugin that can be called with simple
function(){
$('.myDiv').scrollbars();
}
It's simple and easy to use, but it doesn't work on Ajax loaded content. Here is the code I use to post form and reload div's:
$(function() {
$('#fotocoment').on('submit', function(e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
}).error(function() {
});
e.preventDefault();
});
});
I've tried creating a function and calling it in Ajax succes:, but no luck. Can anyone show me how to make it work ? How can that simple plugin can be reloaded or reinitialized or, maybe, refreshed. I've studied a lot of jQuery's functions, including ajaxStop, ajaxComplete ... nothing seems to be working or I'm doing something wrong here.
If you're loading elements dynamically after DOM Document is already loaded (like through AJAX in your case) simple binding .scrollbars() to element won't work, even in $(document).ready() - you need to use "live" event(s) - that way jQuery will "catch" dynamically added content:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Source: jQuery Site
Even if I am totally against using such plugins, which tries to replicate your browser's components, I'll try to give some hints.
I suppose you are using this scrollbars plugin. In this case you may want to reinitialize the scrollbars element, and there are many ways to do this. You could create the element again like in the following example
<div class="holder">
<div class="scrollme">
<img src="http://placekitten.com/g/400/300" />
</div>
</div>
.....
$('.scrollme').scrollbars();
...
fakedata = "<div class='scrollme'>Fake response from your server<br /><img src='http://placekitten.com/g/500/300' /></div>";
$.post('/echo/html/', function(response){
$('.holder').html(fakedata);
$('.scrollme').scrollbars();
});
If you want to update the contents of an already initialized widget instead, then things gets more complicated. Once your plugin initialize, it moves the content in some custom wrappers in order to do its 'magic', so make sure you update the correct element, then trigger the resize event on window, pray and hopefully your widget gets re-evaluated.
If it doesn't help, then try to come up with some more details about your HTML structure.
I want to thank everyone of you who took their time to answer me with this problem I have. However, the answer came to me after 4 days of struggle and "inventions" :), and it's not a JS or Jquery solution, but a simple logic in the file.
Originally, I call my functions and plugins at the beginning of the document in "head" tag, like any other programmer out here (there are exceptions also ).
Then my visitors open my blog read it and they want to post comments. But there are a lot of comments, and I don't want to scroll the entire page, or use the default scroll bars, simply because they're ugly and we don't have cross browser support to style that, just yet.
So I .post() the form with the comment, and simply reload the containing all of them. Naturally .scrollbars() plugin doesn't work. Here come the solution.
If I put this :
<script>$('.showcoment').scrollbars();</script>
in the beginning of my loaded document (with load() ), will not work, because is not HTML and it's getting removed automatically. BUT !!! If i do this:
<div><script>$('.showcoment').scrollbars();</script></div>
at the same beginning of loaded document, MAGIC .... it works. The logic that got me there I found it in the basics of javascript. If your script is inside an HTML element, it will be parsed without any problem.
Thank you all again, and I hope my experience will help others.
If I understand you correctly, try this:
var scrollelement = $('.myDiv').scrollbars();
var api = scrollelement.data('jsp');
$(function () {
$('#fotocoment').on('submit', function (e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
api.reinitialise();
}).error(function () {
});
e.preventDefault();
});
});
reinitialise - standart api function, updates scrolbars.
I will try to walk you through this very slow. I am trying to make a poll that are subject to change often so I have to make it dynamical. I also need to have this without page reload, so I would need to use Ajax to submit the form. So what I did was to create a PHP script that will echo the poll for me. This works nicely and I get the poll just the way I want it. Oh yeah, forgot to tell that it is a multi step poll. I navigate through 2-4 questions at a time by hiding/showing divs within a JQM 'page'. And by that I mean:
<div data-role='page'>
At the last page I do have a submit button instead of a next button since the poll obviously has no "next" div to show. This submit button does in no way, shape or form work, and thus is the issue here.
$("#submit").click(function()
{
if ($("#form").validate())
{
$.ajax(
{
type:'POST',
url:'add.php',
data:$('#form').serialize(),
success:function(response)
{
$("#answers").html(response);
}
});
}
else
{
return false;
}
})
This is supposed to send my form data to another PHP file that is named add.php, when then is supposed to post it to the div shown abit underneath. (It's really supposed just to save to database but I try to echo it until I see that it works). Now, the twist is that I did another identical piece of code on a non-dynamical form that was not created through PHP, but merely plotted down in HTML. This was also a multi step poll that span out over 3 divs/'pages'. And this had no problems submitting at all.
So to summarize: I had 2 different projects that each handled half my problem. One generated the form dynamically and the other saved a static form that I made. Both forms consisted of a variety of checkboxes, radiobuttons and textareas. Problem is, they won't work together. When I click the submit button I expect the form to echo out the answers into this div (the one you read about a few lines up):
<div data-role="content" id="answers">
Answers comes here:
</div>
Nevertheless, this div remains the same. I stripped down the $("#submit").click(function()) to alert('test'); and I still could not get a reaction. I've quadrillion-checked the variable names and div names and any other names that are relevant, and I've made various minor adjustments on each separate part (both generating the poll and posting it with ajax) as well as to my attempt to combine them without success. So, the million dollar question is what could be wrong? My last remaining hypothesis is that somehow the JavaScript function for $("#submit").click ... is loaded before the script that generates the poll. This would make sense that when the submit click function is declared it would not be linked up to any button like shown here:
<input type="button" id="submit" name="Submit"/>
Does anyone have any clue on how I can make this submit button to work, or even have a clue as to why it does not work? Thanks to anyone who read this far and I hope you posess and are willing to share some knowledge that could help me. Also thanks to the creators of Stack Overflow for implementing an alt+z function for this as I accidentally clicked alt+a then random letters while writing the sentence before this one. Have a nice day!
EDIT: Tried this after a tip from Kevin an answer below, but even the first alert button doesn't react:
$("#submit").click(function()
{
alert("it works");
if ($("#form").validate())
{
$.ajax(
{
type:'POST',
url:'add.php',
data:$('#form').serialize(),
success:function(response)
{
$("#answers").html(response);
return false;
}
});
}
else
{
return false;
}
})
});
You need a return false; under $("#answers").html(response); inside the scope of the success function. Let me know if this works. Good luck, Kevin
I just tried the script above without the post and it worked fine. Do you have jquery loaded before this script executes, and/or do you have or do you have any javascript errors in your console?
For a website I'm making for school, I'm trying my hand at using Jquery extensively for the first time, and even though I managed quite a bit so far, I'm stuck at two (most likely related) problems.
I'm aware that the upcoming case is somewhat long, but I feel it's necessary to submit all relevant code for everyone reading this to get a good image of what is happening.
Basically, the website is one index.html file, with the CSS thrown in, a few buttons, and one div with the ID content. I use this code to make this work:
<script type="text/javascript">
if ($('#content').innerHTML == " "){
$(document).ready(function(){
$('#content').load('main_text.html');
});
}
</script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
</script>
Then there is one content page, named search.html, which only contains a form that submits a search string to a search.php page (through ajax) that should then place the search results immediately back into a div called search_results in that same search.html file. The jquery that I use for this:
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
$("#search_results").show();
var search_val=$("#search_term").val();
$.post("Functions/search.php", {search_term : search_val}, function(data){
if (data.length>0){
$("#search_results").html(data);
}
})
}
</script>
The issue that I'm having is as followed:
Before I had the first line of code: if ($('#content').innerHTML == " "){; implemented, I would open the site, main_text.html would nicely be loaded in, I could navigate to other subpages fine. But typing in something in the form field in search.html did not display any results (just typing should already trigger the function). When I hit the search button on this form, instead of seeing query results, the main_text.html file load again in the #content div. This made me assume that perhaps, somehow, that the code:
$(document).ready(function(){
$('#content').load('main_text.html');
});
was being called again unwanted. Hency why I implemented that check for whether innerHTML existed.
However, now, when I first load the page, the #content div does not load any initial content at all. (The section on the webpage just becomes black, like my page background) I have to click any button to get some content loaded again in my main content div. Also, when I now go back to the search.html, the typing anything to get results, like previously, still does not work. If I now hit the search button, I get the initial result again of what I'd see when I just opened the page: a blacked out #content div.
So somehow, the biggest issue is in the fact that the jquery to get results from my PHP do not seem to work. My problem with the content.innerhtml check might well be obsolete if the issue with the searchresults not displaying in the #search_result div on the search.html is fixed.
Anyone have any idea's what I could do to fix this. Or otherwise, what other approaches I could take for the kind of website I'm making. Since I'm trying to learn jquery here, better approaches are always appreciated, I'd rather learn myself doing this the right way and all. :)
Thanks for your time.
Few things to note here:
<script type="text/javascript">
if ($('#content').innerHTML == " "){
$(document).ready(function(){
$('#content').load('main_text.html');
});
}
</script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
</script>
In the above, you are testing to see if there is a space in the innerHTML of the element with an id of content.
jQuery uses .html() or .text() to make comparisons against the data being held within a container, so if you want to maintain using jQuery principles, change this line. Going along the same thought process, you are preparing an IF statement on an element before the document is actually ready and loaded.
You should move the document.ready function to the outside of the if statement. This will allow you to ensure that the element is available at DOM, and you can indeed perform checks against this element.
<script type="text/javascript">
$(document).ready(function(){
if ($('#content').html("")){
$('#content').load('main_text.html');
}
});
</script>
Also, while being readily provided and fully functional, I would recommend starting off using $.ajax instead of $.get / $.post. I have personal preferences as to why I think this, but I won't go into that, it's just that, personal.
$.ajax({
url: "Functions/search.php",
type: 'POST',
data: "search_term="+search_val,
success: function(data){
if (data.length>0){
$("#search_results").html(data);
}
});
Lastly, you should be using the GET method and NOT the POST method. Based on REST/SOAP practices, you are retrieving data from the server, and not posting data to the server. It's best practice to follow those two simple ideas. This isn't because web servers will have a difficult time interpreting the data; but, instead, it's to prepare you for working on larger scale application deployment, or future team-environments. This way everyone on the team has an expectation as to what method will be used for what purpose.
Anyway, long story short, you also leave semicolons off of the end of your closing }) brackets. While this is not an issue, nor will it cause flaws in your development, coding is all about uniformity. You've used the closing ; everywhere else, so try and maintain that same uniform design.
Best of luck.
hi i am a new programer
i want to replace the content of current php page from another php page using ajax without refreshing page.
the content to be replaced is in div's.
both pages (current and another) has same div's
HTML Div's are:
<div class="category-container">
<div class="category-image"></div>
<div class="category-desc">#<p>text</p></div>
<div class="rating5" >Editors' rating: </div>
<div class="category-download-btn">Download</div>
<div class="category-buy-btn">Buy</div>
</div>
can anyone tell me how i can do it. it will be a great help.
also can you provide me ajax code not jquery.
thanks.
Have a look at jQuery's load, the section on loading page fragments:
The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted.
To get the div content on another page into an analogous div on the current page, use something like:
$('#content').load('other-page.php #content');
// ^ target div ^ same div on the other page
this is usual jquery.ajax call
function getVotes(id){
$.ajax({
type: 'get',
url: 'ay/templates/backend/_votes_partial.tpl.php',
data: 'charity_id=' + id,
success: function(data) {
$('#shadow').fadeIn('slow');
$('#popupContact').fadeIn('slow');
$('#content').html(data);
}
});
}
the simplest way would be:
$.get("pageurl",function(data){
$("yourdiv").html(data);
});
use jquery.ajax its easy... old way of making ajax calls was too much complicated, jquery made it easy,
you need to install jquery library,include it in ur head tag and go thorough following link for clear understanding, its much easy
Jquery.ajax
You're correct in assuming jquery is the way to go. I'm far from an expert, but this should help. The docs are straightforward.
Generally, jQuery follows the find something then do something approach.
Find something ---> watch for some action on some element (like changing a select box or clicking a link)
Do something ---> make an ajax call to the php page you want replace the current div with the new div
The jQuery documentation is here with an example at the bottom that shows exactly what you're trying to do http://api.jquery.com/jQuery.post/
Some other helpful jQuery commands for this task could be...
http://api.jquery.com/appendTo/
http://api.jquery.com/remove/
http://api.jquery.com/clone/
Hope this helps.
I'm having issues getting jQuery tooltips (using Tipsy) to work. The tooltips work fine on regular pages, but I actually need the tooltips on a page that I am including through PHP. The reason why I'm including that page, is because I'm also using jQuery to auto-refresh that included page every x milliseconds.
It appears that this auto-refresh mechanism is keeping the tooltips from functioning properly. When I remove that mechanism, the tooltips appear but that part of the page obviously does not reload itself anymore at an interval. I'm looking for a way to get Tipsy to work while making sure my included page refreshes itself.
I include my page as follows:
<div id="vardisplay">
<?php include("vardisplay.php"); ?>
</div>
I then use the following script to refresh the "vardisplay" DIV, resulting in my included page to be reloaded:
<script>
$(document).ready(function() {
$('#vardisplay').load('editarticle.php?bid=<?php echo $bnummer ?> #vardisplay');
var refreshId = setInterval(function() {
$('#vardisplay').load('editarticle.php?bid=<?php echo $bnummer ?> #vardisplay')}, 750);
$.ajaxSetup({ cache: false });
});
</script>
The object I would want a Tipsy tooltip on (within my included page) could be something like:
<div id="TipsyMe" title="I got tipsied">
<p>Testpiece</p>
</div>
I'm currently trying to achieve that particular tooltip by putting this script on that page, which is supposed to show "I got tipsied" in a Tipsy tooltip:
<script>
$(function() {
$("#TipsyMe").tipsy({gravity: 's'});
});
</script>
What ends up showing is a regular browser tooltip where jQuery is fully ignored. Again, it works fine when I remove the auto-refresh mechanism on the main page.
I'm dumbfounded at this point. I've been Googling for the past few hours without any result what-so-ever. Any help would be greatly appreciated!
in the tipsy doc, you can stumble upon an option called "live"
$(function() {
$("#TipsyMe").tipsy({
gravity: 's',
live: true
});
});
shall do it. (as you seem new, accepting answer will attract people for your future answer hint hint hint :P)
be careful thou: "live tooltips do not support manual triggering." (from the doc)
EDIT: didn't see properly your code:
$(function() {
$("div.someTotal").tipsy({
gravity: 's',
live: true,
title: "I got tipsied"
});
});
"someTotal" is the class for all you "boxes" where you have the edit and delete icon. If you don't have such class yet, you can create one (you can name it tipsy by example) and use it ($("div.tipsy").tipsy({...