I'm using the code below to load the results from a database query in a PHP page:
click me
$('.item > a').click(function(){
var url = $(this).attr('href');
$('.item-popup').fadeIn('slow');
$('.item-content').load(url);
return false;
});
All works fine right now, but the next bit of functionality is a problem. Inside results.php which ajax loads into .item-content, I have another link that is supposed to update and increment click counts for that link, also without refreshing. The functional PHP bits all work fine. My only problem is the jQuery/AJAX aspect of things.
Maybe I'm going about it the wrong way, but what I really want to do is have a page with a container that loads the result of of a database query from a PHP page, but also in that container, I have a link/button whose click count I want to be able to save and update all without refreshing.
EDIT
I guess the most important question I need answering is: When the ajax on index.php loads the content of results.php into the container in index.php, do browsers treat the newly loaded ajax content as part of the parent page (index.php) or is it still treated as a different page loaded into the container like an iFrame?
If say for example it is click event then you need to write
$('input element').on('click',function() {
// write code over here
})
Dont know for sure if you want this, When returning the data in the load function you will have to add a link like this in the resultant HTML which will be clickable:
Now in javascript you need to catch the click event of the link like this:
<script type="text/javascript">
$(function(){
$(".item-content").on("click", ".clickable", function(){
var counter = $(this).data('counter');
var id = $(this).data('id');
$.ajax({
url : //your url here,
data : {'id' : id, 'counter' : counter },
type : 'POST',
success : function(resp){
//update the counter of the current link
$(this).data('counter', parseInt( $(this).data('counter') )+1 );
//whatever here on successfull calling of ajax request
},
error : function(resp){
}
});
});
});
</script>
Related
We currently search through a form for contacts, and AJAX is used to display the results from a PHP file below the form (on the same page). The form's onsubmit attribute includes a return:false value to allow the AJAX code to complete.
The results appear 'below the fold' and I'd like the focus to jump down to an ID (#peopleResults) but can't manage this; instead, it stays at the top of the parent page.
Should I be trying something in the actual PHP file or in the AJAX call (to the PHP file) to achieve this?
I already tried <script>window.location.hash = "peopleResults";</script> in the PHP file and referencing results.php#peopleResults in the AJAX call, but neither worked.
Is this possible? I guess I am trying to do the equivalent of appending #peopleResults to the URL upon pressing Submit (without the URL necessary changing)...
I already tried <script>window.location.hash = "peopleResults";</script>
location.hash includes the # – both when reading from it, as well when you set a new value.
So
window.location.hash = "#peopleResults"
would be the correct way to tell the browser to jump to an element with the ID (or anchor name) peopleResults.
I think you want to achieve this please check the fiddle.
This is done without using hash. As you just want to view the result after Ajax.
By this you don't need to change the URL.
Based on the reply to my comment, it would seem you're a little foggy on the AJAX portion too. From the documentation:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
//this is where you need to add your data to the div
//after the data is in the div, scroll to it.
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});
You can see, the function where I added the comments is where you need to do the scrolling. After you populate the div (how ever you're doing that), then just use the suggestion Learner Student or phpisuber01 made of scrolling to it:
$("html, body").animate({ scrollTop: $("#peopleResults").scrollTop() }, 1000);
jQuery AJAX documentation: https://api.jquery.com/jQuery.ajax/
jQuery scrollTop documentation: https://api.jquery.com/scrollTop/
I have a file with title ad.php and contains
<img src="bannerimg.png">
and in another file i have:
<iframe src="ad.php"></iframe>
Question is how to count click on iframe!
Just do this if using javascript....
var clik = 0;
$('#myframe').click(function(){
clik++
alert(clik);
});
UPDATE WITH AJAX
$(document).ready(function(){
$('#myframe').click(function(e){
e.preventDefault();
$.ajax({
url : "countclick.php",
success: function(){
alert('done');
}
});
});
});
Then in your php file countclick.php you just retrieve the current value from database, and increment it and update.
Or just execute an increment query directly, without retrieving current value
Im assuming you know how to do that in php/mysql , so Im not gonna post that part
You would have to catch the click event somewhere on the client side (in JavaScript most likely) and then send a request back to the server notifying it of the banner click.
I asked a question about this but the post degenerated into confusion which lost the gist of the problem. Basically I'm trying to set up ajax so that a "like" or "unlike" link updates a database and shows the new status without having to refresh the page.
So I have a "view.php" page with links which are produced by a PHP loop. They look like this:
<div class="tools">
like
</div>
<div class="tools">
unlike
</div>
Note that each link has two classes: firstly a "like" class, and then either a "do_like" class or a "do_unlike" class, according to whether it's a link to "like" or a link to "unlike" respectively. (Originally I only had the "do_like" and "do_unlike" classes, which I was using to transform the link via css into a rollover-type image/icon, but I added the "like" class as well, for the ajax - see below.)
When a user clicks one of these links, the receiving processor.php script takes the variable-value pairs from the query string, and uses them to update a database, and then build a new form of the link, which it echoes out. The new form of the link is such that a "like this" link turns into an "unlike this" link, and vice-versa. So for the first "like" link above, the database returns:
processor.php?c=cars&p=2&s=d&u=d&pid=999999990
It's the "u" variable in the query string which determines whether or not the processor.php page will either insert the data into the database in the case of a "like" (u=i), or delete the data from the database in the case of an "unlike" (u=d). (I'm using prepared PDO statements for the database inserts/deletions.)
I'm using jquery/ajax to insert this newly built link in place of the one that was clicked, without having to refresh the page.
To do this, in the "view.php" page I included jquery.js and used the following javascript function:
<script type="text/javascript">
$(function() {
$("a.like").click(function(e){
e.preventDefault();
var link = $(this);
$.get(
$(this).attr('href'),
function(data){
link.attr('href',data);
});
});
});
</script>
The problem is, although this function sends the data to the processing script OK, and changes the link's href attribute in the page without a page refresh (I can see it's doing this OK by copying the link in the browser after a click), it doesn't change the link's text, class or title. So I as it is, I have to refresh the page to see any visual cues that the link has in fact changed (I might as well just use a header redirection in the processor.php page).
How can I modify the function (or change it) so that it also replaces the link's text, class and title? So that (for example, transforming a "like" link):
like
becomes:
unlike
?
You need to change the class and the title then also:
[...]
$.get(
$(this).attr('href'),
function(data){
link.attr('href',data);
link.toggleClass('do_like do_unlike');
link..attr('title', 'change title here');
});
Use an if condition to check the current state and update the attributes.
$(function () {
$("a.like").click(function (e) {
e.preventDefault();
var link = $(this);
var alreadyLiked = (link.text() == "UnLike") ? true : false;
$.get(link.attr('href'), function (data) {
link.attr('href', data);
if (alreadyLiked) {
link.removeClass("do_unlike").addClass("do_like").text("Like").attr("title", "Click to LIKE this photo");
}
else {
link.removeClass("do_like").addClass("do_unlike").text("UnLike").attr("title", "Click to UN LIKE this photo");
}
alreadyLiked = !alreadyLiked;
});
});
});
This code will work. Tested. Assuming every time the get request gives you the url (for deleting/inserting ) correctly.
This is based on both Shyju's and Pitchinnate's responses (so thanks to both!), and it works a treat using the css rollover link-transformation method (I also included a fade effect):
<script type="text/javascript">
$(function() {
$("a.like").click(function(e){
e.preventDefault();
var link = $(this);
$.get(
$(this).attr('href'),
function(data){
link.attr('href',data);
link.toggleClass('do_like do_unlike');
var titleState=(link.attr("title") == "Click to LIKE this photo") ? "no" : "yes";
if(titleState=="yes")
{
link.attr('title', 'Click to LIKE this photo');
}
else
{
link.attr('title', 'Click to UNLIKE this photo');
}
});
$(this).parents('div.tools').fadeOut(1000);
$(this).parents('div.tools').fadeIn('slow');
});
});
</script>
Finally, I find some article in http://code.google.com/intl/en/web/ajaxcrawling/docs/getting-started.html msnbc use this method. Thanks for all the friends.
Thanks for your all help. I will study it for myself :-}
Today, I updated my question again, remove all of my code. Maybe my thinking all wrong.
I want make a products show page.
One is index.php, another is search.php (as a jquery box page). index.php has some products catagory lists; each click on product catagory item will pass each value to search.php. search.php will create a mysql query and view products details. It(search.php) also has a search box.(search.php can turn a page to show multiple products; the search result looks similar to a jQuery gallery...).
I need to do any thing in search.php but without refreshing index.php.
I tried many method while I was thinking: Make search.php as an iframe (but can not judge search.php height when it turn page and index.php without refresh); use jquery ajax/json pass value from index.php to search.php, then get back all page's value to index.php. (still met some url rule trouble. php depend on url pass values in search.php, but if the value change, the two page will refresh all. )
so. I think, ask, find, try...
Accidental, I find a site like my request.
in this url, change search word after %3D, only the box page refresh
in this url, change search word after = the page will refresh
I found somthing in its source code, is this the key rules?
<script type="text/javascript">
var fastReplace = function() {
var href = document.location.href;
var siteUrl = window.location.port ? window.location.protocol+'//'+window.location.hostname +':'+window.location.port : window.location.protocol+'//'+window.location.hostname;
var delimiter = href.indexOf('#!') !== -1 ? '#!wallState=' : '#wallState=';
var pieces = href.split(delimiter);
if ( pieces[1] ) {
var pieces2 = pieces[1].split('__');
if ( pieces2[1] && pieces2[1].length > 1) {
window.location.replace( unescape(pieces2[1].replace(/\+/g, " ")));
}
}
}();
</script>
If so. in my condition. one page is index.php. another is search.php.
How to use js make a search url like
index.php#search.php?word=XXX&page=XXX
then how to pass value from one to another and avoid refreshing index.php?
Still waiting for help, waiting for some simple working code, only js, pass value get value.
Thanks to all.
I have read your problem, though I can not write complete code for you (lack of time ) So I can suggest you to what to do for your best practice
use dataType ='json' in jQuery.ajax function and
write json_encode() on B.php
and json_decode() on A.php or $.getJSON()
Alternate:
Read
jQuery.load()
assuming you really want to do something like here: http://powerwall.msnbc.msn.com/
I guess they are using a combination of ajax-requests and something like this: http://tkyk.github.com/jquery-history-plugin/
make shure that the navigation (all links, etc.) in the box works via ajax - check all the links and give them new functionality by js. you can write some function which requests the href url via ajax and then replace the content of your box. ...
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
//update url in addressbar
change_box_links(output_area);
}
});
});
});
}
it is upgradeable but shell show the main idea...
addendum[2011-05-15]
Get away from thinking you will have two files, that can handle some many "boxes". i mean you can do this but it's worth it.
but to be able to set up your templates like normal html page you could use the above script to parse the ajax requested html pages.
build your html-pages for
viewing the content,
viewing the search result
, etc.
on your main page you have to provide some "box" where you can display what u need. i recommand a div:
<div id="yourbox"></div>
your main page has buttons to display that box with different content, like in the example page you have showed us. if you click one of those a JS will create an ajax call to the desired page:
(here with jquery)
$('#showsearch_button').bind('click', function(){showsearch();});
function show_search() {
$.ajax({
url: 'search.php',
success: function(data){
var output_area = $('#yourbox');
output_area.html(data);
$.address.hash('search');
change_box_links(output_area);
}
});
});
for other buttons you will have similar functions.
the first function (see above) provides that the requested box-content can be written as a normal html page (so you can call it as stand-alone as well). here is the update of it where it also provides the hashtag url changes:
jquery and requireing the history-plugin
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
var name = url.replace('/\.php/','');
$.address.hash(name);
change_box_links(output_area);
}
});
});
});
}
and you will need some kind of this function, which will bind the back and forward buttons of your browser:
$.address.change(function(event) {
var name = $.address.hash();
switch(name){
case 'search': show_search(); break;
default: alert("page not found: "+name);
}
});
the above code should give an idea of how you can solve your problem. you will have to be very consequnt with filenames if you just copy and past this. again: it is improveable but shell show you the trick ;-)
im not sure that i fully understood what you want, but correct me if i didnt,
i think u need something like a dropdown that once the user select one item some div inside ur page show the result of another page result..
if so u can do it with jquery .load() and here is an example (no need for json)
Step 1:
Index.php
<p>
brand:<select id=jquerybrand>$jquerybrands</select><br />
Model:<select id=jquerycars></select><br />
</p>
<script type=\"text/javascript\">
$(document).ready(function(){
$('#jquerybrand').change(function(){
var value=$(this).value;
var url='api/quick.php?'+this.id+'='+this.value+' option';
$('#jquerycars').load(url);
});
});
</script>
This will simply show 2 dowpdown boxs (can be text or anything u like). and will add a listener to any change in value. once changed it will submit the id of the field and the new value to api/quick.php , then quick.php responce will be loaded into #jquerycars dropdown.
Step 2 quick.php
if(isset($_GET['jquerybrand'])){
$jquerycars="";
require_once("../lib/database.php");
$sql_db = new database();
$l=$sql_db->Item_in_table("car","sheet1","WHERE `brand`='$jquerybrand';");
foreach($l as $l)$jquerycars .="<option>$l</option>";
echo $jquerycars;//response that will replace the old #jquerycars
}
this will confirm that this is a request to get the query result only, then it will do the query and echo the results.
now once the results come back it will replace the old :)
hope it helps :).
I have a website, that uses PHP to select the content,
<div>
<? include ("navigation.php"); // navigation.php generates the menu ?>
</div>
<div>
<?
$type = $_GET["type"];
switch ($type) {
case "page" :
include "Text.php";
break;
case "news":
include "news_2.php";
break;
default :
include "main.php";
}
?>
</div>
The url is of the format domain.com/index.php?type.
I need to change the block #content without reloading the whole page, how can I do this?
As you've tagged the question with "jquery" I assume you know what that is, and that you're loading it into your page.
All you need to is give your div and ID... content here
And then use a bit of jquery.. in its simplest form just to load your content from 'myurl.php' into 'mydiv' when the page has finished loading:
$(document).ready(function() {
$("#mydiv").load("myurl.php");
});
You'll no doubt want some logic to determine what loads, and under what circumstances. If you need to pass data back to the URL then you'll need to go for jquery ajax ($.ajax). Its all pretty easy, loads of examples on the web, and good docs on the JQuery website.
This would best be done with Ajax. I like using jQuery's ajax function. Something like this:
function load(page){
var datastring='ANY DATA YOU WANT TO SEND';
$.ajax({
type: "POST",
url: 'your/pagehtml/',
data: "bust="+Date()+datastring,
dataType: "html",
cache: false,
success: function(html){
$('#content').html(html)
}
});
return false;
}
You wouldn't need to send the page in the URL this way. Anytime you change the url, you must be loading a different page. Outside of .htaccess rewrite. Which isn't what you need.
Fire this on click or whatever you want.
If you're using jQuery, it's pretty easy. You didn't post what is supposed to trigger the change, so I'll assume you have a list of links in another element with an id of nav.
Read more about the jQuery Ajax request here: http://api.jquery.com/jQuery.ajax/
//run on page load
$(function(){
//bind a click event to the nav links
$("#nav a").bind("click", function(e){
//keep the links from going to another page by preventing their default behavior
e.preventDefault();
//this = link; grab the url
var pageLocation = this.href;
//fire off an ajax request
$.ajax({
url: pageLocation,
//on success, set the html to the responsetext
success: function(data){
$("#content").html(data.responseText);
}
});
});
});
I'd also suggest doing some code cleanup like caching your $("#content") element on the load event (something like window.container = $("#container"), and using window.container later on), but I left it as-is so that everything remains clear.