Finally figured it out thanks to One Mad Monkey, but forgot quotes on my $eventDate variable for the SQL query. Thanks for the help guys :)
$(".date_has_event").live("click",function(){
console.log('you clicked', this);
var dateClicked = $(this).attr('id');
$.ajax({
type:"GET",
url: "popup_events.php",
data:"date="+dateClicked,
success: function(data){
$(".popupContent").html(data);
}});
//centering with css
centerPopup();
//load popup
loadPopup();
});
This is linked to my popup_events.php file:
<?php
include ("Includes/dbConnect.php");
$eventDate = $_GET['date'];
$query = "SELECT * FROM events WHERE eventDate='$eventDate'";
$check = mysqli_query($cxn,$query) or die("Couldn't execute query!");
while($row = mysqli_fetch_array($check))
{
$id = $row['eventID'];
echo "<div class='submit_event_list'><a href='individual_event_page_main.php?id=$id'>";
echo $row['eventName'];
echo " | " . $row['host'];
echo " | " . $row['venue'];
echo " | " . $row['eventDate'];
echo "</a></div>";
echo "<br />";
}
?>
If the question is "is this possible?" The answer is yes. Of course you can bind events to your HTML that will show a popup. People do it all the time, so it's not really a valuable question!
The broader question of "am I doing this in a good way?" is a tougher one to answer and also stretches the limits of an "appropriate" Stack Overflow question, which should have a more focused scope than this.
I say "have at it!" safely knowing that you can add popups. Then come back when you have more specific questions. Things I would think about when you get started:
Is JavaScript the best way to dynamically generate a calendar? Are you using a server-side language at all? This might be the better place. And if you ARE using JS, why not build the calendar completely, and THEN go back and populate it?
Do you need to make your ajax call synchronous? Are there ways you can design it so that it can happily go fetch the new information and not worry about whether it's returning in sequence or not? (hint, this might relate back to #1)
Information moreso than a hint: live() is a deprecated function. From jQuery 1.7 onward, I would look into using .on() instead. There's an equivalent for .live() using .on() but I don't think you should use it... you should use the equivalent to .delegate() since you should have an ancestor of your calendar that can serve as a listener (instead of the whole document!). If you're using jQuery 1.5.x or 1.6.x then use .delegate().
Maybe this should've been the first question: have you looked into UI frameworks that already include calendars and popups (they won't include the event management, so you still have some fun work to do)?
I'm not sure you actually have a question...
But it seems like you probably just need some help on how to tell which pop up to display.
in your:
$(".popup").live("click",function(){})
you can use the special "this" variable to determine which of your day's was clicked.
eg.
$(".popup").live("click",function(){
console.log('you clicked', this);
//to get the date id (your formatdate) from this
var dateClicked = $(this).parent().parent().attr('id');
//have to do parent() twice because you put your .popup under <div class='title'>
})
To make it easier.. you should consider changing your click event to use .date_has_event instead of .popup so you could do this instead:
$(".date_has_event").live("click",function(){
var dateClicked = $(this).attr('id');
})
once you know you which day was clicked, you probably want to render that day's popup's content (the list of events for that day) in your popup window.
That's where you should use an ajax request sent to some backend code which is basically the php code you already have shoved behind your (that stuff under your #popupContact).
You should move that code out somewhere.. in say a "getEvents.php"
eg.
$(".date_has_event").live("click",function(){
var dateClicked = $(this).attr('id');
$.ajax({
type: "GET",
url: "getEvents.php",
dataType: "json",
data: "date="+dateClicked,
success: function(data){
//fill your popup with the data received
}
})
})
I think that should be enough to get you on your way.
Good luck.
Related
My PHP page
<ul id="upvote-the-image">
<li>Upvote<img src="image.png" /></li>
</ul>
is currently successfully sending variable to javascript
$("#upvote").each(function(index) {
var upthis = $(this).attr("rel");
var plusone = upthis;
$.post("upvote.php", {
'plusone': plusone
});
alert(plusone);
});
(The alert in the code is for testing)
I have multiple images using the rel tag. I would like for each to be able to be upvoted and shown that they are upvoted on the page without loading a new page.
My question, and problem: what is my next step? I would just like to know how to send a value to upvote.php. I know how touse mysql to add an upvote, just not how to send a value to upvote.php, or even if my javascript code opens the page correctly.
thanks
I think you need something like this:
<ul id="upvote-the-image">
<li><span rel="50" id="upvote">Upvote</span><img src="image.png" /></li>
</ul>
<span id="result"></span>
$("#upvote").click(function(index) {
var upthis = $(this).attr("rel");
var oOptions = {
url: upvote.php, //the receiving data page
data: upthis, //the data to the server
complete: function() { $('#result').text('Thanks!') } //the result on the page
};
$.ajax(oOptions);
}
You dont need an anchor, I changed it for a span, you can test asyc connection using F12 in your browser
Your javascript never opens the php page, it just sends data to it, and receives an http header with a response. Your php script should be watching for $_POST['plusone'] and handle database processing accordingly. Your next step would be to write a callback within your $.post function, which I recommend changing to the full ajax function while learning, as it's easier to understand and see all the pieces of what's happening.
$.ajax({
type: 'POST',
url: "upvote.php",
data: {'plusone': plusone},
success: function(IDofSelectedImg){
//function to increment the rel value in the image that was clicked
$(IDofSelectedImg).attr("rel")= upthis +1;
},
});
You'd need some unique identifier for each img element in order to select it, and send it's id to the php script. add a class instead of id for upvote and make the id a uniquely identifiable number that you could target with jquery when you need to increment the rel value. (From the looks of it, It looks like you're putting the value from the rel attribute into the database in the place of the old value.)
A good programming tip here for JQuery, Don't do:
<a href="javascript:return false;"
Instead do something like:
$(function(){
$('#upvote').on('click', function(event){
event.preventDefault();
$.post('upvote.php', {'plusone': $(this).attr('rel')}, function(data){
alert('done and upvoted');
});
});
});
That is a much better way to handle links on your DOM document.
Here are some Doc pages for you to read about that coding I use:
http://api.jquery.com/on/
http://api.jquery.com/jQuery.post/
Those will explain my code to you.
Hope it helps,
Before anyone says "try searching", I have - I realize this is probably a simple solution, but I just can't get it to work. This is my first venture into AJAX - and my knowledge of javascript is slightly above a 1st grader...I know I need to get up to speed on it.
I'm trying to build a nested task manager, using AJAX. I'm getting jammed up on the AJAX implementation...the list works well otherwise. The basic concept should output like this:
Goal: Create a nested task list
Milestone: Build the basic setup - completed 2/11/12
Task: Design the database - completed 2/11/12
Task: Design the php stuff - completed 2/11/12
Milestone: Add the finesse
Task: Include AJAX functioning
Task: Include CSS
As you click on the link, it runs my MySQL update to show the item being completed. I have three nested while loops (one for goals, one for milestones and one for tasks). They are near identical. Here's the most deeply nested loop:
$query_tasks = mysql_query("SELECT * FROM task WHERE task_gid = '$task_gid' AND task_mid = '$task_mid' AND task_tid IS NOT NULL");
$t_numrows = mysql_num_rows($query_tasks);
if($t_numrows > 0){
while( $get_task = mysql_fetch_array($query_tasks)){
$task_id = $get_task['task_id'];
$task_goal = $get_task['task_goal'];
$task_due = $task_task['task_due'];
$task_due = date("m/d/Y", $task_due);
$task_complete = $get_task['task_complete'];
$task_complete_date = $get_task['task_complete_date']; ?>
Here is my link to trigger the query:
<a id="link" href="#"><?=$task_goal?> by <?=$task_due?> </a>
}
Here is my ajax query:
<script type="text/javascript">
$('#link').click(function(){
$.ajax({
type: "GET",
url: "complete.php?id=<?=$task_id?>"
});
return false;
});
</script>
I've got it to work for one link (if I click on the last rendered link, it works as desired - but no other links do). I've tried calling the javascript in the head (my preferred method) as well as calling it each time the loop passes (not sure that's a good idea, but whatever). My thought is to use the variable from the while loop for each task in the javascript function. I've tried placing the ajax script into a javascript function and calling it on the onClick behavior for the link, but no luck. Thoughts?
This is how you should do it:
http://pastebin.com/ZMCzAS5H
By setting a custom attribute (task_id) to your link you'll be able to retrieve it later in the ajax request. This way you'll use one event binder for all of the links instead of one for each link.
It's not a good idea to use the same ID for several elements within the same document; IDs should be unique. Use classes instead so try
<a class="link" href="#"><?=$task_goal?> by <?=$task_due?> </a>
and
<script type="text/javascript">
$('.link').click(function(){
$.ajax({
type: "GET",
url: "complete.php?id=<?=$task_id?>"
});
return false;
});
</script>
JavaScript and PHP do not interact. PHP is a 'pre-processor' and basically generates HTML (in this context). You can't use PHP variables in JavaScript. Period.
When generating the HTML, add the task_id to the anchor
echo "<a class=\"link\" href=\"#\" rel=\"". $task_id ."\">". $task_goal ." by ". $task_due . " </a>";
(don't use an ID for link, but use a class)
Then in jQuery:
$('.link').click(function(e){
e.preventDefault(); // use this instead of return false;
task_id = $(this).attr('rel');
$.ajax({
type: "GET",
url: "complete.php?id="+ task_id
});
});
"I've got it to work for one link (if I click on the last rendered link, it works as desired - but no other links do)"
This is probably because you have used an ID for the anchor, and you can only use an ID once on the page. You must use a class
This is my first post and every opinion/help will be much appreciated by me.
I am new to php and javascript.
So lets start...
What i want to do is parse a variable to an external php form every time a person clicks on text.
For example lets assume that i have the following string echoed $test = "what a beautiful day";
I want when a person clicks on "what" the "phpquery?test=what" to be triggered.
From what i have read javascript can help with that because of the client side scripting logic
Thank you all in advance!
This is usually handed via XMLHttpRequest, usually abstracted via a library that irons out the differences between browsers (bigger libraries that do lots of other stuff include YUI and jQuery).
I would parse the sentence in such a way that each word is encapsulated in a tag. For example:
<span class="clickable">What</span> <span class="clickable">a</span> <span class="clickable">wonderful</span> <span class="clickable">day</span>
than you can bind a click function to each of these spans like so using JQuery
$(document).ready(function() {
$("span.clickable").bind("click", function() {
var wordClicked = $(this).html();
$.get("phpquery?word=" + wordClicked );
});
});
and do as SalmanPK suggested and use the $.get to send the word click to PHP :)
HTH
Yes you will have to do that using AJAX.
Have a look at jQuery, its very easy to learn for newbies.
You can accomplish this with jQuery using this simple piece of code:-
$('a').click(function(){ // You can use a css selector to select your anchor tag
$.get("phpquery?test=what");
});
Ofcourse in most cases XMLHttpRequest would be suitable, but maybe you prefer the simple solution:
window.location.search = "?test=what";
here is an example of how you could achieve the click handling with jQuery, and also how you can do an ajax call (commented out after alert)
http://jsfiddle.net/UgXAH/1/
HTML:
<p class="interactive">this is some text</p>
Javascript:
$().ready(function(){
var textArray = $('.interactive').text().split(' ')
$('.interactive').empty()
$(textArray).each(function(){
var textItem = $('<span>'+this+' </span>')
textItem.click(function(){
var text = $(this).text()
alert('fire off ajax request with text='+text)
/*$.ajax({
url:'some-url.php',
data:{
text:text
}
})*/
})
$('.interactive').append(textItem)
})
})
I'm building a website which has a page that users can add content to, and they can rearrange the divs to whichever position and size they want. I'd like to have a save button which saves the current position of each div; however, I don't want the page to refresh each time (I'm also going to have an auto-save, which will have to save the information in the background).
I can't figure out how to post the data to the server though, without causing the page to reload. I figure I need some kind of AJAX request, but can't find anything that tells me how to do that (all the AJAX examples I can find seem to be about reading data from the server). I think I'm just starting to go round in circles now, but I can't get my head around this at all - I know it's probably not a hard thing to do, but I keep getting confused by the different examples.
So, first of all, is this the best way to do it? And, if so, can someone point me to a straightforward example of posting data via AJAX? I'm already using jQuery, so can use that for the Ajax as well.
Thanks.
Super simple AJAX with jQuery:
$.ajax({
url: '/save-the-stuff-url',
type: 'POST',
data: {
// information about your divs, etc.
'foo' : 'bar'
},
success: function(response) {
// if the AJAX call completes successfully, this function will get called.
alert('POST successful!');
}
});
Give it a shot!
Here, try this for AJAX:
$.post("example.php", {
from : "ajax", // put some info in these - they are the params
time : "2pm",
data : "save"
},
function(data) { // callback function - data always passed to it
$("#success").html(data); // do something with that data
}
);
And put this somewhere:
<span id='success'></span>
And then, try this example for example.php:
<?php
if(isset($_POST['from']) and $_POST['from'] == 'ajax'){
echo "<span style='color: green;'>Saved!</span>";
}
else {
echo "<span style='color: red;'>Failure!</span>";
}
?>
And then just modify these to fit your needs, probably changing the file of target. Whatever the script outputs is what is given to the ajax request. This means that if this was my PHP script:
<?php echo "Aloha!"; ?>
And this was my javascript:
$("#output").load("myScript.php");
Then #output would have "Aloha!" in it.
Hope this helps!
Please go through the Jquery site for various examples of post.
HTH
and the jQuery docs pages are a great way to learn jQuery.. the page for post is http://docs.jquery.com/Post
you may also want to look at jQuery draggables if you're not using that yet..
http://docs.jquery.com/UI/API/1.8/Draggable
you can fire a save tied to your draggable object being let go rather easily with
$( ".selector" ).draggable({
stop: function(event, ui) { ... }
});
I am doing a mysql database search and retrieving some results via ajax livesearch using the example on w3schools and i want to manipulate those results (drag and drop them) but im having a problem because the script loads before you enter the search and get the results so it does absolutely nothing no the search results. Any thoughts on this matter ?
Ah - thanks for the clarification.
The elements you want to drag are being created after the drag/drop initialization. You need make them draggable:
for example, add 'dragMe' as a class to the items. Once the list is populated from the server, then make those items dragable:
$('.dragMe').draggable();
I would really look into jQuery's ajax functions and their autocomplete
To clarify and for jquery (against your cited example):
function showUser(str)
{
$.get( 'getuser.php', { q: str },
function(data) {
$('#txtHint').html( data ); // add the returned content to #txtHint
$('#txtHint').find('.dragItem').draggable(); //make the new items draggable
}, 'html' );
}
In your php, change your display so it is blocks that can be dragged.
while($row = mysql_fetch_array($result))
{
echo "<div class="dragItem">"; // see how we're adding the 'dragItem' class?
echo "Firstname " . $row['FirstName'];
echo "</div>";
}
past that, you'll really want to do some more research to get a better idea of whats going on.