i have 2 functions
1- addMessage(): save data into database and is called only on click .
2-updateMessage():get data with ajax from database, called when document is ready ,called every 3 seconds for new data, and called on success of addMessage().
function updateMessage()
{
$.ajax({
url:"db.php",
type:"post",
dataType:"text/xml",
success:function(data)
{
$(data).find("message").each(function() {
var msg_id = $(this).find("msg_id").text();
var date_time = $(this).find("date_time").text();
var from_user = $(this).find("from_user").text();
var from_group = $(this).find("from_group").text();
var to_user = $(this).find("to_user").text();
var to_group = $(this).find("to_group").text();
var msg_type = $(this).find("msg_type").text();
var msg = $(this).find("msg").text();
var grp_abr = $(this).find("grp_abr").text();
var html = "<tr class='blue'>";
html += "<td><a href='#' class='bullet' onclick='changeStatus(\""+msg_id+"\")'><\/a><\/td>";
html += "<td><a href='#' class='reply' onclick='reply(\""+from_user+"\");'><\/a><\/td>";
html += "<td>"+date_time+"<\/td>";
html += "<td>"+from_user+"["+from_group+"]"+"<\/td>";
html += "<td>"+to_user+"["+to_group+"]"+"<\/td>";
html += "<td><a href='#' class="+msg_type+"><\/a><\/td>";
html += "<td><a href='#' class='flag_msg' onclick='flagMsg("+msg_id+")'><\/a><\/td>";
html += "<td>"+msg_id+msg+"<\/td>";
html += "<td>"+grp_abr+"<\/td><\/tr>";
});
}
});
setTimeout('updateMessage()',3000);
}
Now the data retrieved i want to add to different tabs with different names and different containers, how would i do that. My question isn't a matter of code, it is more about logic or sequence of steps.
Any help please.
Not sure I understand what you really want. Assuming you are asking how you can add tabs dynamically
Look into the jQuery Tabs add() method and maybe the tabTemplate and panelTemplate options.
At the end of your success function when you have constructed the new tab content append it somewhere suitable in the DOM (e.g. hidden table which holds all tabs) and the just use the add method.
If you have multiple tab-containers just call the add-method on the one you want.
Related
Ive spent several hours trying to resolve an issue with very limited experience with jQuery which is not helping me.
I am wanting to search a database for a list of results using a few input fields and then a submit button, when you click submit the values are passed to a .php script which returns the results and these are displayed in a table within a div container which works perfect.
Each record is then displayed in its own row within the table, with columns for different data.
record number
name
town
What i want is for the record number to be a click link of some kind, which when clicked, it then passes that value and does a different mysql request displaying that unique records data in more detail in a different div container. This is the part i cant get to work as i believe its something to do with BINDING, or the .ON which i dont really know anything or understand how it works, as my experience is very limited.
<script type="text/javascript">
$(document).ready(function() {
$(".click").click(function() {
var name = $("#name").val();
var name = $(this).attr("id");
$('#2').load("mysqlrequest_unique.php?recordid=" +name);
});
$("#get").click(function() {
var sales_record_number = "sales_record_number=" + $("#sales_record_number").val() + "&";
var item_id = "item_id=" + $("#item_id").val() + "&";
var user_id = "user_id=" + $("#user_id").val() + "&";
var buyer_fullname = "buyer_fullname=" + $("#buyer_fullname").val() + "&";
var sale_date = "sale_date=" + $("#sale_date").val() + "&";
var paypal_transaction_id = "paypal_transaction_id=" + $("#paypal_transaction_id").val() + "&";
var ship_to_zip = "ship_to_zip=" + $("#ship_to_zip").val() + "&";
var item_title = "item_title=" + $("#item_title").val() + "&";
$('#1').load("mysqlrequest_all.php?"+sales_record_number+item_id+user_id+buyer_fullname+sale_date+paypal_transaction_id+ship_to_zip+item_title, function(){
var name = $("#name").val();
var name = $(this).attr("id");
$('#2').load("mysqlrequest_unique.php?recordid=" +name);
}
);
});
});
</script>
<div id="1" name='container_display_all'></div>
<div id="2" name='container_display_unique'></div>
This is what each row would have in the table, which doesnt work when its contained in generated html using a jQuery
<a class = 'click' id = '19496'>19496</a>
This isn't working because you are adding html elements dynamically and the event handlers aren't being added to the dynamically added elements.
$(document).ready(...) is only run when the document loads. So if all the elements that have the class click are being added dynamically, this bit of code $(".click") (inside $(document).ready(...) ) will return a jquery object that contains no elements (as there are currently none in the DOM with the class click).
Then later your elements (with class click) are added to the DOM but have no handlers on them. What you need to do is set the handlers for those object when you add them.
So change this line:
$('#1').load("mysqlrequest_all.php?"+sales_record_number+item_id+user_id+buyer_fullname+sale_date+paypal_transaction_id+ship_to_zip+item_title);
to this:
$('#1').load("mysqlrequest_all.php?"+sales_record_number+item_id+user_id+buyer_fullname+sale_date+paypal_transaction_id+ship_to_zip+item_title, function(){
$(".click").click(function() {
var name = $("#name").val();
var name = $(this).attr("id");
$('#2').load("mysqlrequest_unique.php?recordid=" +name);
});
}
);
This code will execute the function that is passed once the new html is loaded into the first div, which will add the needed handlers to the new elements.
I can't find/think of a way to solve this problem.
I have a list of links outputted by a php script and I need to get the text value from the item (link) that's been clicked.
Here is the php part that outputs data:
$query = mysql_query("SELECT NAME FROM ccm WHERE NAME LIKE '$value%'");
while( $run = mysql_fetch_array($query)){
$name = $run['NAME'];
echo '<a id="rez_link" onClick="klik();">'.$name.'</a>';
}
And here are some of my attempts to fetch the .text() from the link that's been clicked:
var value = $('a#rez_link').text(); //this one targets every text if there are multiple search result from the query
var value = jQuery(this).find("a").text(); //this one returns nothing
So how do I do it?
Maybe I should modify the php script so that it outputs new links with id=""+i and then target them like that in jQuery or something like that.
Is there a simple way to do this?
You can't have more anchor tags with same id
echo '<a id="rez_link" onClick="klik();">'.$name.'</a>';
it's better to use class instead
echo '<a class="rez_link">'.$name.'</a>';
$(function() {
$(".rez_link").on("click",function()
{
var text = $(this).text();
alert(text);
}
});
$(function() {
$('.rez_link').bind('click', function(e) {
e.preventDefault();
var linkText = $(this).text();
$('#show').text(linkText);
});
});
It's this what you try to do ?
How to add the value of php variabele to jquery variable and adds them,i have a form that will take a value and post to second page where second page contains a div panel where the form checkboxes values are adding and subtracting,basically i want to add the submitted value from page1 to page2.Here is the code.I have 3 form values which will be redirected one by one.Whenever user submits the respective button
if($_POST['submit'])
{
$beg=$_POST['basic'];
}
function refreshPrices() {
var currentTotalValue = 0;
var beg=?????
$("#results div").each(function() {
if (!isNaN(parseInt($(this).find("span").text().substring(1)))) {
currentTotalValue += parseInt($(this).find("span").text().substring(1));
}
});
$("#totalValue").text("$" + currentTotalValue)
}
var beg=<?php echo $beg; ?>
Try this:
var beg = '<?php echo $beg ;?>';
if you want to add to the total value you can do this:
currentTotalValue = currentTotalValue + parseInt(beg);
its better to do it this way :
var js_var = '<?=json_encode($php_var);?>';
This way you will be able to transfer any type of data to js (arrays, objects, strings, etc.) and access it easily like this:
js_var['element']
var beg = '<?php echo $beg ;?>';
But this can be only one once during the load of the page. After that we cant assign a server side script to js.
Retrieve value by input class or id like dat
var beg = $("#basic").val();
Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/
please take a look of this:
$(function () {
$("#add").click(function() {
val = $('#add_lang').val();
val1 = $('#add_lang_level').val();
listitem_html = '<li>';
listitem_html += val + ' <strong>('+ val1 + '/100)</strong>';
$.ajax({ url: 'addremovelang.php', data: {addname: val,addlevel: val1}, type: 'post', success: function(output) { alert(output); }});
listitem_html += 'Remove'
listitem_html += '</li>';
$('#langs').append(listitem_html);
});
$('.remove_lang').live('click', function(e) {
e.preventDefault();
$(this).parent().remove();
$.ajax({ url: 'addremovelang.php', data: {delname: val}, type: 'post', success: function(output) { alert(output); }});
});
});
This simple jquery script adds strings to a html list when the user hits the button with the id add. Also, it puts a remove link to each line, so when the user hits remove it triggers the function remove_lang and the string is deleted.
When the users add a string, this text comes from a text field, and i stored it on the variable val (as you can see on the 5 line of the code). Then i call a php script via Ajax to add this info to my mysql database.
But, when the user remove the string, i dont know how to know what string was removed, i mean, the name of this one, that i need to send to my php script in order to remove it from the database.
Take a look of this version of my code without the ajax call: http://jsfiddle.net/wnFsE/
Thanks for any help!!!
When you click remove you can do something like this:
val = $(this).parent().find('input').val();
That will get the value from hidden input you added:
Demo Here
You need to think about the string as instead a group of elements:
var li = $('<li/>');
var strong = $('<strong/>', { text: '(' + val1 + '/100)' });
var link = $('<a/>');
link.click(function()
{
// Insert code here for the link click
});
li.append(strong).append(link);
$('#langs').append(li)
There are other patterns that would work too, like:
$(listitem_html').find('a').click(function()
{
// Insert code here for the link click
});
Just get a reference to the element, and then attach the click event handler.
An Object Oriented Programming approach would help keep the actions very organized. You basically store the actions for each given language in an object, modifying the action for that language whenever it's removed or added.
Here's a live example that will print that "storage" object out to the console every time you add or remove a language so that you can clearly see what's going on.
And here's just the JS code (you'll notice that I barely changed a thing):
languageActions = {}
$(function () {
$("#add").click(function() {
val = $('#add_lang').val();
listitem_html = '<li>';
listitem_html += val;
listitem_html += '<input type="hidden" name="languages[]" value="' + val + '" /> ';
listitem_html += 'Remove'
listitem_html += '</li>';
$('#langs').append(listitem_html);
//now add it to our object
languageActions[val] = 'add';
console.log(languageActions);
});
$('.remove_lang').live('click', function(e) {
e.preventDefault();
val = $(this).prev().val();
$(this).parent().remove();
//now change it's value in languageActions
languageActions[val] = 'remove';
console.log(languageActions);
});
});
The only other thing I'll point out is that you don't really need that hidden input element since you're doing this via AJAX rather than a standard form submit. Instead, you could just do <li><span>Spanish</span><a class="remove_lang">Remove</a></li> for your HTML and then the click event on .remove_lang would do $(this).prev().text() rather than $(this).prev().val(). Not a huge deal, but you're HTML will be a little cleaner.
I guess that would be a simple:
$i = 1;
while(xxx){
//get the list with a different value for each element
echo '<div id="add_' . $i . '>$whatever</div>';
$i++;
}