Pass PHP variable from while loop to javascript function - php

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

Related

pass sql query result to another php page (that is contained in a div) to run another sql query - all on the same page, with ajax

Objective:
Pass sql query result to separate php file that uses that result to run another sql query.
I have an sql query that lists a few rows of data. I want one data piece of the row as a link. When that link is clicked, that data is passed to another php page that runs an sql from that passed data.
Currently have an ajax script that updates content in a separate div on the same page as the original sql query. Basically my sql lists basketball players info. Name, height, weight, position. I want to click the players name and have a separate php file pull up more data based on the players name.
What I have to create the column with the players name:
echo
"<td><a href=javascript:void(0); onClick=getdata('/players/player1.php,'content');>".$players['first_name']." ".$players['last_name']."</a></td>";
How do I pass the name to a separate php file? Thank you!
A couple of errors in your HTML: the attribute data needs to be wrapped in quotes, and you have a missing single quote:
echo
"<td><a href='javascript:void(0);' onClick='getdata(\'/players/player1.php\',\'content\');'>".$players['first_name']." ".$players['last_name']."</a></td>";
So, knowing that, you've obviously not written the getData function?
Assuming that you haven't, and assuming you're a beginner, I'd encourage you to look at jQuery as this will simplify a lot of what you are doing. (It can be done in JavaScript without jQuery if that's what you prefer, but this is simpler.)
Your HTML will be
echo
"<td><a href='#' class='js-load-more' data-playername='" . htmlspecialchars($players['first_name']) . "'>".htmlspecialchars($players['first_name'])." ".htmlspecialchars($players['last_name'])."</a></td>";
Than include jQuery in your HTML (see http://jquery.com/)
Then include the event handlers: and right on the front page of jQuery are the two examples you need to adapt. You'll end up with something like this (where #info is a div on your page where you display the data):
$( ".js-load-more" ).on( "click", function( event ) {
$.ajax({
url: 'http://YourUrl/page.php?name=' + $(this).data('playername'),
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'json',
success: function(data) {
var $title = $('<h1>').text(data.talks[0].talk_title);
var $description = $('<p>').text(data.talks[0].talk_description);
$('#info')
.append($title)
.append($description);
},
type: 'GET'
});
});
have a play from there, this should get you going.

Can a variable go to a hidden PHP page using jQuery?

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,

How to tell which JQUERY popup to display

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.

PHP post and get value to a jQuery box page, refresh page as `msnbc.com`

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 :).

How to get element id into PHP variable

Is it possible to get an element id into a PHP variable?
Let's say I have a number of element with IDs:
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
How do I get this into a PHP variable in order to submit a query. I suppose I would have to resubmit the page, which is OK. I would like to use POST. Can I do something like:
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post("'.$_SERVER['REQUEST_URI'].'", { id: $(this).attr("id") });
});
});
</script>
I need to pass $(this).attr('id') into $newID in order to run
SELECT * from t1 WHERE id = $newID
jQuery is a very powerful tool and I would like to figure out a way to combine its power with server-side code.
Thanks.
This is like your question: ajax post with jQuery
If you want this all in one file (posting to active file) here is what you would need in general:
<?php
// Place this at the top of your file
if (isset($_POST['id'])) {
$newID = $_POST['id']; // You need to sanitize this before using in a query
// Perform some db queries, etc here
// Format a desired response (text, html, etc)
$response = 'Format a response here';
// This will return your formatted response to the $.post() call in jQuery
return print_r($response);
}
?>
<script type='text/javascript'>
$(document).ready(function() {
$('.myElement').click(function() {
$.post(location.href, { id: $(this).attr('id') }, function(response) {
// Inserts your chosen response into the page in 'response-content' DIV
$('#response-content').html(response); // Can also use .text(), .append(), etc
});
});
});
</script>
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
<div id='response-content'></div>
From here you can customize the queries and response and what you would like to do with the response.
You have two "good" choices in my mind.
The first is to initiate a post request every time the ordering changes. You might be changing the ordering using jQuery UI sortable. Most libraries that support dragging and dropping also allow you to put an event callback on the drop simply within the initialization function.
In this even callback, you'd initiate the $.post as you have written it in your code (although I would urge you to look up the actual documentation on the matter to make sure you're POSTing to the correct location).
The second strategy is to piggyback on a form submission action. If you're using the jQuery Form Plugin to handle your form submissions, they allow you to indicate a before serialize callback where you can simply add into your form a field that specifies the ordering of the elements.
In both cases, you'd need to write your own function that actually serializes the element IDs. Something like the following would do just fine (totally untested; may contain syntax errors):
var order = [];
$('span.myElement').each(function(){
// N.B., "this" here is a DOM element, not a jQuery container
order.push(this.id);
});
return order.join(',');
You're quite right, something along those lines would work. Here's an example:
(btw, using $.post or $.get doesn't resubmit the page but sends an AJAX request that can call a callback function once the server returns, which is pretty neat)
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post(document.location, { id: $(this).attr("id") },
function (data) {
// say data will be some new HTML the server sends our way
// update some component on the page with contents representing the element with that new id
$('div#someContentSpace').html(data);
});
});
});
</script>
Your approach looks perfectly fine to me, but jQuery does not have a $_SERVER variable like PHP does. The url you would want to provide would be window.location (I believe an empty string will also work, or you can just specify the url on your own). You seem to be sending the ID just fine, though, so this will work.
If you want the page to react to this change, you can add a callback function to $.post(). You can do a variety of things.
$.post(window.location, {id: this.id}, function (data) {
//one
location.reload();
//two
$("#responsedata").html(data);
//three
$("#responsedata").load("affected_page.php #output");
});
I think number 2 is the most elegent. It does not require a page reload. Have your server side php script echo whatever data you want back (json, html, whatever), and it will be put in data above for jQuery to handle however you wish.
By the way, on the server side running the query, don't forget to sanitize the $id and put it in quotes. You don't want someone SQL Injecting you.

Categories