How can I add a simple counter function in javascript jquery? - php

I'm using Shadowbox a jquery overlay and I wanted to count how many people are actually using the overlay. Thus, I would need a function that would write a counter to a file or sending a query through a php api...
has to be a a php url api because I cant use php on the server where the overlay is.
So I need help with executing a javascript function on the overlay click, tips on how to make a counter query through GET method.
Thanks
<script type="text/javascript">
Shadowbox.init({
handleOversize: "resize",
overlayOpacity: 0.9
});

When you bind your click handler to open the shadownbox, add a binding for an ajax call, such as this:
$.ajax({
type: "GET",
url: "stats.js",
data: "name=urlOrNameOfItem"
});
Replace urlOrNameOfItem with something meaningful so you can track what has been clicked. I assume you know in php how to handle a query string.
See JQuery docs: http://api.jquery.com/jQuery.ajax/

Before you display your Shadowbox throw an Ajax query to a php script which would save the current request in a db (including $_SERVER info for better analysis).
This PHP script can fetch the current count of views for that image from the Db and update it accordingly.
I'm guessing the shadowbox function is called as a onclick event on your image so just add the Ajax call something like this:
$.ajax({
url: 'path-to-counter-script.php?i='+image-identifier,
success: function() {
//display shadowbox
}
});

Related

Can I dynamically load a portion of a table first?

I've recently changed my searching page to a searchable datatable page due to my employer's request for easier data management. The problem is that it is taking too long to load.
I'm wondering it there is a way to only load like a portion of the table and finish loading the page first. Then finish off loading the rest of the table after that, e.g. while the user actually attempt to search for the data.
This was requested because the user might want to navigate to other parts of the page instead of using the datatable.
Extra info : The page is in .php and the data is loaded using php do-while loop. Maybe we can do a workaround using php functions?
Using the AJAX method recommended in the comments, the following is similar to how you could handle the page-load. You would need the jQuery library for the below.
Initial page
<script type="text/javascript">
// when the page is done loading,
// let's send a call to load more data
$(document).ready(function(){
myFunction();
});
// function to handle AJAX request to gather data
function myFunction(){
$.ajax({
type: "POST",
url: "./linkToMyPHP.php?loadData=1",
success: function(data){
// handle the data using the "data" variable
}
});
}
</script>
AJAX Page
<?php
if(isset($_GET["loadData"])){
// call query here and echo information
}
It may be recommended, to actually use a PHP function called json_encode() to echo back the information from your AJAX page in JSON form. This would allow you to transmit an array of information, instead of raw data. You would then need to update your AJAX request function similar to below.
$.ajax({
type: "POST",
url: "./linkToMyPHP.php?loadData=1",
dataType: "json",
success: function(data){
$("#myDivToChange").html(data);
}
});
You can read up on JSON at this highly rated question.

Run ajaxed javascript

I know this has been covered a few times, but I'm completely a noob when it comes to javascript so I have no idea what I'm doing. I am running a javascript that sends variables to a php file and that info is ajaxed into the current page using innerhtml. Here is that part of the code...
function givingHistory(dyear,did)
{
var divname="giving" + dyear;
$.ajax({
url: 'finance/givinghistory.php',
type: 'POST',
data: {
year: dyear,
id: did
},
success: function(givedata) {
document.getElementById(divname).innerHTML = givedata;
}
});
}
</script>
In the givedata function response from the php file there is a call to another javascript function that is already loaded in my common .js file (so both javascript functions are loaded when the page loads). How do I get the onClick that is added via innerhtml to work? Inside the php file, I check to see if id = a php session variable. If it does it spits out the text that includes the onClick.
If you use a specific id/class/identifier when the page loads in the $('*') function then the action will only bind to that. To get the action bind to anything ever try using $(document).on('click', **selector**, function() {});.
Previously there was bind/live that bound to elements as and when but on is the function now.
Also why are you mixing the $.ajax (jQuery) with document.getElementById(divname).innerHTML (regular javascript)? If you are already using jQuery you could just use $('#'+divname).html(blahbahblah);

Passing PHP variable to Jquery without refresh

I apologize upfront for my lack of jquery knowledge. In this website I am building, a user is presented with a number of thumbnail images representing plants. When a thumbnail is clicked, a jquery popup is initiated. What I would like to be able to do is pass a php variable that has the ID of the plant over to the jquery popup to display the prper information. Any help would be greatly appreciated. Thank you.
EDIT: http://www.plantcombos.com/header/main_index.php?display=random_mix
Im pretty sure you dont need to query PHP each time ... something like this would work :
<img class-"imgclick" src="/small-plant.jpg" data-id="123" />
This would be the output from your server side (php if thats what your using) - it stores the ID of the image in the data attribute
JavaScript :
$(document).ready(function() {
$('.imglink').click(function(event) {
event.preventDefault();
$('dialogid')
.data('image_id', $(this).data('id'))
.dialog('open');
})
})
the image id from the data attribute is then passed to the data attribute of the dialog. This attribute can be accessed using $(this).data('image_id') form within the dialog then
Use the jQuery AJAX method to gather data from a PHP file and display it on the page. It is very easy and you can pass any variables (parameters) you like to the page.
http://api.jquery.com/jQuery.ajax/
For example:
// This will send a request to a PHP page
$.ajax({
url: "http://example.com/test.php",
dataType: "html",
success: function(data){
// Place the returned data into your content
$('#image').html(data);
}
});

jQuery and AJAX Loading

I am making a page that when you click on a "story" it loads the text and the media for that story, I have a seperate PHP script for the story text and the media (video or image) loading. both scripts work and actually it all works.
My problem is that when you click the story it is supposed to load the text, and then slide the media down when it's loaded However, it slides down even when the text is still loading.
newspaper.nmyster.co.uk/ is the site in question. click on the vimeo story on the left and see what I mean.
The code for the AJAX that loads the story and media is:
$.ajax({
url: './scripts/storyLoader.php?storyid='+storyId,
success: function(result){
$('#storycontainer').hide();
$('#loading').remove();
$('#storycontainer').hide(0).html(result).fadeIn(1000);
}
});
$.ajax({
url: './scripts/mediaLoader.php?storyid='+storyId,
success: function(result){
$('.martefact').hide();
$('#loading').remove();
$('.martefact').html(result).slideDown(1000);
}
});
Basically, I only want the media div to slide down once the video or image has finished loading.
Thanks
I would use something like this:
var requestHandle;
function loadPage(url, vars) {
//cancel pending
if (requestHandle!=null)
requestHandle.abort();
//load page..
requestHandle = $.get(url, vars, function(data) {
$('#storycontainer').hide();
$('#loading').remove();
$('#storycontainer').hide(0).html(data).fadeIn(1000);
});
}
Your request is asynchronous. It means that the script won't wait for data to load before executing the aesthetics bit.
You need to add async: false to your $.ajax call (look up other options over at jQuery documentation). That way, browser will wait for data to arrive first before executing the rest of JS.
What does your mediaLoader.php script do? Does it just check the database whether there are any media entries for the given story and if so format them properly and output them? Because currently I don't think you can slide down after the video is completely loaded, since you are embedding a vimeo video container, which handles the loading of the video itself and you have no access to it...
You need to use an 'on complete' callback function on the first animation.
Have a look jQuery api documentation for .fadeIn()
It should look something like:
$('#book').fadeIn('slow', function() {
// Code to run after animation completed...
});

Return results from a MySQL database using jQuery/AJAX and insert into a DIV

I am working on a project for reserving classrooms. One way of reserving a room is to select a room, see if the things it has (# of seats, # of computers, etc.) is ample for whatever the person needs it for, and then make a reservation.
I have a page that displays all of the available rooms as links in an HTML table, created dynamically in PHP/MySQL. My goal is when a user clicks on a room name, the AJAX request executes a query and returns the necessary data, and then displays it in a DIV on that same page.
Right now, I'm calling an external PHP file that gets the ID of the room that's clicked and executes the query. I'm still very much a novice at jQuery, and I'm pretty sure the problem is in my jQuery script:
<script type="text/javascript">
$(document).ready(function()
{
$('table.roomNums td a.rm-details').click(function()
{
var id = $(this).attr('id');
$.ajax(
{
type: 'POST',
url: 'roomInfo.php',
data: {
roomID: id
},
dataType: 'json',
cache: false,
success: function(result)
{
$('#room-details').empty();
$('#room-details').append("<ul>\n\t<li>Seats: " + result.numOfSeats + "</li>\n</ul>");
}
});
});
});
</script>
As of now, when I click on one of the room number links, nothing happens. I'm assuming that my problem resides in this script, but I'm not sure where or what. I've been reading into the ajax function in jQuery and I'm pretty sure I understand what's going on, but I'm having no luck at the moment.
You want to troubleshoot the following four things:
The HTTP Request Does the browser even issue an ajax request? If so, does it contain the form parameter you are trying to make it contain?
The HTTP Response Does your php script return the data you are expecting in JSON format so JQuery can automatically parse it for you? Copy and paste the response from the server into a test javascript file and see if it compiles as a valid JSON object in a javascript debugger.
AJAX success function Does your javascript error out? Can you step through each line of execution in a javascript debugger like firebug?
Click Event Handler Does your click handler properly return false so the page does not reload? Does your click event handler function fire at all upon click?
Somewhere in the above four things lies your issue. It looks to me like you just need to return false in your click handler so the page does not reload.

Categories