i have this HTML / PHP code:
$notes.='<div class="note '.$color.'" ';
if($row["xyz"] == '') {
$notes.='style="left:45%; top:10%; z-index:0;"><h3 align="center">New Note</h3>';
} else {
$notes.='style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">';
}
$notes.=htmlspecialchars($row['text']).'
<a class="closeMessage">X</a><div class="addedby">'.htmlspecialchars($row['addedby']).'</div>
<span class="data">'.$row['sequence'].'</span>
</div>';
there are multiple containing different data from the database
i would like to use ajax to send data to a PHP page using GET, i currently have this:
$('.closeMessage').live('click',function(){
//alert("close");
alert($('span.data').html());
$.get('/includes/sticky_notes/closeMessage.php',{
sequence : $('span.data').html()
});
alert("close");
});
but its passing the incorrect sequence each time. its passing the sequence number of a different row
As your HTML code for the notes have several elements with the class 'data', when you call for $('span.data').html() you will always get the inner html of the first span with the data class.
You can traverse the dom tree and use something like the siblings function.
$(document).ready( function(){
$('.closeMessage').on('click',function(){
//alert("close");
this_data = $(this).siblings('.data').html();
alert(this_data);
$.get('/includes/sticky_notes/closeMessage.php',{
sequence : this_data
});
alert("close");
});
});
In this example we store the data in a variable this_data = $(this).siblings('.data').html(), so we refer to the element that was clicked - $(this) and then go down in the tree until the next element with the class data.
One last thing - consider to use $('.closeMessage').on instead of live as it has been deprecated - http://api.jquery.com/live/
Related
I have a table containing data read from a MySQL database via PHP. The first column holds all item names. Now, on clicking a td element in the first column of the table would link to a page with more detailed information about the item contained in the td.
Now I came up with the following idea:
$(document).ready(function() {
$('#table td:first-child').click(function() {
$('div.main').animate({
height: "50px"
}, 600);
setTimeout(function() {
$('div.data').fadeIn(1000);
}, 600);
});
});
div.main is the div-container that has the table included. What I want to do now is to slide that container up and fade a new div-container in, right below it, the new container include()s a PHP page which holds a dynamic query (pseudocode, no string escaping, simplified version):
SELECT detail FROM items WHERE items.name = $_GET['name'];
What I couldn't figure out is if and how I can tell the PHP file that is included in the in-fading div-container which item name it has to grab details for, off the database.
Right now I can read the item name via JavaScript/jQuery, but I couldn't figure a way out to pass that value to the PHP file without having to reload the page.
Any ideas or suggestions welcome!
I think what you're looking for is asynchronous JavaScript and XML (AJAX). It sounds intimidating, but fortunately jQuery makes it very easy.
You can call $.ajax() directly, but for most cases, you can use one of the convenience wrappers. In this case, I think $.load() will meet your needs.
So, let's say your PHP file is called detail_ajax.php and it returns the HTML you wish to put in your div (with class data). All you would have to do then is this:
$('div.data').load( '/detail_ajax.php', function(data){
$(this).html(data);
});
If you want to pass data TO detail_ajax.php, you can pass it along this way:
$('div.data').load( '/detail_ajax.php', { 'someField' : 'someValue' },
function(data) {
$(this).html(data);
}
});
In detail_ajax.php, if you examine $_POST['someField'], you will see the value passed in.
You can do this by using ajax. Output your query on a separate page in JSON format then fetch it using jquery ajax
you need to use ajax to do the same thing. create an event like onclick and call a
method on click call ajax set variable in js and pass it to and do as you want,
show data in particular div in response. Hope it will help you.
You are looking for $.ajax(). However, 3 things will need to take place for this to happen as you intend.
First, we need a reference held in the HTML that is generated by the table so we can streamline the server request. When you generate the table, add a unique data-name string to the TD.
<td data-name="<?php echo $row['name']; ?>">
If, for instance, the td's were generated in a foreach loop, where we expect an array to be returned.
Now, we need to detect the request on our page so we can properly return the data to the browser, we'll look for $_GET['name'] as per your example.
<?php
if(isset($_GET['name'])):
$mysqli = new mysqli('host', 'user', 'pass', 'db');
$ret;
if($stmt = $mysqli->prepare('SELECT detail FROM items WHERE items.name = ?')):
$stmt ->bind_param('s', $_GET['name']);
$stmt ->execute();
$stmt ->bind_result($details); // we only want one column
$stmt ->fetch(); //get our row
$ret['success'] = TRUE;
$ret['html'] = '<div>'. $details .'</div>';
else:
$ret['success'] = FALSE;
endif;
echo json_encode($ret); //return to the browser
endif;
?>
Now we need to employ ajax to bridge the gap between the server and the browser.
Edit - I forgot to modify the click function.
$('#table td:first-child').click(function() {
$('div.main').animate({
height:'0px'
}, function(){
//once the animation completes
$.ajax({
url: '/',
type: 'GET', //this is default anyway
data:{name: $(this).data('name')}, //send the name from the td clicked
dataType: 'json', //what we expect back from the server
success: function(data){ //will fire when complete. data is the servers response
if(data.success !== false){
$('div').html(data.html);
$('div.main').animate({
height: "50px"
}, 600);
}else{
alert("Something went wrong");
}
}
});
}, 600);
});
I am having a problem with setInterval in the $(document).ready(function(){}
What I am doing is setting the interval to do is call a PHP script that runs some MySQL queries to check the condition of 4 switches and then updating the screen with the values are in the database like so:
$(document).ready(function(){
setInterval(function(){
<?php require('fetchSwitchStatuses.php'); ?>
$("#switch1").css('background', 'rgb(<?php echo $switchColor1 ?>)');
$("#switch1").html('<?php echo $switchState1 ?>');
$("#switch2").css('background', 'rgb(<?php echo $switchColor2 ?>)');
$("#switch2").html('<?php echo $switchState2 ?>');
$("#switch3").css('background', 'rgb(<?php echo $switchColor3 ?>)');
$("#switch3").html('<?php echo $switchState3 ?>');
$("#switch4").css('background', 'rgb(<?php echo $switchColor4 ?>)');
$("#switch4").html('<?php echo $switchState4 ?>');
},1000);
});
Here is the code for fetchSwitchStatuses.php:
$connect = mysqli_connect("localhost", "root", "root");
mysqli_select_db($connect, "db_name");
$fetch1 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '3'"
);
$fetch2 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '5'"
);
$fetch3 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '6'"
);
$fetch4 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '9'"
);
$i = 1;
while($row = mysqli_fetch_array(${'fetch'.$i}))
{
if($row['SwitchStatus'] == 0)
{
${'switchColor'.$i} = "255, 0, 0";
${'switchState'.$i} = "OFF";
}
else if ($row['SwitchStatus'] == 1){
${'switchColor'.$i} = "0, 255, 0";
${'switchState'.$i} = "ON";
}
else {
${'switchColor'.$i} = "100, 100, 100";
${'switchState'.$i} = "ERROR";
}
$i++;
}
mysqli_close($connect);
When the page is loaded the information is correct, whatever is in the database is what is reflected by the colors on the screen.
When I click on the object to change the value, all of the necessary changes are made and the database is updated. However, the problem arises when the Interval is repeated. The values are switched back to whatever the original values were when the page was loaded. So, although the information is correctly changed in the database, for some reason the colors of the buttons is always reset to the first value read by the queries.
How can I fix this so that the information that is reflected on the screen is accurate?
With AJAX technology you can:
Send a request and get results from server by requesting a page (a .txt .js .html or even php).
So with AJAX you can get result of a page save something to database, get something from data base, you can work with sessions and anything you can do with a php file.
When you send an AJAX request to a see a page(i.e /userData.php?userId=5) the page /userData.php?userId=5 will be executed and its output will be returned.(HTML or just a word ‘yes’ or ‘no’ or ‘you can’t access to this user’s information’).
You can send data to file with POST or GET. But the question is how you can get data from page. Because the result AJAX will give you is what the requested page echoed to page like this
<html>
….
</html>
Or
‘Yes’
Or
<?php echo ‘something’; ?>
So what about getting a row of Date or lots of data? Because the only thing you are getting is a text or maybe a long text.
For that you can use JSON which Is something like nested arrays.
[
{
"term": "BACCHUS",
"part": "n.",
"definition": "A convenient deity invented by the...",
"quote": [
"Is public worship, then, a sin,",
"That for devotions paid to Bacchus",
"The lictors dare to run us in,",
"And resolutely thump and whack us?"
],
"author": "Jorace"
},
…
And this is a string too. But you can get Data in it with $.getJSON in jQuery and you can generate JSON data in server side like this.
<?php
$arr=array(
‘data’=>’ffff’,
‘anotherData’=>array(‘rrrrr’,’sssss’);
);
Echo json_encode($arr);
?>
Json_encode() in PHP gets an array and returns json string of it. And we echo it.
Now we can use jQuery to get Data which will be retrieved from server.
This section if from
Learning jQuery 1.3
Better Interaction Design and Web Development with Simple JavaScript Techniques
Jonathan Chaffer
Karl Swedberg
Global jQuery functions
To this point, all jQuery methods that we've used have been attached to a jQuery object that we've built with the $() factory function. The selectors have allowed us to specify a set of DOM nodes to work with, and the methods have operated on them in some way. This $.getJSON() function, however, is different. There is no logical DOM element to which it could apply; the resulting object has to be provided to the script, not injected into the page. For this reason, getJSON() is defined as a method of the global jQuery object (a single object called jQuery or $ defined once by the jQuery library), rather than of an individual jQuery object instance (the objects we create with the $() function).
If JavaScript had classes like other object-oriented languages, we'd call $.getJSON() a class method. For our purposes, we'll refer to this type of method as a global function; in effect, they are functions that use the jQuery namespace so as not to conflict with other function names.
To use this function, we pass it the file name as before:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json');
return false;
});
});
This code has no apparent effect when we click the link. The function call loads the file, but we have not told JavaScript what to do with the resulting data. For this, we need to use a callback function.
The $.getJSON() function takes a second argument, which is a function to be called when the load is complete. As mentioned before, AJAX calls are asynchronous, and the callback provides a way to wait for the data to be transmitted rather than executing code right away. The callback function also takes an argument, which is filled with the resulting data. So, we can write:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
});
return false;
});
});
Here we are using an anonymous function as our callback, as has been common in our jQuery code for brevity. A named function could equally be provided as the callback.
Inside this function, we can use the data variable to traverse the data structure as necessary. We'll need to iterate over the top-level array, building the HTML for each item. We could do this with a standard for loop, but instead we'll introduce another of jQuery's useful global functions, $.each(). We saw its counterpart, the .each() method, in Chapter 5. Instead of operating on a jQuery object, this function takes an array or map as its first parameter and a callback function as its second. Each time through the loop, the current iteration index and the current item in the array or map are passed as two parameters to the callback function.
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
$('#dictionary').empty();
$.each(data, function(entryIndex, entry) {
var html = '<div class="entry">';
html += '<h3 class="term">' + entry['term'] + '</h3>';
html += '<div class="part">' + entry['part'] + '</div>';
html += '<div class="definition">';
html += entry['definition'];
html += '</div>';
html += '</div>';
$('#dictionary').append(html);
});
});
return false;
});
});
Before the loop, we empty out so that we can fill it with our newly-constructed HTML. Then we use $.each() to examine each item in turn, building an HTML structure using the contents of the entry map. Finally, we turn this HTML into a DOM tree by appending it to the .
This approach presumes that the data is safe for HTML consumption; it should not contain any stray < characters, for example.
I have a web page that lists a number of companies from a MYSQL database, the listing just shows the name of the company. When user clicks on the company name a jquery accordion slider shows the rest of the information about that company.
When company name is clicked it also sends a request to a php script to log that a person has viewed that company's details.
My Problem
I want to send the ID for each record to the php script.
I have achieved this by including the accordion jquery code within the while loop that reads the output of the mysql query, but it generates a lot of unnecessary source code (i.e. for each company listed).
I need to include the jquery accordion code outside of the while statement.
How do I pass the id of each database record (i.e. company name) to the $.post in the jquery code, when it is outside of the while loop?
Accordion Jquery code
$(document).ready(function() { $('div.listing> div').hide(); $('div.listing> h4').click(function() {
$.post("/record.php", { id: "<?php echo $LM_row02[id]; ?>" } )
var $nextDiv = $(this).next();
var $visibleSiblings = $nextDiv.siblings('div:visible');
if ($visibleSiblings.length ) {
$visibleSiblings.slideUp('fast', function() {
$nextDiv.slideToggle('fast');
});
} else {
$nextDiv.slideToggle('fast');
} }); });
Any idea most welcome.
When you create the HTML (I assume you do that in the loop as well), add a data-* attribute with the ID as value to the element and read that value with jQuery when the element is clicked on.
E.g. your resulting HTML will look like:
<h4 data-id="123">Some title</h4>
and your JavaScript:
$('div.listing > h4').click(function() {
$.post("/record.php", { id: $(this).attr('data-id') }, function() {
// ...
});
});
When you create the h4 element in html add a html5 data attribute like
<h4 data-companyid="<?php echo $LM_row02[id]; ?>">Company Name</h4>
Then use that companyid in your ajax call like
$.post("/record.php", { id: $(this).data('companyid') } );
I have a while loop which creates a list of anchor tags each with a unique class name counting from 1 to however many items there are. I would like to change a css attriubute on a specific anchor tag and class when it is clicked so lets say the background color is changed. Here is my code
while($row = mysql_fetch_array($results)){
$title = $row['title'];
$i++;
echo "<a class='$i'>$title</a>
}
I would like my jquery to look something like this, it is obviously going to be more complicated than this I am just confused as where to start.
$(document).ready(function() {
$('a .1 .2 .3 .4 and so on').click(function() {
$('a ./*whichever class was clicked*/').css('background':'red');
});
});
Can you give the class a more consistent name? Like myClass_1, myClass_2, etc.
Then you could do:
$(document).ready(function() {
$('a[class^=myClass_]').click(function() { // Assign handler to elements with a
// class that starts with 'myClass_'
$(this).css('background','red'); // Change background of clicked one.
});
});
Here, a "starts with" selector is used to assign the event to all classes that start with myClass.
You could still retrieve the index number if needed.
Within the event handler, $(this) refers to the one that was clicked.
Live Example: http://jsfiddle.net/Jurv3/
Docs for "starts with" selector: http://api.jquery.com/attribute-starts-with-selector/
EDIT: I had a missing ] in the selector. Fixed now.
You can use an iterator over an array like this:
var myclasses = [".1",".2",".3"]; // generated by php
$.each(myclasses, function(index, value) {
$('a '+value).click(function() {
$(this).css('background':'red');
});
});
Note: I think you might be better off using unique ID for each item in your list of anchor tags and have them all share a single class. That's more what classes and IDs are for.
Just give them all the same class, say, myClass. Then:
$('a.myClass').click(function () {
$(this).css('background':'red');
});
This will work as long as you're having the links operate on themselves, or on their parents - as long as the relationship between link and target is the same for each. To operate on the parent, it would be $(this).parent().css(...), and to operate on the next element it would be $(this).next().css(...) and so on.
have you tried something like this?
while($row = mysql_fetch_array($results)){
$title = $row['title'];
$i++;
echo '<a class="anchor_link" id="'.$i.'">'.$title.'</a>';
}
And then for the jQuery:
$(document).ready(function() {
$('a.anchor_link').click(function() {
var thisAnchor = $(this).attr('id');
$(this).css('background':'red');
});
});
The reason for my adding the js var 'thisAnchor' is because I am assuming that you need that $i php variable as the anchor marker? if so you can just take the js var and use it however you need. if you can't use ID because the anchored content is marked by id, use a diferent attr, such as 'title' or 'alt'.
I hope this was helpful.
I am trying to send a php script some content to be stored in a database via ajax. I am using the jQuery framework. I would like to use a link on a page to send the information. I am having trouble writing the function that will send and receive the information, everything that I have tried is asymptotic.
EDIT
The idea is that the user will click the link, and a column called "show_online" (a tiny int) in a table called "listings" will update to either 1 or 0 (**a basic binary toggle!) On success, specific link that was clicked will be updated (if it sent a 1 before, it will be set as 0).
EDIT
There will be 20-30 of these links on a page. I have set each containing div with a unique id ('onlineStatus'). I would rather not have a separate js function for every instance.
Any assistance is much appreciated. The essential code is below.
<script type="text/javascript">
function doAjaxPostOnline( shouldPost, bizID ){
load("ajaxPostOnline.php?b='+bizID+'&p='+shouldPost", jsonData, callbackFunction);
function callbackFunction(responseText, textStatus, XMLHttpRequest)
{
// if you need more functionality than just replacing the contents, do it here
}
}
}
</script>
<!-- the link that submits the info -->:
<div id='onlineStatus<?php echo $b_id ?>'>
<a href='#' onclick="doAjaxPostOnline( 0, <?php echo $b_id ?> ); return false;" >Post Online</a>
</div>
ajaxPostOnline.php
<!-- ajaxPostOnline.php ... the page that the form posts to -->
<?php
$id = mysql_real_escape_string($_GET['b']);
$show = mysql_real_escape_string($_GET['p']);
if( $id && ctype_digit($id) && ($show == 1 || $show == 0) ) {
mysql_query( "UPDATE listing SET show_online = $show
WHERE id = $id LIMIT 1" );
}
if($result) {
if($show == '0'){
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, <?php echo $b_id ?> ); return false;' >Post Online</a>";
}
if($show == '1'){
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 0, $b_id ); return false;' >Post Online</a>";
}
print json_encode(array("id" => $id, "return" => $return));
}
?>
The load() function in jQuery is really cool for this sort of thing.
Here's an example. Basically, you have an outer div as a container. You call a script/service which returns html. You have a div in that html with an id that you will refer to later in the ajax call. The replacement div replaces the inner html of the container div. You pass your data as a json object as the second parameter to the load method, and you can pass a reference to a callback function as the third parameter. The callback function will receive every possible piece of information from the response (the full response text for further parsing/processing, the http status code, and the XMLHttpRequest object associated with this ajax call).
$("#id_of_some_outer_div").load("somepage.php #id_of_replacement_div", jsonData, callbackFunction);
function callbackFunction(responseText, textStatus, XMLHttpRequest)
{
// if you need more functionality than just replacing the contents, do it here
}
so, in your case you're talking about replacing links. Put the original link inside of a div on both sides of the operation.
Here's the link to the jQuery api doc for load():
load
EDIT:
In response to your comment about doing multiple replacements in one pass:
You can have the callback function do all the work for you.
Add a unique css class to all divs that need replacing. This will allow you to select all of them in one shot. Remember that html elements can have more than one css class (that's what the "c" in CSS means). So, they'd all be <div id="[some unique id]" class="replace_me"... Then, if you have a variable set to $("div.replace_me"), this will be a collection of all divs with the replace_me style.
Whatever elements that come from the ajax call (whether they're another div container or just a single "a" element) should have a unique id similar to the container they're to be inserted into. For example, div_replace1 would be the id of a container and div_replace1_insert would be the id of the element to be inserted
Inside the callback function, iterate over the replacements using $("div.replace_me").each(function(){ ...
Inside each iteration the "this" keyword refers to the current item. You can grab the id of this item, have a variable like var replacement_id = this.id + "_insert"; (as in the example above) which is now the unique id of the element you'd like to insert. $("#" + replacement_id) will now give you a reference to the element you want to insert. You can do the insertion something like this: this.html( $("#" + replacement_id) );
You may have to edit the code above (it's not tested), but this would be the general idea. You can use naming conventions to relate elements in the ajax return data to elements on the page, iterate the elements on the page with "each", and replace them with this.html()
did you really mean to declare your ajax success return function as
function(html)
? .. i think maybe you mean for the param to be 'data' ?
Since your php script is returning json you should set the dataType to json. Note that in your posted code sample, the success function() was outside of the $.ajax() and it needs to be inside.
$.ajax({
url: "ajaxPostOnline.php?b=" + bizID + "&p=" + shouldPost,
dataType: "json",
success: function(json){
$("#onlineStatus" + bizID).html(json.return);
}
});
You might want to check out the getJSON method since it's more concise for this particular situation.
$.getJSON("ajaxPostOnline.php", {b:bizID, p:shouldPost}, function(json) {
$("#onlineStatus" + bizID).html(json.return);
});
EDIT: Original question was edited and the provided sample changed significantly. I would still recommend the $.getJSON method.
Unless I am mistaken, it seems you have an error mixing AJAX and server-side scripting.
That depends on whether $return is PHP parsed anywhere after assignment snippet in ajaxPostOnline.php (hardly, if it is called from AJAX!).
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, <?php echo $b_id ?> ); return false;' >Post Online</a>";
Surely this should be:
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, ".$id." ); return false;' >Post Online</a>";